summaryrefslogtreecommitdiffstats
path: root/Lib/test/test_curses.py
blob: 274704152007d01b383422f72916528ea198cabc (plain)
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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
#
# Test script for the curses module
#
# This script doesn't actually display anything very coherent. but it
# does call (nearly) every method and function.
#
# Functions not tested: {def,reset}_{shell,prog}_mode, getch(), getstr(),
# init_color()
# Only called, not tested: getmouse(), ungetmouse()
#

import os
import sys
import tempfile
import unittest

from test.support import requires, import_module, verbose

# Optionally test curses module.  This currently requires that the
# 'curses' resource be given on the regrtest command line using the -u
# option.  If not available, nothing after this line will be executed.
import inspect
requires('curses')

# If either of these don't exist, skip the tests.
curses = import_module('curses')
curses.panel = import_module('curses.panel')

term = os.environ.get('TERM', 'unknown')

@unittest.skipUnless(sys.__stdout__.isatty(), 'sys.__stdout__ is not a tty')
@unittest.skipIf(term == 'unknown',
                 "$TERM=%r, calling initscr() may cause exit" % term)
@unittest.skipIf(sys.platform == "cygwin",
                 "cygwin's curses mostly just hangs")
class TestCurses(unittest.TestCase):
    @classmethod
    def setUpClass(cls):
        curses.setupterm(fd=sys.__stdout__.fileno())

    def setUp(self):
        if verbose:
            # just to make the test output a little more readable
            print()
        self.stdscr = curses.initscr()
        curses.savetty()

    def tearDown(self):
        curses.resetty()
        curses.endwin()

    def test_window_funcs(self):
        "Test the methods of windows"
        stdscr = self.stdscr
        win = curses.newwin(10,10)
        win = curses.newwin(5,5, 5,5)
        win2 = curses.newwin(15,15, 5,5)

        for meth in [stdscr.addch, stdscr.addstr]:
            for args in [('a'), ('a', curses.A_BOLD),
                         (4,4, 'a'), (5,5, 'a', curses.A_BOLD)]:
                meth(*args)

        for meth in [stdscr.box, stdscr.clear, stdscr.clrtobot,
                     stdscr.clrtoeol, stdscr.cursyncup, stdscr.delch,
                     stdscr.deleteln, stdscr.erase, stdscr.getbegyx,
                     stdscr.getbkgd, stdscr.getkey, stdscr.getmaxyx,
                     stdscr.getparyx, stdscr.getyx, stdscr.inch,
                     stdscr.insertln, stdscr.instr, stdscr.is_wintouched,
                     win.noutrefresh, stdscr.redrawwin, stdscr.refresh,
                     stdscr.standout, stdscr.standend, stdscr.syncdown,
                     stdscr.syncup, stdscr.touchwin, stdscr.untouchwin]:
            meth()

        stdscr.addnstr('1234', 3)
        stdscr.addnstr('1234', 3, curses.A_BOLD)
        stdscr.addnstr(4,4, '1234', 3)
        stdscr.addnstr(5,5, '1234', 3, curses.A_BOLD)

        stdscr.attron(curses.A_BOLD)
        stdscr.attroff(curses.A_BOLD)
        stdscr.attrset(curses.A_BOLD)
        stdscr.bkgd(' ')
        stdscr.bkgd(' ', curses.A_REVERSE)
        stdscr.bkgdset(' ')
        stdscr.bkgdset(' ', curses.A_REVERSE)

        win.border(65, 66, 67, 68,
                   69, 70, 71, 72)
        win.border('|', '!', '-', '_',
                   '+', '\\', '#', '/')
        with self.assertRaises(TypeError,
                               msg="Expected win.border() to raise TypeError"):
            win.border(65, 66, 67, 68,
                       69, [], 71, 72)

        stdscr.clearok(1)

        win4 = stdscr.derwin(2,2)
        win4 = stdscr.derwin(1,1, 5,5)
        win4.mvderwin(9,9)

        stdscr.echochar('a')
        stdscr.echochar('a', curses.A_BOLD)
        stdscr.hline('-', 5)
        stdscr.hline('-', 5, curses.A_BOLD)
        stdscr.hline(1,1,'-', 5)
        stdscr.hline(1,1,'-', 5, curses.A_BOLD)

        stdscr.idcok(1)
        stdscr.idlok(1)
        stdscr.immedok(1)
        stdscr.insch('c')
        stdscr.insdelln(1)
        stdscr.insnstr('abc', 3)
        stdscr.insnstr('abc', 3, curses.A_BOLD)
        stdscr.insnstr(5, 5, 'abc', 3)
        stdscr.insnstr(5, 5, 'abc', 3, curses.A_BOLD)

        stdscr.insstr('def')
        stdscr.insstr('def', curses.A_BOLD)
        stdscr.insstr(5, 5, 'def')
        stdscr.insstr(5, 5, 'def', curses.A_BOLD)
        stdscr.is_linetouched(0)
        stdscr.keypad(1)
        stdscr.leaveok(1)
        stdscr.move(3,3)
        win.mvwin(2,2)
        stdscr.nodelay(1)
        stdscr.notimeout(1)
        win2.overlay(win)
        win2.overwrite(win)
        win2.overlay(win, 1, 2, 2, 1, 3, 3)
        win2.overwrite(win, 1, 2, 2, 1, 3, 3)
        stdscr.redrawln(1,2)

        stdscr.scrollok(1)
        stdscr.scroll()
        stdscr.scroll(2)
        stdscr.scroll(-3)

        stdscr.move(12, 2)
        stdscr.setscrreg(10,15)
        win3 = stdscr.subwin(10,10)
        win3 = stdscr.subwin(10,10, 5,5)
        stdscr.syncok(1)
        stdscr.timeout(5)
        stdscr.touchline(5,5)
        stdscr.touchline(5,5,0)
        stdscr.vline('a', 3)
        stdscr.vline('a', 3, curses.A_STANDOUT)
        stdscr.chgat(5, 2, 3, curses.A_BLINK)
        stdscr.chgat(3, curses.A_BOLD)
        stdscr.chgat(5, 8, curses.A_UNDERLINE)
        stdscr.chgat(curses.A_BLINK)
        stdscr.refresh()

        stdscr.vline(1,1, 'a', 3)
        stdscr.vline(1,1, 'a', 3, curses.A_STANDOUT)

        if hasattr(curses, 'resize'):
            stdscr.resize()
        if hasattr(curses, 'enclose'):
            stdscr.enclose()


    def test_module_funcs(self):
        "Test module-level functions"
        stdscr = self.stdscr
        for func in [curses.baudrate, curses.beep, curses.can_change_color,
                     curses.cbreak, curses.def_prog_mode, curses.doupdate,
                     curses.filter, curses.flash, curses.flushinp,
                     curses.has_colors, curses.has_ic, curses.has_il,
                     curses.isendwin, curses.killchar, curses.longname,
                     curses.nocbreak, curses.noecho, curses.nonl,
                     curses.noqiflush, curses.noraw,
                     curses.reset_prog_mode, curses.termattrs,
                     curses.termname, curses.erasechar, curses.getsyx]:
            func()

        # Functions that actually need arguments
        if curses.tigetstr("cnorm"):
            curses.curs_set(1)
        curses.delay_output(1)
        curses.echo() ; curses.echo(1)

        f = tempfile.TemporaryFile()
        stdscr.putwin(f)
        f.seek(0)
        curses.getwin(f)
        f.close()

        curses.halfdelay(1)
        curses.intrflush(1)
        curses.meta(1)
        curses.napms(100)
        curses.newpad(50,50)
        win = curses.newwin(5,5)
        win = curses.newwin(5,5, 1,1)
        curses.nl() ; curses.nl(1)
        curses.putp(b'abc')
        curses.qiflush()
        curses.raw() ; curses.raw(1)
        curses.setsyx(5,5)
        curses.tigetflag('hc')
        curses.tigetnum('co')
        curses.tigetstr('cr')
        curses.tparm(b'cr')
        curses.typeahead(sys.__stdin__.fileno())
        curses.unctrl('a')
        curses.ungetch('a')
        curses.use_env(1)

        # Functions only available on a few platforms
        if curses.has_colors():
            curses.start_color()
            curses.init_pair(2, 1,1)
            curses.color_content(1)
            curses.color_pair(2)
            curses.pair_content(curses.COLOR_PAIRS - 1)
            curses.pair_number(0)

            if hasattr(curses, 'use_default_colors'):
                curses.use_default_colors()

        if hasattr(curses, 'keyname'):
            curses.keyname(13)

        if hasattr(curses, 'has_key'):
            curses.has_key(13)

        if hasattr(curses, 'getmouse'):
            (availmask, oldmask) = curses.mousemask(curses.BUTTON1_PRESSED)
            # availmask indicates that mouse stuff not available.
            if availmask != 0:
                curses.mouseinterval(10)
                # just verify these don't cause errors
                curses.ungetmouse(0, 0, 0, 0, curses.BUTTON1_PRESSED)
                m = curses.getmouse()

        if hasattr(curses, 'is_term_resized'):
            curses.is_term_resized(*stdscr.getmaxyx())
        if hasattr(curses, 'resizeterm'):
            curses.resizeterm(*stdscr.getmaxyx())
        if hasattr(curses, 'resize_term'):
            curses.resize_term(*stdscr.getmaxyx())

    def test_unctrl(self):
        from curses import ascii
        for ch, expected in [('a', 'a'), ('A', 'A'),
                             (';', ';'), (' ', ' '),
                             ('\x7f', '^?'), ('\n', '^J'), ('\0', '^@'),
                             # Meta-bit characters
                             ('\x8a', '!^J'), ('\xc1', '!A'),
                             ]:
            self.assertEqual(ascii.unctrl(ch), expected,
                             'curses.unctrl fails on character %r' % ch)


    def test_userptr_without_set(self):
        w = curses.newwin(10, 10)
        p = curses.panel.new_panel(w)
        # try to access userptr() before calling set_userptr() -- segfaults
        with self.assertRaises(curses.panel.error,
                               msg='userptr should fail since not set'):
            p.userptr()

    def test_userptr_memory_leak(self):
        w = curses.newwin(10, 10)
        p = curses.panel.new_panel(w)
        obj = object()
        nrefs = sys.getrefcount(obj)
        for i in range(100):
            p.set_userptr(obj)

        p.set_userptr(None)
        self.assertEqual(sys.getrefcount(obj), nrefs,
                         "set_userptr leaked references")

    def test_userptr_segfault(self):
        panel = curses.panel.new_panel(self.stdscr)
        class A:
            def __del__(self):
                panel.set_userptr(None)
        panel.set_userptr(A())
        panel.set_userptr(None)

    @unittest.skipUnless(hasattr(curses, 'resizeterm'),
                           'resizeterm not available')
    def test_resize_term(self):
        lines, cols = curses.LINES, curses.COLS
        new_lines = lines - 1
        new_cols = cols + 1
        curses.resizeterm(new_lines, new_cols)

        self.assertEqual(curses.LINES, new_lines)
        self.assertEqual(curses.COLS, new_cols)

    def test_issue6243(self):
        curses.ungetch(1025)
        self.stdscr.getkey()

    @unittest.skipUnless(hasattr(curses, 'unget_wch'),
                         'unget_wch not available')
    def test_unget_wch(self):
        stdscr = self.stdscr
        encoding = stdscr.encoding
        for ch in ('a', '\xe9', '\u20ac', '\U0010FFFF'):
            try:
                ch.encode(encoding)
            except UnicodeEncodeError:
                continue
            try:
                curses.unget_wch(ch)
            except Exception as err:
                self.fail("unget_wch(%a) failed with encoding %s: %s"
                          % (ch, stdscr.encoding, err))
            read = stdscr.get_wch()
            self.assertEqual(read, ch)

            code = ord(ch)
            curses.unget_wch(code)
            read = stdscr.get_wch()
            self.assertEqual(read, ch)

    def test_issue10570(self):
        b = curses.tparm(curses.tigetstr("cup"), 5, 3)
        self.assertIs(type(b), bytes)
        curses.putp(b)

    def test_encoding(self):
        stdscr = self.stdscr
        import codecs
        encoding = stdscr.encoding
        codecs.lookup(encoding)

        with self.assertRaises(TypeError):
            stdscr.encoding = 10

        stdscr.encoding = encoding
        with self.assertRaises(TypeError):
            del stdscr.encoding

    def test_issue21088(self):
        stdscr = self.stdscr
        #
        # http://bugs.python.org/issue21088
        #
        # the bug:
        # when converting curses.window.addch to Argument Clinic
        # the first two parameters were switched.

        # if someday we can represent the signature of addch
        # we will need to rewrite this test.
        try:
            signature = inspect.signature(stdscr.addch)
            self.assertFalse(signature)
        except ValueError:
            # not generating a signature is fine.
            pass

        # So.  No signature for addch.
        # But Argument Clinic gave us a human-readable equivalent
        # as the first line of the docstring.  So we parse that,
        # and ensure that the parameters appear in the correct order.
        # Since this is parsing output from Argument Clinic, we can
        # be reasonably certain the generated parsing code will be
        # correct too.
        human_readable_signature = stdscr.addch.__doc__.split("\n")[0]
        offset = human_readable_signature.find("[y, x,]")
        assert offset >= 0, ""

    def test_update_lines_cols(self):
        # this doesn't actually test that LINES and COLS are updated,
        # because we can't automate changing them. See Issue #4254 for
        # a manual test script. We can only test that the function
        # can be called.
        curses.update_lines_cols()


if __name__ == '__main__':
    unittest.main()
* with the new StcResourceProfile. * name * Pointer to a constant null-terminated character string which contains * the name of the class to which the new object belongs (it is this * pointer value that will subsequently be returned by the astGetClass * method). * region * A pointer to the Region encapsulated by the StcResourceProfile. * ncoords * Number of KeyMap pointers supplied in "coords". Can be zero. * Ignored if "coords" is NULL. * coords * Pointer to an array of "ncoords" KeyMap pointers, or NULL if * "ncoords" is zero. Each KeyMap defines defines a single <AstroCoords> * element, and should have elements with keys given by constants * AST__STCNAME, AST__STCVALUE, AST__STCERROR, AST__STCRES, AST__STCSIZE, * AST__STCPIXSZ. These elements hold values for the corresponding * components of the STC AstroCoords element. Any of these elements may * be omitted, but no other elements should be included. All supplied * elements should be vector elements, with vector length less than or * equal to the number of axes in the supplied Region. The data type of * all elements should be "double", except for AST__STCNAME which should * be "character string". If no value is available for a given axis, then * AST__BAD (or NULL for the AST__STCNAME element) should be stored in * the vector at the index corresponding to the axis (trailing axes * can be omitted completely from the KeyMap). * Returned Value: * A pointer to the new StcResourceProfile. * Notes: * - A null pointer will be returned if this function is invoked with the * global error status set, or if it should fail for any reason. *- */ /* Local Variables: */ AstStcResourceProfile *new; /* Pointer to new StcResourceProfile */ /* Check the global status. */ if ( !astOK ) return NULL; /* If necessary, initialise the virtual function table. */ if ( init ) astInitStcResourceProfileVtab( vtab, name ); /* Initialise a Stc structure (the parent class) as the first component within the StcResourceProfile structure, allocating memory if necessary. */ new = (AstStcResourceProfile *) astInitStc( mem, size, 0, (AstStcVtab *) vtab, name, region, ncoords, coords ); /* If an error occurred, clean up by deleting the new StcResourceProfile. */ if ( !astOK ) new = astDelete( new ); /* Return a pointer to the new StcResourceProfile. */ return new; } AstStcResourceProfile *astLoadStcResourceProfile_( void *mem, size_t size, AstStcResourceProfileVtab *vtab, const char *name, AstChannel *channel, int *status ) { /* *+ * Name: * astLoadStcResourceProfile * Purpose: * Load a StcResourceProfile. * Type: * Protected function. * Synopsis: * #include "stcresourceprofile.h" * AstStcResourceProfile *astLoadStcResourceProfile( void *mem, size_t size, AstStcResourceProfileVtab *vtab, * const char *name, AstChannel *channel ) * Class Membership: * StcResourceProfile loader. * Description: * This function is provided to load a new StcResourceProfile using data read * from a Channel. It first loads the data used by the parent class * (which allocates memory if necessary) and then initialises a * StcResourceProfile structure in this memory, using data read from the input * Channel. * * If the "init" flag is set, it also initialises the contents of a * virtual function table for a StcResourceProfile at the start of the memory * passed via the "vtab" parameter. * Parameters: * mem * A pointer to the memory into which the StcResourceProfile is to be * loaded. This must be of sufficient size to accommodate the * StcResourceProfile data (sizeof(StcResourceProfile)) plus any data used by derived * classes. If a value of NULL is given, this function will * allocate the memory itself using the "size" parameter to * determine its size. * size * The amount of memory used by the StcResourceProfile (plus derived class * data). This will be used to allocate memory if a value of * NULL is given for the "mem" parameter. This value is also * stored in the StcResourceProfile structure, so a valid value must be * supplied even if not required for allocating memory. * * If the "vtab" parameter is NULL, the "size" value is ignored * and sizeof(AstStcResourceProfile) is used instead. * vtab * Pointer to the start of the virtual function table to be * associated with the new StcResourceProfile. If this is NULL, a pointer * to the (static) virtual function table for the StcResourceProfile class * is used instead. * name * Pointer to a constant null-terminated character string which * contains the name of the class to which the new object * belongs (it is this pointer value that will subsequently be * returned by the astGetClass method). * * If the "vtab" parameter is NULL, the "name" value is ignored * and a pointer to the string "StcResourceProfile" is used instead. * Returned Value: * A pointer to the new StcResourceProfile. * Notes: * - A null pointer will be returned if this function is invoked * with the global error status set, or if it should fail for any * reason. *- */ /* Local Variables: */ astDECLARE_GLOBALS /* Pointer to thread-specific global data */ AstStcResourceProfile *new; /* Pointer to the new StcResourceProfile */ /* Initialise. */ new = NULL; /* Check the global error status. */ if ( !astOK ) return new; /* Get a pointer to the thread specific global data structure. */ astGET_GLOBALS(channel); /* If a NULL virtual function table has been supplied, then this is the first loader to be invoked for this StcResourceProfile. In this case the StcResourceProfile belongs to this class, so supply appropriate values to be passed to the parent class loader (and its parent, etc.). */ if ( !vtab ) { size = sizeof( AstStcResourceProfile ); vtab = &class_vtab; name = "StcResourceProfile"; /* If required, initialise the virtual function table for this class. */ if ( !class_init ) { astInitStcResourceProfileVtab( vtab, name ); class_init = 1; } } /* Invoke the parent class loader to load data for all the ancestral classes of the current one, returning a pointer to the resulting partly-built StcResourceProfile. */ new = astLoadStc( mem, size, (AstStcVtab *) vtab, name, channel ); if ( astOK ) { /* Read input data. */ /* ================ */ /* Request the input Channel to read all the input data appropriate to this class into the internal "values list". */ astReadClassData( channel, "StcResourceProfile" ); /* Now read each individual data item from this list and use it to initialise the appropriate instance variable(s) for this class. */ /* In the case of attributes, we first read the "raw" input value, supplying the "unset" value as the default. If a "set" value is obtained, we then use the appropriate (private) Set... member function to validate and set the value properly. */ /* There are no values to read. */ /* ---------------------------- */ /* If an error occurred, clean up by deleting the new StcResourceProfile. */ if ( !astOK ) new = astDelete( new ); } /* Return the new StcResourceProfile pointer. */ return new; } /* Virtual function interfaces. */ /* ============================ */ /* These provide the external interface to the virtual functions defined by this class. Each simply checks the global error status and then locates and executes the appropriate member function, using the function pointer stored in the object's virtual function table (this pointer is located using the astMEMBER macro defined in "object.h"). Note that the member function may not be the one defined here, as it may have been over-ridden by a derived class. However, it should still have the same interface. */