How to write a unit test for C language test using Python unit test. The motivation is to reduce the number of compilations as much as possible. This method eliminates the need for compilation when writing tests (although I don't know if it's speedy or if the return value is complex).
First, the C language code is as follows.
//main.c
#include<stdio.h>
int add(int a, int b);
struct Pair {
int l;
int r;
};
int
main(void) {
printf("%d + %d = %d\n", 3, 4, add(3, 4));
return (0);
}
int add(int a, int b) {
return a + b;
}
struct Pair make_pair(int l, int r) {
struct Pair p;
p.l = l;
p.r = r;
return p;
}
Then the python code to call from gdb looks like this:
#debug.py
import unittest
class Test(unittest.TestCase):
def assertEqual_(self, a, expr):
self.assertEqual(a, gdb.parse_and_eval(expr))
def test_aaaa(self):
self.assertEqual_(42, 'add(30, 12)')
def test_bbb(self):
self.assertEqual_(0, 'add(0, 0)')
def test_ccc(self):
p = gdb.parse_and_eval("make_pair(3, 4)")
self.assertEqual("{l = 3, r = 4}", str(p))
gdb.execute('break main')
gdb.execute('run')
unittest.main()
To test C code with this python code:
$ gcc -g3 main.c
$ gdb -q -x ./debug.py a.out
The standard output looks like this: Now you can add and modify tests written in C in Python without recompiling.
Reading symbols from a.out...done.
Breakpoint 1 at 0x804841c: file main.c, line 9.
Breakpoint 1, main () at main.c:9
9 printf("%d + %d = %d\n", 3, 4, add(3, 4));
...
----------------------------------------------------------------------
Ran 3 tests in 0.003s
OK
As I wrote at the beginning, if the return value of the function is complicated, I think that it is possible to handle the structure better. In C language, it may be realistic to prepare a function that converts the contents of an object into a character string.
Recommended Posts