0

Say I wanna test my c++ code but I don't want to do it by hand. I realize I can write a python script that can test my code for me. So I want to test this c++ code for example:

#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:

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. How can I make this work? Or is there something better that I can do?

Mats Petersson
  • 126,704
  • 14
  • 140
  • 227
user3904534
  • 309
  • 5
  • 13
  • Removing "C++" tag, as your question is not about how to do something in C++, but how to do something in Python - even if you put some C++ code in the question, that is not the code you are asking about [directly]. – Mats Petersson Mar 04 '16 at 23:23
  • You could use `subprocess.pipe` and `Popen.communicate`, perhaps? – Mats Petersson Mar 04 '16 at 23:24
  • 1
    Possible duplicate of [Python executing shell command doesn't terminate](http://stackoverflow.com/questions/16196288/python-executing-shell-command-doesnt-terminate) – Prune Mar 04 '16 at 23:25
  • Why do you want to test your C++ code with python script? Is there any special reason for that? I think it is more natural and easier to use C++ unit testing libraries like [boots.test](http://www.boost.org/doc/libs/develop/libs/test/doc/html/index.html). – Borys Serebrov Mar 04 '16 at 23:31
  • 1
    @BorisSerebrov We have an entire test team that writes tests for c++ programs in python. These tests drive the C++ at the command line level and by using a foreign function interface when appropriate. This is not C++ unit testing of course (we do that too) but it is a major component of testing. Putting "boost" and "easy" in the same sentence may also be violating natural law. – tdelaney Mar 04 '16 at 23:35
  • Your code works. ./a.out is called and when I type in a word then hit , it prints the line and then crashes on the next call. I presume that you want more control of the input and output? For that, use the `Popen` object. – tdelaney Mar 04 '16 at 23:37

1 Answers1

1

Testing can get complicated but as a minimum you can use the subprocess.Popen object to manage the input and output of the program. 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)
tdelaney
  • 73,364
  • 6
  • 83
  • 116