[英]How to write a python script that test my c++?
Say I wanna test my c++ code but I don't want to do it by hand. 说我想测试我的C ++代码,但是我不想手工做。 I realize I can write a python script that can test my code for me.
我意识到我可以编写一个可以为我测试代码的python脚本。 So I want to test this c++ code for example:
因此,我想例如测试此c ++代码:
#include <iostream>
#include <string>
using namespace std;
int main() {
string line;
cin >> line;
cout << line << endl;
}
Here is the python script that I tried to test this c++ code: 这是我尝试测试此c ++代码的python脚本:
import subprocess as sb
sb.call("g++ main.cpp", shell=True)
sb.call("./a.out", shell=True)
sb.call("chocolate", shell=True)
This create the a.out
executable file but it doesn't allow me to run my program. 这将创建
a.out
可执行文件,但不允许我运行程序。 How can I make this work? 我该如何进行这项工作? Or is there something better that I can do?
还是我能做得更好?
Testing can get complicated but as a minimum you can use the subprocess.Popen
object to manage the input and output of the program. 测试可能会变得很复杂,但至少可以使用
subprocess.Popen
对象来管理程序的输入和输出。 Here is a minimalist test suite 这是一个简约的测试套件
import subprocess as sb
import threading
def timeout():
print('timeout')
exit(3)
sb.check_call("g++ main.cpp", shell=True)
t = threading.Timer(10, timeout)
proc = sb.Popen("./a.out", shell=True, stdin=sb.PIPE, stdout=sb.PIPE,
stderr=sb.PIPE)
out, err = proc.communicate('hello\n')
t.cancel()
assert proc.returncode == 0
assert out == 'hello\n'
assert err == ''
sb.check_call("chocolate", shell=True)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.