If you want to write UnitTest when using stdin in Python. Pytest provide setattr function in monkeypatch

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
from io import StringIO
import sys


def divide():
    input = sys.stdin.readline
    return list(input())


def gather():
    input = sys.stdin.readline
    return sum(list(map(int, input().split())))


def test_divide(monkeypatch):
    monkeypatch.setattr('sys.stdin', StringIO('abc'))
    assert divide() == ['a', 'b', 'c']


def test_gather(monkeypatch):
    monkeypatch.setattr('sys.stdin', StringIO('1 2 3'))
    assert gather() == 6

Reference

See Also

Support

記事をお読みくださりありがとうございます。このウェブサイトの運営を支援していただける方を募集しています。 もしよろしければ、下のボタンからサポート(投げ銭)していただけると、ブログ執筆、情報発信のモチベーションに繋がります✨