如何编写测试我的 C++ 的 python 脚本?

How to write a python script that test my c++?

假设我想测试我的 C++ 代码,但我不想手动执行。我意识到我可以编写一个 python 脚本来测试我的代码。所以我想测试这个 C++ 代码,例如:

#include <iostream>
#include <string>
using namespace std;

int main() {
   string line;
   cin >> line;
   cout << line << endl;
}

这是我试图测试此 c++ 代码的 python 脚本:

import subprocess as sb

sb.call("g++ main.cpp", shell=True)
sb.call("./a.out", shell=True)
sb.call("chocolate", shell=True)

这会创建 a.out 可执行文件,但它不允许我 运行 我的程序。我怎样才能使这项工作?或者有什么更好的我可以做的吗?

测试可能会变得复杂,但至少您可以使用 subprocess.Popen 对象来管理程序的输入和输出。这是一个极简测试套件

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)