Merged pull request #12 from bhy/T423.
[cython.git] / tests / run / posix_test.pyx
1 # tag: posix
2 from libc.stdio   cimport *
3 from posix.unistd cimport *
4 from posix.fcntl  cimport *
5
6 cdef int noisy_function() except -1:
7     cdef int ret = 0
8     ret = printf(b"0123456789\n", 0)
9     assert ret == 11
10     ret = fflush(stdout)
11     assert ret == 0
12     ret = fprintf(stdout, b"0123456789\n", 0)
13     assert ret == 11
14     ret = fflush(stdout)
15     assert ret == 0
16     ret = write(STDOUT_FILENO, b"0123456789\n", 11)
17     assert ret == 11
18     return  0
19
20
21 def test_silent_stdout():
22     """
23     >>> test_silent_stdout()
24     """
25     cdef int ret
26     cdef int stdout_save, dev_null
27     stdout_save = dup(STDOUT_FILENO)
28     assert stdout_save != -1
29     dev_null = open(b"/dev/null", O_WRONLY, 0)
30     assert dev_null != -1
31     ret = dup2(dev_null, STDOUT_FILENO)
32     assert ret == STDOUT_FILENO
33     ret = close(dev_null)
34     assert ret == 0
35     try:
36         noisy_function()
37     finally:
38         ret = dup2(stdout_save, STDOUT_FILENO)
39         assert ret == STDOUT_FILENO
40         ret = close(stdout_save)
41         assert ret == 0
42
43 cdef class silent_fd:
44
45     cdef int fd_save, fd
46
47     def __cinit__(self, int fd=-1):
48         self.fd_save = -1
49         self.fd = STDOUT_FILENO
50         if fd != -1:
51             self.fd = fd
52
53     def __enter__(self):
54         cdef int ret = 0, dev_null = -1
55         assert self.fd_save == -1
56         dev_null = open(b"/dev/null", O_WRONLY, 0)
57         assert dev_null != -1
58         try:
59             self.fd_save = dup(self.fd)
60             assert self.fd_save != -1
61             try:
62                 ret = dup2(dev_null, self.fd)
63                 assert ret != -1
64             except:
65                 ret = close(self.fd_save)
66                 self.fd_save = -1
67         finally:
68             ret = close(dev_null)
69
70     def __exit__(self, t, v, tb):
71         cdef int ret = 0
72         if self.fd_save != -1:
73             ret = dup2(self.fd_save, self.fd)
74             assert ret == self.fd
75             ret = close(self.fd_save)
76             assert ret == 0
77             self.fd_save = -1
78         return None
79
80 def test_silent_stdout_ctxmanager():
81     """
82     >> test_silent_stdout_ctxmanager()
83     """
84     with silent_fd():
85         noisy_function()
86     try:
87         with silent_fd():
88             noisy_function()
89             raise RuntimeError
90     except RuntimeError:
91         pass
92     with silent_fd(STDOUT_FILENO):
93         noisy_function()