Upstream version 10.39.225.0
[platform/framework/web/crosswalk.git] / src / third_party / chromite / cros / commands / lint_unittest.py
1 #!/usr/bin/python
2 # Copyright (c) 2013 The Chromium OS Authors. All rights reserved.
3 # Use of this source code is governed by a BSD-style license that can be
4 # found in the LICENSE file.
5
6 """Test the lint module."""
7
8 from __future__ import print_function
9
10 import collections
11 import os
12 import sys
13
14 sys.path.insert(0, os.path.abspath('%s/../../..' % os.path.dirname(__file__)))
15
16 from chromite.lib import cros_test_lib
17 import lint
18
19
20 class TestNode(object):
21   """Object good enough to stand in for lint funcs"""
22
23   Args = collections.namedtuple('Args', ('args', 'vararg', 'kwarg'))
24   Arg = collections.namedtuple('Arg', ('name',))
25
26   def __init__(self, doc='', fromlineno=0, path='foo.py', args=(), vararg='',
27                kwarg=''):
28     self.doc = doc
29     self.lines = doc.split('\n')
30     self.fromlineno = fromlineno
31     self.file = path
32     self.args = self.Args(args=[self.Arg(name=x) for x in args],
33                           vararg=vararg, kwarg=kwarg)
34
35   def argnames(self):
36     return self.args
37
38
39 class DocStringCheckerTest(cros_test_lib.TestCase):
40   """Tests for DocStringChecker module"""
41
42   GOOD_FUNC_DOCSTRINGS = (
43       'Some string',
44       """Short summary
45
46       Body of text.
47       """,
48       """line o text
49
50       Body and comments on
51       more than one line.
52
53       Args:
54         moo: cow
55
56       Returns:
57         some value
58
59       Raises:
60         something else
61       """,
62       """Short summary.
63
64       Args:
65         fat: cat
66
67       Yields:
68         a spoon
69       """,
70   )
71
72   BAD_FUNC_DOCSTRINGS = (
73       """
74       bad first line
75       """,
76       """ whitespace is wrong""",
77       """whitespace is wrong    """,
78       """ whitespace is wrong
79
80       Multiline tickles differently.
81       """,
82       """Should be no trailing blank lines
83
84       Returns:
85         a value
86
87       """
88       """ok line
89
90       cuddled end""",
91       """we want Args/Returns not Arguments/Return
92
93       Arguments:
94       Return:
95       """,
96       """section order is wrong here
97
98       Raises:
99       Returns:
100       """,
101       """sections lack whitespace between them
102
103       Args:
104         foo: bar
105       Returns:
106         yeah
107       """,
108       """yields is misspelled
109
110       Yield:
111         a car
112       """,
113       """Section name has bad spacing
114
115       Args:\x20\x20\x20
116         key: here
117       """,
118       """too many blank lines
119
120
121       Returns:
122         None
123       """,
124       """wrongly uses javadoc
125
126       @returns None
127       """
128   )
129
130   # The current linter isn't good enough yet to detect these.
131   TODO_BAD_FUNC_DOCSTRINGS = (
132       """The returns section isn't a proper section
133
134       Args:
135         bloop: de
136
137       returns something
138       """,
139       """the indentation is incorrect
140
141         Args:
142           some: day
143       """,
144   )
145
146   def add_message(self, msg_id, node=None, line=None, args=None):
147     """Capture lint checks"""
148     # We include node.doc here explicitly so the pretty assert message
149     # inclues it in the output automatically.
150     self.results.append((msg_id, node.doc, line, args))
151
152   def setUp(self):
153     self.results = []
154     self.checker = lint.DocStringChecker()
155     self.checker.add_message = self.add_message
156
157   def testGood_visit_function(self):
158     """Allow known good docstrings"""
159     for dc in self.GOOD_FUNC_DOCSTRINGS:
160       self.results = []
161       node = TestNode(doc=dc)
162       self.checker.visit_function(node)
163       self.assertEqual(self.results, [],
164                        msg='docstring was not accepted:\n"""%s"""' % dc)
165
166   def testBad_visit_function(self):
167     """Reject known bad docstrings"""
168     for dc in self.BAD_FUNC_DOCSTRINGS:
169       self.results = []
170       node = TestNode(doc=dc)
171       self.checker.visit_function(node)
172       self.assertNotEqual(self.results, [],
173                           msg='docstring was not rejected:\n"""%s"""' % dc)
174
175   def testSmoke_visit_module(self):
176     """Smoke test for modules"""
177     self.checker.visit_module(TestNode(doc='foo'))
178     self.assertEqual(self.results, [])
179     self.checker.visit_module(TestNode(doc='', path='/foo/__init__.py'))
180     self.assertEqual(self.results, [])
181
182   def testSmoke_visit_class(self):
183     """Smoke test for classes"""
184     self.checker.visit_class(TestNode(doc='bar'))
185
186   def testGood_check_first_line(self):
187     """Verify _check_first_line accepts good inputs"""
188     # pylint: disable=W0212
189     docstrings = (
190         'Some string',
191     )
192     for dc in docstrings:
193       self.results = []
194       node = TestNode(doc=dc)
195       self.checker._check_first_line(node, node.lines)
196       self.assertEqual(self.results, [],
197                        msg='docstring was not accepted:\n"""%s"""' % dc)
198
199   def testBad_check_first_line(self):
200     """Verify _check_first_line rejects bad inputs"""
201     # pylint: disable=W0212
202     docstrings = (
203         '\nSome string\n',
204     )
205     for dc in docstrings:
206       self.results = []
207       node = TestNode(doc=dc)
208       self.checker._check_first_line(node, node.lines)
209       self.assertEqual(len(self.results), 1)
210
211   def testGoodFuncVarKwArg(self):
212     """Check valid inputs for *args and **kwargs"""
213     # pylint: disable=W0212
214     for vararg in (None, 'args', '_args'):
215       for kwarg in (None, 'kwargs', '_kwargs'):
216         self.results = []
217         node = TestNode(vararg=vararg, kwarg=kwarg)
218         self.checker._check_func_signature(node)
219         self.assertEqual(len(self.results), 0)
220
221   def testMisnamedFuncVarKwArg(self):
222     """Reject anything but *args and **kwargs"""
223     # pylint: disable=W0212
224     for vararg in ('arg', 'params', 'kwargs', '_moo'):
225       self.results = []
226       node = TestNode(vararg=vararg)
227       self.checker._check_func_signature(node)
228       self.assertEqual(len(self.results), 1)
229
230     for kwarg in ('kwds', '_kwds', 'args', '_moo'):
231       self.results = []
232       node = TestNode(kwarg=kwarg)
233       self.checker._check_func_signature(node)
234       self.assertEqual(len(self.results), 1)
235
236   def testGoodFuncArgs(self):
237     """Verify normal args in Args are allowed"""
238     # pylint: disable=W0212
239     datasets = (
240         ("""args are correct, and cls is ignored
241
242          Args:
243            moo: cow
244          """,
245          ('cls', 'moo',), None, None,
246         ),
247         ("""args are correct, and self is ignored
248
249          Args:
250            moo: cow
251            *args: here
252          """,
253          ('self', 'moo',), 'args', 'kwargs',
254         ),
255         ("""args are allowed to wrap
256
257          Args:
258            moo:
259              a big fat cow
260              that takes many lines
261              to describe its fatness
262          """,
263          ('moo',), None, 'kwargs',
264         ),
265     )
266     for dc, args, vararg, kwarg in datasets:
267       self.results = []
268       node = TestNode(doc=dc, args=args, vararg=vararg, kwarg=kwarg)
269       self.checker._check_all_args_in_doc(node, node.lines)
270       self.assertEqual(len(self.results), 0)
271
272   def testBadFuncArgs(self):
273     """Verify bad/missing args in Args are caught"""
274     # pylint: disable=W0212
275     datasets = (
276         ("""missing 'bar'
277
278          Args:
279            moo: cow
280          """,
281          ('moo', 'bar',),
282         ),
283         ("""missing 'cow' but has 'bloop'
284
285          Args:
286            moo: cow
287          """,
288          ('bloop',),
289         ),
290         ("""too much space after colon
291
292          Args:
293            moo:  cow
294          """,
295          ('moo',),
296         ),
297         ("""not enough space after colon
298
299          Args:
300            moo:cow
301          """,
302          ('moo',),
303         ),
304     )
305     for dc, args in datasets:
306       self.results = []
307       node = TestNode(doc=dc, args=args)
308       self.checker._check_all_args_in_doc(node, node.lines)
309       self.assertEqual(len(self.results), 1)
310
311
312 if __name__ == '__main__':
313   cros_test_lib.main()