![](/img/trans.png)
[英]Python subprocess with /usr/bin/time: How can I capture timing information, but ignore all other output?
[英]Pytest: How can I blindly run any subprocess and capture all output?
我有一個 Python 程序,它調用print()
和/或調用 subprocess.Popen subprocess.Popen()
對其他幾種語言的腳本,它也可以print, console.log, system.out.println,
等。實際的程序很容易打印所有this 到終端,這是預期的行為。
對於集成測試,我想捕獲所有這些 output 以檢查它是否與預期值匹配。 我無法模擬子流程。 這不是單元測試,我不在乎我的 Python 代碼實際上在做什么,只是 output 是正確的。
所有這些選項都適用於捕獲內部 Python output:
capfd
夾具直接用Pytest捕獲並讀取所有outputcontext_lib
和redirect_stdout
sys.stdout
重新分配給顯式文件,然后讀取此文件以獲取 output 代碼大致如下。 對於capfd
和redirect_stdout
,您只需在run_string
之前和之后改變您所做的事情。
# tests are parametrized from several JSON files.
def test_code(test_json):
with open("/tmp/output_file.txt", "w+") as output_file:
orig_stdout = sys.stdout
sys.stdout = output_file
print("initial")
run_string(test_json["code"])
output_file.seek(0)
sys.stdout = orig_stdout
output = output_file.read()
assert output == test_json["expected"]
這些都完美地獲得了內部 output ,但都無法從 subprocess.Popen 獲得一致的subprocess.Popen
。 我嘗試使用所有這些方法,將subprocess.stdout
設置為文件,設置為PIPE
並稍后將其打印出來, shell=True
和其他一些東西,但它們都有相同的奇怪問題。 我真的對這種行為沒有任何解釋,所以我只是希望有人能幫助我:
pytest
時則無效。 嗯? 為什么?????!?我也可以嘗試測試整個 CLI,但我想避免這種情況,而且我不確定它是否能正常工作。 如果有人知道如何強制 Pytest 像本機代碼一樣運行而不將子進程放在某種盒子中,那真的是我需要的。
對於那些想知道的人,我最終選擇了capfd
鈎子,並完全刪除了嵌套的子進程要求。 我的應用程序需要執行的子進程不再允許output 直接到shell,特別是因為它是如此不一致。 這是我最終得到的最終代碼。
def test_dits(dit_json, capfd):
if "long" in dit_json and not pytest.all_val: # type: ignore
pytest.skip("Long test")
run_string(dit_json["dit"], "tests/fail.dit")
output, err = capfd.readouterr()
assert output == dit_json["expected"]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.