簡體   English   中英

Pytest 一個 function 打印到標准輸出

[英]Pytest a function that prints to stdout

def f(n):
    nuw = n.casefold()
    for i in ["a","e","i","o","u"]:
        nuw = nuw.replace(i,"")
    print(nuw)

if __name__=='__main__':
    ask = input("Word? ")
    f(ask)

這是根據文檔的解決方案:

def f(n):
    nuw = n.casefold()
    for i in ["a","e","i","o","u"]:
        nuw = nuw.replace(i,"")
    print(nuw)

def test_my_func_f(capsys):  # or use "capfd" for fd-level
    f("oren")
    captured = capsys.readouterr()
    assert captured.out == "rn\n"

當你運行它時,它很順利:

$ pytest --capture=sys main.py 
================================================== test session starts ===================================================
platform linux -- Python 3.10.4, pytest-7.1.2, pluggy-1.0.0
rootdir: /home/oren/Downloads/LLL
collected 1 item                                                                                                         

main.py .                                                                                                          [100%]

=================================================== 1 passed in 0.01s ====================================================

雖然完全可以測試實際發送到標准輸出的內容,但這不是推薦的方式。

相反,請設計您的函數,以便它們返回結果。 即,正如另一位評論者所寫,它們沒有副作用 優點是,像這樣的函數(“純函數”)非常容易測試:它只是為您提供 output — 每次相同的輸入都應該是相同的 output。

然后,最后,要從您的程序中實際生成 output,請在頂層執行 IO。 例如,在main()或其他一些頂級函數/文件中。 當然,如果它很重要,你也可以測試它。 但我發現測試較低級別的函數(這很容易做到)讓我有足夠的信心相信我的代碼可以正常工作。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM