23c46c4234344183449e12096124075f73c22b67
[sdc/sdc-distribution-client.git] /
1 #!/usr/bin/env python
2 #
3 #  Licensed under the Apache License, Version 2.0 (the "License"); you may
4 #  not use this file except in compliance with the License. You may obtain
5 #  a copy of the License at
6 #
7 #       http://www.apache.org/licenses/LICENSE-2.0
8 #
9 #  Unless required by applicable law or agreed to in writing, software
10 #  distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
11 #  WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
12 #  License for the specific language governing permissions and limitations
13 #  under the License.
14
15 import os
16 import struct
17 import sys
18
19 import mock
20 import nose
21
22 from cliff import utils
23
24
25 def test_utils_terminal_width():
26     width = utils.terminal_width(sys.stdout)
27     # Results are specific to the execution environment, so only assert
28     # that no error is raised.
29     assert width is None or isinstance(width, int)
30
31
32 @mock.patch('cliff.utils.os')
33 def test_utils_terminal_width_get_terminal_size(mock_os):
34     if not hasattr(os, 'get_terminal_size'):
35         raise nose.SkipTest('only needed for python 3.3 onwards')
36     ts = os.terminal_size((10, 5))
37     mock_os.get_terminal_size.return_value = ts
38     width = utils.terminal_width(sys.stdout)
39     assert width == 10
40
41     mock_os.get_terminal_size.side_effect = OSError()
42     width = utils.terminal_width(sys.stdout)
43     assert width is None
44
45
46 @mock.patch('fcntl.ioctl')
47 def test_utils_terminal_width_ioctl(mock_ioctl):
48     if hasattr(os, 'get_terminal_size'):
49         raise nose.SkipTest('only needed for python 3.2 and before')
50     mock_ioctl.return_value = struct.pack('hhhh', 57, 101, 0, 0)
51     width = utils.terminal_width(sys.stdout)
52     assert width == 101
53
54     mock_ioctl.side_effect = IOError()
55     width = utils.terminal_width(sys.stdout)
56     assert width is None
57
58
59 @mock.patch('cliff.utils.ctypes')
60 @mock.patch('sys.platform', 'win32')
61 def test_utils_terminal_width_windows(mock_ctypes):
62     if hasattr(os, 'get_terminal_size'):
63         raise nose.SkipTest('only needed for python 3.2 and before')
64
65     mock_ctypes.create_string_buffer.return_value.raw = struct.pack(
66         'hhhhHhhhhhh', 101, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0)
67     mock_ctypes.windll.kernel32.GetStdHandle.return_value = -11
68     mock_ctypes.windll.kernel32.GetConsoleScreenBufferInfo.return_value = 1
69
70     width = utils.terminal_width(sys.stdout)
71     assert width == 101
72
73     mock_ctypes.windll.kernel32.GetConsoleScreenBufferInfo.return_value = 0
74
75     width = utils.terminal_width(sys.stdout)
76     assert width is None
77
78     width = utils.terminal_width('foo')
79     assert width is None