【发布时间】:2020-11-23 17:35:58
【问题描述】:
设置
我已将问题简化为核心:
- 已安装 pytest
pip install pytest==5.4.3
- 有一个shell脚本
# has-stdin.sh
# Detect stdin
if [[ ! -t 0 ]]; then
echo "yes"
else
echo "no"
fi
- 进行 Python 测试
# test.py
import subprocess
import unittest
class TestCase(unittest.TestCase):
def test(self):
process = subprocess.run(
["sh", "./has-stdin.sh"],
stderr=subprocess.PIPE,
stdout=subprocess.PIPE,
check=True,
shell=False
)
assert process.stdout.decode("utf-8") == "no\n"
测试
✅ 脚本在 bash shell 中工作
$ sh ./has-stdin.sh
no
$ echo '' | sh ./has-stdin.sh
yes
$ sh ./has-stdin.sh <<< ''
yes
✅ 使用-s 成功运行(例如--capture=no)
$ pytest test.py -s
platform linux -- Python 3.7.7, pytest-5.4.3, py-1.9.0, pluggy-0.13.1
rootdir: /Users/maikel/docker/library/postgresql
collected 1 item
test.py .
=========================== 1 passed in 0.02s ===========================
❌ 在没有-s 的情况下运行失败
$ pytest test.py
========================== test session starts ==========================
platform linux -- Python 3.7.7, pytest-5.4.3, py-1.9.0, pluggy-0.13.1
rootdir: /Users/maikel/docker/library/postgresql
collected 1 item
test.py F [100%]
================================ FAILURES ===============================
_____________________________ TestCase.test _____________________________
self = <test.TestCase testMethod=test>
def test(self):
process = subprocess.run(
["sh", "./has-stdin.sh"],
stderr=subprocess.PIPE,
stdout=subprocess.PIPE,
check=True,
shell=False
)
> assert process.stdout.decode("utf-8") == "no\n"
E AssertionError: assert 'yes\n' == 'no\n'
E - no
E + yes
test.py:23: AssertionError
======================== short test summary info ========================
FAILED test.py::TestCase::test - AssertionError: assert 'yes\n' == 'no\n'
=========================== 1 failed in 0.10s ===========================
????使用-s 有什么不同?如何在没有-s 的情况下成功运行这个pytest?
我尝试过Test calling of an external script run via Popen that expects no available data in stdin using pytest,但是当使用该方法时,两个pytest 命令都失败了。
【问题讨论】:
标签: python subprocess pytest