标签: testbook

使用 testbook 测试 Jupyter notebook 单元时如何修补 input()?

我参与的一个项目使用testbook来测试 Jupyter 笔记本的代码单元。修补工作正常吗?—?除非要测试的代码要求用户输入input(). 我只是不知道如何正确修补它。

使用的版本:Python:3.8.10,测试书:0.4.2

要在 Jupyter 代码单元中测试的代码,标记为name_checking

def fix(text):
    return text.strip().title()

def check(text):
    return len(text) > 1

firstname = input("What's your first name?")
lastname = input("What's your last name?")
fixed_first = fix(firstname)
fixed_last = fix(lastname)
if check(fixed_first) and check(fixed_last):
    print(f"Your name is {fixed_first} {fixed_last}.")
else:
    print("You entered an invalid name.")
Run Code Online (Sandbox Code Playgroud)

尝试 1:测试代码补丁 builtins.input

@testbook(path)
def test_name_checking1(tb): # execute cell tagged "name_checking"
    with tb.patch("builtins.input") as mock_input:
        mock_input.return_value = ["   haRrY   ", " …
Run Code Online (Sandbox Code Playgroud)

python testing monkeypatching jupyter-notebook testbook

3
推荐指数
1
解决办法
29
查看次数