<p>所以我的方法是用<a href="https://pytest.org" rel="nofollow">pytest</a></p>
<p><strong>示例:</strong>(<em>人为</em>)</p>
<pre><code>from subprocess import Popen, PIPE
def test():
p = Popen(["echo", "Hello World!"], stdout=PIPE)
stdout, _ = p.communicate()
assert stdout == b"Hello World!\n"
</code></pre>
<p><strong>输出:</strong></p>
<pre><code>$ py.test -x -s test_subprocess.py
======================================= test session starts ========================================
platform linux2 -- Python 2.7.9 -- py-1.4.28 -- pytest-2.7.1
rootdir: /home/prologic/work/circuits, inifile:
plugins: cov
collected 1 items
test_subprocess.py .
===================================== 1 passed in 0.01 seconds =====================================
</code></pre>
<hr/>
<p>或者使用标准库<a href="https://docs.python.org/2/library/unittest.html" rel="nofollow">unittest</a>:</p>
<p><strong>示例:</strong></p>
<pre><code>#!/usr/bin/env python
from unittest import main, TestCase
from subprocess import Popen, PIPE
class TestProcess(TestCase):
def test(self):
p = Popen(["echo", "Hello World!"], stdout=PIPE)
stdout, _ = p.communicate()
self.assertEquals(stdout, b"Hello World!\n")
if __name__ == "__main__":
main()
</code></pre>
<p><strong>输出:</strong></p>
<pre><code>$ python test_subprocess.py
.
----------------------------------------------------------------------
Ran 1 test in 0.001s
OK
</code></pre>