我正在编写一些测试,依靠用户输入来决定它们是否已通过。使pytest等待用户输入
我有这样的功能:
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
它运行良好,并且在每次试验后停下来获取用户输入。但是,我想用它设置了各种变量和标头日志文件(称为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()
当我这样运行它,它不会停止或运行任何测试。
如果我可以写入日志文件,同时也写入相同的东西到终端(包括用户输入),这将是伟大的。否则,正确调用这个函数的方法也会起作用。
单元测试的要点是它们不需要用户交互... –
此功能可以被测试的唯一方法就是这样,因为它可能是不正确的 –
您真的需要找到一种方法来模拟用户输入用于测试目的。如果您在测试过程中依赖用户输入,那么运行测试的其他人可能不会测试与您相同的内容。测试应该是确定性的。 – larsks