与正在运行的代码交互
title: 与正在运行的代码交互
如果您需要异步测试代码或在终端窗口中与它交互,您可以使用 .running_code() 获取 RunningCode 对象。
从 RunningCode 对象中,您可以使用 .iprocess 获取一个 icommandlib iprocess 对象。
"long_string" 设置为
import sys
import time
answer = input("favorite color:")
with open("color.txt", "w") as handle:
handle.write(answer)
answer = input("favorite movie:")
with open("movie.txt", "w") as handle:
handle.write(answer)
time.sleep(0.5)
sys.exit(0)
from hitchrunpy import ExamplePythonCode
from ensure import Ensure
import hitchbuildpy
import hitchbuild
BUILD_DIR = "/path/to/build_dir/.."
virtualenv = hitchbuildpy.VirtualenvBuild(
"/path/to/build_dir/../py3.7",
base_python=hitchbuildpy.PyenvBuild(
'/path/to/share_dir/../pyenv3.7',
"3.7",
),
)
virtualenv.verify()
pyrunner = ExamplePythonCode(
virtualenv.bin.python,
'/path/to/working_dir',
)
running_code = pyrunner.with_code(long_string).with_terminal_size(10, 10).running_code()
assert not running_code.finished
running_code.iprocess.wait_until_output_contains("favorite color:")
running_code.iprocess.send_keys("red\n")
running_code.iprocess.wait_until_output_contains("favorite movie:")
running_code.iprocess.send_keys("the usual suspects\n")
running_code.iprocess.wait_for_finish()
with open("screenshot.txt", 'w') as handle:
handle.write(running_code.iprocess.stripshot())
assert running_code.finished
然后,代码编写的“screenshot.txt”文件将包含
favorite c
olor:red
favorite m
ovie:the u
sual suspe
cts
可执行规范
从 running-code.story storytests 自动生成的文档。