python - 让 pytest 等待用户输入

标签 python user-input pytest gui-testing

我正在编写一些依赖用户输入来决定是否通过的测试。

我有这个功能:

def viewable(actual_proj):
    print("\nCan you see %s projects named:\n"%len(actual_proj))
    for i in actual_proj:
        print (i+"\n")
    return input("(y/n)? : ")

内:

def is_present(pytestconfig, project_not_present = 0):

    actual_projects = all_projects.copy()
    if (project_not_present!=0):
        del_file = all_ini_files[project_not_present-1]
        os.rename(del_file, del_file +'_tst')
        del actual_projects[project_not_present-1]
    capmanager = pytestconfig.pluginmanager.getplugin('capturemanager')

    subprocess.Popen('./MultiPRM.exe')
    capmanager.suspendcapture(in_=True)

    decision = viewable(actual_projects)
    capmanager.resumecapture()
    if (project_not_present!=0):
        os.rename(del_file+'_tst', del_file)
    if (decision =='y'):
        return True
    else:
        return False

当我运行命令pytest name_of_test_file.py时,它运行良好,并在每次测试后停止以获取用户输入。但是,我想使用一个为日志文件设置各种变量和 header 的文件(称为 run_tests.py)

# start the report
print("Creating test report: " + os.path.abspath(report_filepath))
rep = open(report_filepath, "w")
rep.write(report_header)
rep.write("Test environment: \n");
rep.write("  Username: " + os.environ['USERNAME'] + "\n")
rep.write("Testing started at: " + get_time() + "\n\n")
rep.close()

# get application version
cmd = exe_under_test + " --help >> " + report_filepath
os.system(cmd)

# start the tests
cmd = "pytest >> " + report_filepath 
os.system(cmd)

# finalise the report
rep = open(report_filepath, "a+")
rep.write("\nTesting completed at: " + get_time() + "\n\n")
rep.close()

当我以这种方式运行它时,它不会停止或运行任何测试。

如果我可以写入日志文件,同时也可以将相同的内容写入终端(包括用户输入),那就太好了。否则,正确调用该函数的方法也可以工作。

最佳答案

您的测试应该尽可能容易运行,以便轻松执行它们。如果它们依赖于外部(例如用户的)输入和其他一些技巧来正确运行,那么从长远来看没有人会执行它们。

如果您是项目中的唯一开发人员,您可能可以接受它,但我想说这种方法是不正确的,并且不被认为是最佳实践

首先,如果您只是在控制台中等待用户的输入(这看起来像您的代码片段),那么只需模拟 input 内置并设置它的返回值,例如:

app.py

def my_input(prompt=''):
    try:
        return raw_input(prompt)
    except NameError:
        return input(prompt)


def my_great_func():
    choice = my_input('y/n?: ')
    return choice

测试.py

import unittest.mock as mock    
import pytest

from app import my_great_func

@pytest.yield_fixture
def fake_input():
    with mock.patch('app.my_input') as m:
        yield m


def test_my_great_func(fake_input):
    fake_input.return_value = 'y'
    assert my_great_func() == 'y'

测试执行:

$ pytest test.py -v
============================= test session starts ==============================
platform linux -- Python 3.5.2, pytest-3.2.1
cachedir: .cache
rootdir: /home/kris/projects/tmp, inifile:
collected 1 item                                                                

test.py::test_my_great_func PASSED

=========================== 1 passed in 0.01 seconds ===========================

其次,努力编写应用程序逻辑和 GUI 松散耦合的代码 - 这样您就可以测试您的逻辑,而无需考虑 GUI(无论是 Web、桌面还是移动应用程序)。

关于python - 让 pytest 等待用户输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46035759/

相关文章:

batch-file - 为什么这个批处理文件 "remember"用户输入?

asynchronous - 超时的用户输入无法按预期工作

python - py.test 2.3.5 : generative tests that use fixtures?

python - 具有全局范围的 py.test 固定装置

python - 带点的函数参数给出 SyntaxError

javascript - 在 node.js 中等待用户输入

python - 在没有任何 python 子包的情况下创建 pip 轮

pytest-dependency 在我的测试中不起作用

python - Pandas 数据框到字典的字典

python - 基于选择的列表理解