• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1#!/usr/bin/env python
2#
3# Copyright 2018, The Android Open Source Project
4#
5# Licensed under the Apache License, Version 2.0 (the "License");
6# you may not use this file except in compliance with the License.
7# You may obtain a copy of the License at
8#
9#     http://www.apache.org/licenses/LICENSE-2.0
10#
11# Unless required by applicable law or agreed to in writing, software
12# distributed under the License is distributed on an "AS IS" BASIS,
13# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14# See the License for the specific language governing permissions and
15# limitations under the License.
16
17"""Unittests for atest_utils."""
18
19import subprocess
20import sys
21import unittest
22import mock
23
24import atest_utils
25
26if sys.version_info[0] == 2:
27    from StringIO import StringIO
28else:
29    from io import StringIO
30
31#pylint: disable=protected-access
32class AtestUtilsUnittests(unittest.TestCase):
33    """Unit tests for atest_utils.py"""
34
35    def test_capture_fail_section_has_fail_section(self):
36        """Test capture_fail_section when has fail section."""
37        test_list = ['AAAAAA', 'FAILED: Error1', '^\n', 'Error2\n',
38                     '[  6% 191/2997] BBBBBB\n', 'CCCCC',
39                     '[  20% 322/2997] DDDDDD\n', 'EEEEE']
40        want_list = ['FAILED: Error1', '^\n', 'Error2\n']
41        self.assertEqual(want_list,
42                         atest_utils._capture_fail_section(test_list))
43
44    def test_capture_fail_section_no_fail_section(self):
45        """Test capture_fail_section when no fail section."""
46        test_list = ['[ 6% 191/2997] XXXXX', 'YYYYY: ZZZZZ']
47        want_list = []
48        self.assertEqual(want_list,
49                         atest_utils._capture_fail_section(test_list))
50
51    def test_is_test_mapping(self):
52        """Test method is_test_mapping."""
53        tm_option_attributes = [
54            'test_mapping',
55            'include_subdirs'
56        ]
57        for attr_to_test in tm_option_attributes:
58            args = mock.Mock()
59            for attr in tm_option_attributes:
60                setattr(args, attr, attr == attr_to_test)
61            args.tests = []
62            self.assertTrue(
63                atest_utils.is_test_mapping(args),
64                'Failed to validate option %s' % attr_to_test)
65
66        args = mock.Mock()
67        for attr in tm_option_attributes:
68            setattr(args, attr, False)
69        args.tests = [':group_name']
70        self.assertTrue(atest_utils.is_test_mapping(args))
71
72        args = mock.Mock()
73        for attr in tm_option_attributes:
74            setattr(args, attr, False)
75        args.tests = [':test1', 'test2']
76        self.assertFalse(atest_utils.is_test_mapping(args))
77
78        args = mock.Mock()
79        for attr in tm_option_attributes:
80            setattr(args, attr, False)
81        args.tests = ['test2']
82        self.assertFalse(atest_utils.is_test_mapping(args))
83
84    @mock.patch('curses.tigetnum')
85    def test_has_colors(self, mock_curses_tigetnum):
86        """Test method _has_colors."""
87        # stream is file I/O
88        stream = open('/tmp/test_has_colors.txt', 'wb')
89        self.assertFalse(atest_utils._has_colors(stream))
90        stream.close()
91
92        # stream is not a tty(terminal).
93        stream = mock.Mock()
94        stream.isatty.return_value = False
95        self.assertFalse(atest_utils._has_colors(stream))
96
97        # stream is a tty(terminal) and colors < 2.
98        stream = mock.Mock()
99        stream.isatty.return_value = True
100        mock_curses_tigetnum.return_value = 1
101        self.assertFalse(atest_utils._has_colors(stream))
102
103        # stream is a tty(terminal) and colors > 2.
104        stream = mock.Mock()
105        stream.isatty.return_value = True
106        mock_curses_tigetnum.return_value = 256
107        self.assertTrue(atest_utils._has_colors(stream))
108
109
110    @mock.patch('atest_utils._has_colors')
111    def test_colorize(self, mock_has_colors):
112        """Test method colorize."""
113        original_str = "test string"
114        green_no = 2
115
116        # _has_colors() return False.
117        mock_has_colors.return_value = False
118        converted_str = atest_utils.colorize(original_str, green_no,
119                                             highlight=True)
120        self.assertEqual(original_str, converted_str)
121
122        # Green with highlight.
123        mock_has_colors.return_value = True
124        converted_str = atest_utils.colorize(original_str, green_no,
125                                             highlight=True)
126        green_highlight_string = '\x1b[1;42m%s\x1b[0m' % original_str
127        self.assertEqual(green_highlight_string, converted_str)
128
129        # Green, no highlight.
130        mock_has_colors.return_value = True
131        converted_str = atest_utils.colorize(original_str, green_no,
132                                             highlight=False)
133        green_no_highlight_string = '\x1b[1;32m%s\x1b[0m' % original_str
134        self.assertEqual(green_no_highlight_string, converted_str)
135
136
137    @mock.patch('atest_utils._has_colors')
138    def test_colorful_print(self, mock_has_colors):
139        """Test method colorful_print."""
140        testing_str = "color_print_test"
141        green_no = 2
142
143        # _has_colors() return False.
144        mock_has_colors.return_value = False
145        capture_output = StringIO()
146        sys.stdout = capture_output
147        atest_utils.colorful_print(testing_str, green_no, highlight=True,
148                                   auto_wrap=False)
149        sys.stdout = sys.__stdout__
150        uncolored_string = testing_str
151        self.assertEqual(capture_output.getvalue(), uncolored_string)
152
153        # Green with highlight, but no wrap.
154        mock_has_colors.return_value = True
155        capture_output = StringIO()
156        sys.stdout = capture_output
157        atest_utils.colorful_print(testing_str, green_no, highlight=True,
158                                   auto_wrap=False)
159        sys.stdout = sys.__stdout__
160        green_highlight_no_wrap_string = '\x1b[1;42m%s\x1b[0m' % testing_str
161        self.assertEqual(capture_output.getvalue(),
162                         green_highlight_no_wrap_string)
163
164        # Green, no highlight, no wrap.
165        mock_has_colors.return_value = True
166        capture_output = StringIO()
167        sys.stdout = capture_output
168        atest_utils.colorful_print(testing_str, green_no, highlight=False,
169                                   auto_wrap=False)
170        sys.stdout = sys.__stdout__
171        green_no_high_no_wrap_string = '\x1b[1;32m%s\x1b[0m' % testing_str
172        self.assertEqual(capture_output.getvalue(),
173                         green_no_high_no_wrap_string)
174
175        # Green with highlight and wrap.
176        mock_has_colors.return_value = True
177        capture_output = StringIO()
178        sys.stdout = capture_output
179        atest_utils.colorful_print(testing_str, green_no, highlight=True,
180                                   auto_wrap=True)
181        sys.stdout = sys.__stdout__
182        green_highlight_wrap_string = '\x1b[1;42m%s\x1b[0m\n' % testing_str
183        self.assertEqual(capture_output.getvalue(), green_highlight_wrap_string)
184
185        # Green with wrap, but no highlight.
186        mock_has_colors.return_value = True
187        capture_output = StringIO()
188        sys.stdout = capture_output
189        atest_utils.colorful_print(testing_str, green_no, highlight=False,
190                                   auto_wrap=True)
191        sys.stdout = sys.__stdout__
192        green_wrap_no_highlight_string = '\x1b[1;32m%s\x1b[0m\n' % testing_str
193        self.assertEqual(capture_output.getvalue(),
194                         green_wrap_no_highlight_string)
195
196    @mock.patch('subprocess.check_output')
197    def test_is_external_run(self, mock_output):
198        """Test method is_external_run."""
199        mock_output.return_value = ''
200        self.assertTrue(atest_utils.is_external_run())
201        mock_output.return_value = 'test@other.com'
202        self.assertTrue(atest_utils.is_external_run())
203        mock_output.return_value = 'test@google.com'
204        self.assertFalse(atest_utils.is_external_run())
205        mock_output.side_effect = OSError()
206        self.assertTrue(atest_utils.is_external_run())
207        mock_output.side_effect = subprocess.CalledProcessError(1, 'cmd')
208        self.assertTrue(atest_utils.is_external_run())
209
210    @mock.patch('atest_utils.is_external_run')
211    def test_print_data_collection_notice(self, mock_is_external_run):
212        """Test method print_data_collection_notice."""
213
214        # is_external_run return False.
215        mock_is_external_run.return_value = True
216        notice_str = ('\n==================\nNotice:\n'
217                      '  We collect anonymous usage statistics'
218                      ' in accordance with our'
219                      ' Content Licenses (https://source.android.com/setup/start/licenses),'
220                      ' Contributor License Agreement (https://opensource.google.com/docs/cla/),'
221                      ' Privacy Policy (https://policies.google.com/privacy) and'
222                      ' Terms of Service (https://policies.google.com/terms).'
223                      '\n==================\n\n')
224        capture_output = StringIO()
225        sys.stdout = capture_output
226        atest_utils.print_data_collection_notice()
227        sys.stdout = sys.__stdout__
228        uncolored_string = notice_str
229        self.assertEqual(capture_output.getvalue(), uncolored_string)
230
231        # is_external_run return False.
232        mock_is_external_run.return_value = False
233        notice_str = ('\n==================\nNotice:\n'
234                      '  We collect usage statistics'
235                      ' in accordance with our'
236                      ' Content Licenses (https://source.android.com/setup/start/licenses),'
237                      ' Contributor License Agreement (https://cla.developers.google.com/),'
238                      ' Privacy Policy (https://policies.google.com/privacy) and'
239                      ' Terms of Service (https://policies.google.com/terms).'
240                      '\n==================\n\n')
241        capture_output = StringIO()
242        sys.stdout = capture_output
243        atest_utils.print_data_collection_notice()
244        sys.stdout = sys.__stdout__
245        uncolored_string = notice_str
246        self.assertEqual(capture_output.getvalue(), uncolored_string)
247
248
249if __name__ == "__main__":
250    unittest.main()
251