-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathtest.h
65 lines (54 loc) · 1.69 KB
/
test.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
#include "doctest.h"
#include "../PyLogHook.h"
#include <string>
inline void check_python_error()
{
CHECK(PyErr_Occurred() == 0);
if (PyErr_Occurred())
{
PyObject *ptype, *pvalue, *ptraceback;
PyErr_Fetch(&ptype, &pvalue, &ptraceback);
PyObject *pyErrStr = PyObject_Str(ptype);
FAIL(PyUnicode_AsUTF8(pyErrStr));
Py_DECREF(pyErrStr);
PyErr_Restore(ptype, pvalue, ptraceback);
}
}
TEST_CASE("Print test")
{
// init Python
Py_Initialize();
REQUIRE(Py_IsInitialized() != 0);
// set hook
std::string stdoutString;
tyti::pylog::redirect_stdout([&stdoutString](const char *w)
{
stdoutString += w; // stdout
});
check_python_error();
std::string stderrString;
tyti::pylog::redirect_stderr([&stderrString](const char *w)
{
stderrString += w; // stdout
});
check_python_error();
// execute printing operation
const std::string test_str = "TESTING";
SUBCASE("testing stdout")
{
std::string code = std::string("print(\"") + test_str + std::string("\")");
PyRun_SimpleString(code.c_str());
check_python_error();
// check
REQUIRE(stdoutString == test_str + "\n");
}
SUBCASE("testing stderr")
{
std::string code = std::string("import sys\nsys.stderr.write(\"") + test_str + std::string("\")");
PyRun_SimpleString(code.c_str());
check_python_error();
// check
REQUIRE(stderrString == test_str);
}
Py_Finalize();
}