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