xref: /petsc/src/binding/petsc4py/test/test_stdout.py (revision 9e2fe13843cc1957dbe26e9163e43e9766df8148)
1*9e2fe138SToby Isaacimport unittest
2*9e2fe138SToby Isaac
3*9e2fe138SToby Isaac# --------------------------------------------------------------------
4*9e2fe138SToby Isaac
5*9e2fe138SToby Isaac
6*9e2fe138SToby Isaacclass TestStdout(unittest.TestCase):
7*9e2fe138SToby Isaac    def testStdoutRedirect(self):
8*9e2fe138SToby Isaac        from io import StringIO
9*9e2fe138SToby Isaac        import sys
10*9e2fe138SToby Isaac        prevstdout = sys.stdout
11*9e2fe138SToby Isaac        prevstderr = sys.stderr
12*9e2fe138SToby Isaac        sys.stdout = StringIO()
13*9e2fe138SToby Isaac        sys.stderr = StringIO()
14*9e2fe138SToby Isaac
15*9e2fe138SToby Isaac        import numpy as np
16*9e2fe138SToby Isaac        from petsc4py import PETSc
17*9e2fe138SToby Isaac
18*9e2fe138SToby Isaac        if not (__name__ == '__main__'):
19*9e2fe138SToby Isaac            PETSc._push_python_vfprintf()
20*9e2fe138SToby Isaac
21*9e2fe138SToby Isaac        a = np.array([0.,0.,0.])
22*9e2fe138SToby Isaac        a_vec = PETSc.Vec().createWithArray(a,comm=PETSc.COMM_SELF)
23*9e2fe138SToby Isaac        a_vec.view()
24*9e2fe138SToby Isaac        v = PETSc.Viewer.STDERR(PETSc.COMM_SELF)
25*9e2fe138SToby Isaac        v.printfASCII("Error message")
26*9e2fe138SToby Isaac
27*9e2fe138SToby Isaac        newstdout = sys.stdout
28*9e2fe138SToby Isaac        newstderr = sys.stderr
29*9e2fe138SToby Isaac        sys.stdout = prevstdout
30*9e2fe138SToby Isaac        sys.stderr = prevstderr
31*9e2fe138SToby Isaac
32*9e2fe138SToby Isaac        output = newstdout.getvalue()
33*9e2fe138SToby Isaac        error = newstderr.getvalue()
34*9e2fe138SToby Isaac        if not (__name__ == '__main__'):
35*9e2fe138SToby Isaac            PETSc._pop_python_vfprintf()
36*9e2fe138SToby Isaac        stdoutshouldbe = \
37*9e2fe138SToby Isaac"""Vec Object: 1 MPI processes
38*9e2fe138SToby Isaac  type: seq
39*9e2fe138SToby Isaac0.
40*9e2fe138SToby Isaac0.
41*9e2fe138SToby Isaac0.
42*9e2fe138SToby Isaac"""
43*9e2fe138SToby Isaac        stderrshouldbe = "Error message"
44*9e2fe138SToby Isaac        if PETSc._stdout_is_stderr():
45*9e2fe138SToby Isaac            stdoutshouldbe = stdoutshouldbe + stderrshouldbe
46*9e2fe138SToby Isaac            stderrshouldbe = ""
47*9e2fe138SToby Isaac        self.assertEqual(output,stdoutshouldbe)
48*9e2fe138SToby Isaac        self.assertEqual(error,stderrshouldbe)
49*9e2fe138SToby Isaac
50*9e2fe138SToby Isaac
51*9e2fe138SToby Isaac
52*9e2fe138SToby Isaac# --------------------------------------------------------------------
53*9e2fe138SToby Isaac
54*9e2fe138SToby Isaacif __name__ == '__main__':
55*9e2fe138SToby Isaac    unittest.main()
56*9e2fe138SToby Isaac
57*9e2fe138SToby Isaac# --------------------------------------------------------------------
58