如何使用输入调用测试功能?
我有一个用Python编写的控制台程序。它使用以下命令询问用户问题:
some_input = input('Answer the question:', ...)
如何测试包含对input
using的调用的函数pytest
?我不想强迫测试人员多次输入文本只是为了完成一次测试运行。
-
您可能应该模拟内置
input
功能,可以在每次测试后使用teardown
提供的功能pytest
还原为原始input
功能。import module # The module which contains the call to input class TestClass: def test_function_1(self): # Override the Python built-in input method module.input = lambda: 'some_input' # Call the function you would like to test (which uses input) output = module.function() assert output == 'expected_output' def test_function_2(self): module.input = lambda: 'some_other_input' output = module.function() assert output == 'another_expected_output' def teardown_method(self, method): # This method is being called after each test case, and it will revert input back to original function module.input = input
更好的解决方案是将
mock
模块与一起使用with statement
。这样,您就不需要使用拆解,并且修补的方法只会存在于with
范围内。import mock import module def test_function(): with mock.patch.object(__builtins__, 'input', lambda: 'some_input'): assert module.function() == 'expected_output'
-
使用用户输入来调用功能
2021-01-29 关注 0 浏览88 1答案
-
Wordpress:如何使用Ajax调用来调用插件功能?
2021-01-31 关注 0 浏览87 1答案
-
如何使用 httptest 在 Go 中测试 http 调用
2022-01-03 关注 0 浏览76 1答案
-
使用grunt-shell调用调用docker run的脚本时,如何解决“输入设备不是TTY”问题?
2021-02-01 关注 0 浏览112 1答案
-
如何使用Hibernate调用自定义数据库功能?
2021-02-01 关注 0 浏览147 1答案
-
测试调用:如何进行所有测试套件通用的设置
2021-01-30 关注 0 浏览82 1答案
-
如何在Go中测试HTTP调用
2021-02-01 关注 0 浏览110 1答案
-
如何使用Karma和Jasmine在角度服务中测试“私有”功能
2021-02-01 关注 0 浏览65 1答案
-
如何使用Jasmine进行测试,该AngularJS控制器调用返回Promise的服务方法
2021-02-01 关注 0 浏览54 1答案
-
使用jQuery测试输入是否具有焦点
2021-02-02 关注 0 浏览61 1答案