blob: 289aa853476790c2ac773fcbf5f1f944b146f820 [file] [log] [blame]
Bill Wendling92290f12018-01-14 16:49:35 -08001# Copyright 2016 Google Inc. All Rights Reserved.
Bill Wendling9fb475b2016-10-23 02:10:01 -07002#
3# Licensed under the Apache License, Version 2.0 (the "License");
4# you may not use this file except in compliance with the License.
5# You may obtain 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,
11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12# See the License for the specific language governing permissions and
13# limitations under the License.
14"""Facebook tests for yapf.reformatter."""
15
16import textwrap
17import unittest
18
19from yapf.yapflib import reformatter
20from yapf.yapflib import style
Bill Wendling9fb475b2016-10-23 02:10:01 -070021
Bill Wendlinga8ebae22016-10-23 16:09:06 -070022from yapftests import yapf_test_helper
Bill Wendling9fb475b2016-10-23 02:10:01 -070023
24
Bill Wendlinga8ebae22016-10-23 16:09:06 -070025class TestsForFacebookStyle(yapf_test_helper.YAPFTest):
Bill Wendling9fb475b2016-10-23 02:10:01 -070026
27 @classmethod
28 def setUpClass(cls):
29 style.SetGlobalStyle(style.CreateFacebookStyle())
30
31 def testNoNeedForLineBreaks(self):
32 unformatted_code = textwrap.dedent("""\
33 def overly_long_function_name(
34 just_one_arg, **kwargs):
35 pass
36 """)
37 expected_formatted_code = textwrap.dedent("""\
38 def overly_long_function_name(just_one_arg, **kwargs):
39 pass
40 """)
Bill Wendlinga8ebae22016-10-23 16:09:06 -070041 uwlines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
Bill Wendling9fb475b2016-10-23 02:10:01 -070042 self.assertCodeEqual(expected_formatted_code, reformatter.Reformat(uwlines))
43
44 def testDedentClosingBracket(self):
45 unformatted_code = textwrap.dedent("""\
46 def overly_long_function_name(
47 first_argument_on_the_same_line,
48 second_argument_makes_the_line_too_long):
49 pass
50 """)
51 expected_formatted_code = textwrap.dedent("""\
52 def overly_long_function_name(
53 first_argument_on_the_same_line, second_argument_makes_the_line_too_long
54 ):
55 pass
56 """)
Bill Wendlinga8ebae22016-10-23 16:09:06 -070057 uwlines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
Bill Wendling9fb475b2016-10-23 02:10:01 -070058 self.assertCodeEqual(expected_formatted_code, reformatter.Reformat(uwlines))
59
60 def testBreakAfterOpeningBracketIfContentsTooBig(self):
61 unformatted_code = textwrap.dedent("""\
62 def overly_long_function_name(a, b, c, d, e, f, g, h, i, j, k, l, m,
63 n, o, p, q, r, s, t, u, v, w, x, y, z):
64 pass
65 """)
66 expected_formatted_code = textwrap.dedent("""\
67 def overly_long_function_name(
68 a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, \
69v, w, x, y, z
70 ):
71 pass
72 """)
Bill Wendlinga8ebae22016-10-23 16:09:06 -070073 uwlines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
Bill Wendling9fb475b2016-10-23 02:10:01 -070074 self.assertCodeEqual(expected_formatted_code, reformatter.Reformat(uwlines))
75
76 def testDedentClosingBracketWithComments(self):
77 unformatted_code = textwrap.dedent("""\
78 def overly_long_function_name(
79 # comment about the first argument
80 first_argument_with_a_very_long_name_or_so,
81 # comment about the second argument
82 second_argument_makes_the_line_too_long):
83 pass
84 """)
85 expected_formatted_code = textwrap.dedent("""\
86 def overly_long_function_name(
87 # comment about the first argument
88 first_argument_with_a_very_long_name_or_so,
89 # comment about the second argument
90 second_argument_makes_the_line_too_long
91 ):
92 pass
93 """)
Bill Wendlinga8ebae22016-10-23 16:09:06 -070094 uwlines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
Bill Wendling9fb475b2016-10-23 02:10:01 -070095 self.assertCodeEqual(expected_formatted_code, reformatter.Reformat(uwlines))
96
97 def testDedentImportAsNames(self):
98 code = textwrap.dedent("""\
99 from module import (
100 internal_function as function,
101 SOME_CONSTANT_NUMBER1,
102 SOME_CONSTANT_NUMBER2,
103 SOME_CONSTANT_NUMBER3,
104 )
105 """)
Bill Wendlinga8ebae22016-10-23 16:09:06 -0700106 uwlines = yapf_test_helper.ParseAndUnwrap(code)
Bill Wendling9fb475b2016-10-23 02:10:01 -0700107 self.assertCodeEqual(code, reformatter.Reformat(uwlines))
108
109 def testDedentTestListGexp(self):
Justin Huangb5febcb2017-08-06 19:44:38 -0700110 unformatted_code = textwrap.dedent("""\
Bill Wendling9fb475b2016-10-23 02:10:01 -0700111 try:
112 pass
113 except (
114 IOError, OSError, LookupError, RuntimeError, OverflowError
115 ) as exception:
116 pass
117
118 try:
119 pass
120 except (
Bill Wendling94962e52017-02-04 04:07:19 -0800121 IOError, OSError, LookupError, RuntimeError, OverflowError,
Bill Wendling9fb475b2016-10-23 02:10:01 -0700122 ) as exception:
123 pass
124 """)
Justin Huangb5febcb2017-08-06 19:44:38 -0700125 expected_formatted_code = textwrap.dedent("""\
126 try:
127 pass
128 except (
129 IOError, OSError, LookupError, RuntimeError, OverflowError
130 ) as exception:
131 pass
132
133 try:
134 pass
135 except (
136 IOError,
137 OSError,
138 LookupError,
139 RuntimeError,
140 OverflowError,
141 ) as exception:
142 pass
143 """)
144 uwlines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
145 self.assertCodeEqual(expected_formatted_code, reformatter.Reformat(uwlines))
Bill Wendling9fb475b2016-10-23 02:10:01 -0700146
147 def testBrokenIdempotency(self):
148 # TODO(ambv): The following behaviour should be fixed.
149 pass0_code = textwrap.dedent("""\
150 try:
151 pass
152 except (IOError, OSError, LookupError, RuntimeError, OverflowError) as exception:
153 pass
154 """)
155 pass1_code = textwrap.dedent("""\
156 try:
157 pass
158 except (
159 IOError, OSError, LookupError, RuntimeError, OverflowError
160 ) as exception:
161 pass
162 """)
Bill Wendlinga8ebae22016-10-23 16:09:06 -0700163 uwlines = yapf_test_helper.ParseAndUnwrap(pass0_code)
Bill Wendling9fb475b2016-10-23 02:10:01 -0700164 self.assertCodeEqual(pass1_code, reformatter.Reformat(uwlines))
165
166 pass2_code = textwrap.dedent("""\
167 try:
168 pass
169 except (
170 IOError, OSError, LookupError, RuntimeError, OverflowError
171 ) as exception:
172 pass
173 """)
Bill Wendlinga8ebae22016-10-23 16:09:06 -0700174 uwlines = yapf_test_helper.ParseAndUnwrap(pass1_code)
Bill Wendling9fb475b2016-10-23 02:10:01 -0700175 self.assertCodeEqual(pass2_code, reformatter.Reformat(uwlines))
176
177 def testIfExprHangingIndent(self):
178 unformatted_code = textwrap.dedent("""\
179 if True:
180 if True:
181 if True:
182 if not self.frobbies and (
183 self.foobars.counters['db.cheeses'] != 1 or
184 self.foobars.counters['db.marshmellow_skins'] != 1):
185 pass
186 """)
187 expected_formatted_code = textwrap.dedent("""\
188 if True:
189 if True:
190 if True:
191 if not self.frobbies and (
192 self.foobars.counters['db.cheeses'] != 1 or
193 self.foobars.counters['db.marshmellow_skins'] != 1
194 ):
195 pass
196 """)
Bill Wendlinga8ebae22016-10-23 16:09:06 -0700197 uwlines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
Bill Wendling9fb475b2016-10-23 02:10:01 -0700198 self.assertCodeEqual(expected_formatted_code, reformatter.Reformat(uwlines))
199
200 def testSimpleDedenting(self):
201 unformatted_code = textwrap.dedent("""\
202 if True:
203 self.assertEqual(result.reason_not_added, "current preflight is still running")
204 """)
205 expected_formatted_code = textwrap.dedent("""\
206 if True:
207 self.assertEqual(
208 result.reason_not_added, "current preflight is still running"
209 )
210 """)
Bill Wendlinga8ebae22016-10-23 16:09:06 -0700211 uwlines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
Bill Wendling9fb475b2016-10-23 02:10:01 -0700212 self.assertCodeEqual(expected_formatted_code, reformatter.Reformat(uwlines))
213
214 def testDedentingWithSubscripts(self):
215 unformatted_code = textwrap.dedent("""\
216 class Foo:
217 class Bar:
218 @classmethod
219 def baz(cls, clues_list, effect, constraints, constraint_manager):
220 if clues_lists:
221 return cls.single_constraint_not(clues_lists, effect, constraints[0], constraint_manager)
222
223 """)
224 expected_formatted_code = textwrap.dedent("""\
225 class Foo:
226 class Bar:
227 @classmethod
228 def baz(cls, clues_list, effect, constraints, constraint_manager):
229 if clues_lists:
230 return cls.single_constraint_not(
231 clues_lists, effect, constraints[0], constraint_manager
232 )
233 """)
Bill Wendlinga8ebae22016-10-23 16:09:06 -0700234 uwlines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
Bill Wendling9fb475b2016-10-23 02:10:01 -0700235 self.assertCodeEqual(expected_formatted_code, reformatter.Reformat(uwlines))
236
237 def testDedentingCallsWithInnerLists(self):
238 code = textwrap.dedent("""\
239 class _():
240 def _():
241 cls.effect_clues = {
242 'effect': Clue((cls.effect_time, 'apache_host'), effect_line, 40)
243 }
244 """)
Bill Wendlinga8ebae22016-10-23 16:09:06 -0700245 uwlines = yapf_test_helper.ParseAndUnwrap(code)
Bill Wendling9fb475b2016-10-23 02:10:01 -0700246 self.assertCodeEqual(code, reformatter.Reformat(uwlines))
247
248 def testDedentingListComprehension(self):
249 unformatted_code = textwrap.dedent("""\
250 class Foo():
251 def _pack_results_for_constraint_or():
252 self.param_groups = dict(
253 (
254 key + 1, ParamGroup(groups[key], default_converter)
255 ) for key in six.moves.range(len(groups))
256 )
257
258 for combination in cls._clues_combinations(clues_lists):
259 if all(
260 cls._verify_constraint(combination, effect, constraint)
261 for constraint in constraints
262 ):
263 pass
264
265 guessed_dict = dict(
266 (
267 key, guessed_pattern_matches[key]
268 ) for key in six.moves.range(len(guessed_pattern_matches))
269 )
270
271 content = "".join(
272 itertools.chain(
273 (first_line_fragment, ), lines_between, (last_line_fragment, )
274 )
275 )
276
277 rule = Rule(
278 [self.cause1, self.cause2, self.cause1, self.cause2], self.effect, constraints1,
279 Rule.LINKAGE_AND
280 )
281
282 assert sorted(log_type.files_to_parse) == [
283 ('localhost', os.path.join(path, 'node_1.log'), super_parser),
284 ('localhost', os.path.join(path, 'node_2.log'), super_parser)
285 ]
286 """)
287 expected_formatted_code = textwrap.dedent("""\
288 class Foo():
289 def _pack_results_for_constraint_or():
290 self.param_groups = dict(
291 (key + 1, ParamGroup(groups[key], default_converter))
292 for key in six.moves.range(len(groups))
293 )
294
295 for combination in cls._clues_combinations(clues_lists):
296 if all(
297 cls._verify_constraint(combination, effect, constraint)
298 for constraint in constraints
299 ):
300 pass
301
302 guessed_dict = dict(
303 (key, guessed_pattern_matches[key])
304 for key in six.moves.range(len(guessed_pattern_matches))
305 )
306
307 content = "".join(
308 itertools.chain(
309 (first_line_fragment, ), lines_between, (last_line_fragment, )
310 )
311 )
312
313 rule = Rule(
314 [self.cause1, self.cause2, self.cause1, self.cause2], self.effect,
315 constraints1, Rule.LINKAGE_AND
316 )
317
318 assert sorted(log_type.files_to_parse) == [
319 ('localhost', os.path.join(path, 'node_1.log'), super_parser),
320 ('localhost', os.path.join(path, 'node_2.log'), super_parser)
321 ]
322 """)
Bill Wendlinga8ebae22016-10-23 16:09:06 -0700323 uwlines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
Bill Wendling9fb475b2016-10-23 02:10:01 -0700324 self.assertCodeEqual(expected_formatted_code, reformatter.Reformat(uwlines))
325
326 def testMustSplitDedenting(self):
327 code = textwrap.dedent("""\
328 class _():
329 def _():
330 effect_line = FrontInput(
331 effect_line_offset, line_content,
Bill Wendling47c3e4f2016-11-21 15:25:09 -0800332 LineSource('localhost', xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx)
Bill Wendling9fb475b2016-10-23 02:10:01 -0700333 )
334 """)
Bill Wendlinga8ebae22016-10-23 16:09:06 -0700335 uwlines = yapf_test_helper.ParseAndUnwrap(code)
Bill Wendling9fb475b2016-10-23 02:10:01 -0700336 self.assertCodeEqual(code, reformatter.Reformat(uwlines))
337
338 def testDedentIfConditional(self):
339 code = textwrap.dedent("""\
340 class _():
341 def _():
342 if True:
343 if not self.frobbies and (
344 self.foobars.counters['db.cheeses'] != 1 or
345 self.foobars.counters['db.marshmellow_skins'] != 1
346 ):
347 pass
348 """)
Bill Wendlinga8ebae22016-10-23 16:09:06 -0700349 uwlines = yapf_test_helper.ParseAndUnwrap(code)
Bill Wendling9fb475b2016-10-23 02:10:01 -0700350 self.assertCodeEqual(code, reformatter.Reformat(uwlines))
351
352 def testDedentSet(self):
353 code = textwrap.dedent("""\
354 class _():
355 def _():
356 assert set(self.constraint_links.get_links()) == set(
357 [
358 (2, 10, 100),
359 (2, 10, 200),
360 (2, 20, 100),
361 (2, 20, 200),
362 ]
363 )
364 """)
Bill Wendlinga8ebae22016-10-23 16:09:06 -0700365 uwlines = yapf_test_helper.ParseAndUnwrap(code)
Bill Wendling9fb475b2016-10-23 02:10:01 -0700366 self.assertCodeEqual(code, reformatter.Reformat(uwlines))
367
368 def testDedentingInnerScope(self):
369 code = textwrap.dedent("""\
370 class Foo():
371 @classmethod
372 def _pack_results_for_constraint_or(cls, combination, constraints):
373 return cls._create_investigation_result(
374 (clue for clue in combination if not clue == Verifier.UNMATCHED),
375 constraints, InvestigationResult.OR
376 )
377 """)
Bill Wendlinga8ebae22016-10-23 16:09:06 -0700378 uwlines = yapf_test_helper.ParseAndUnwrap(code)
Bill Wendling9fb475b2016-10-23 02:10:01 -0700379 reformatted_code = reformatter.Reformat(uwlines)
380 self.assertCodeEqual(code, reformatted_code)
381
Bill Wendlinga8ebae22016-10-23 16:09:06 -0700382 uwlines = yapf_test_helper.ParseAndUnwrap(reformatted_code)
Bill Wendling9fb475b2016-10-23 02:10:01 -0700383 reformatted_code = reformatter.Reformat(uwlines)
384 self.assertCodeEqual(code, reformatted_code)
385
386 def testCommentWithNewlinesInPrefix(self):
Bill Wendlingfb9b3e22016-10-23 02:40:21 -0700387 unformatted_code = textwrap.dedent("""\
388 def foo():
389 if 0:
390 return False
391
392
393 #a deadly comment
394 elif 1:
395 return True
396
397
398 print(foo())
399 """)
400 expected_formatted_code = textwrap.dedent("""\
Bill Wendling9fb475b2016-10-23 02:10:01 -0700401 def foo():
402 if 0:
403 return False
404
405 #a deadly comment
406 elif 1:
407 return True
408
409
410 print(foo())
411 """)
Bill Wendlinga8ebae22016-10-23 16:09:06 -0700412 uwlines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
Bill Wendlingfb9b3e22016-10-23 02:40:21 -0700413 self.assertCodeEqual(expected_formatted_code, reformatter.Reformat(uwlines))
Bill Wendling9fb475b2016-10-23 02:10:01 -0700414
Bill Wendling2b0c6312018-01-13 21:53:14 -0800415 def testIfStmtClosingBracket(self):
416 unformatted_code = """\
417if (isinstance(value , (StopIteration , StopAsyncIteration )) and exc.__cause__ is value_asdfasdfasdfasdfsafsafsafdasfasdfs):
418 return False
419"""
420 expected_formatted_code = """\
421if (
422 isinstance(value, (StopIteration, StopAsyncIteration)) and
423 exc.__cause__ is value_asdfasdfasdfasdfsafsafsafdasfasdfs
424):
425 return False
426"""
427 uwlines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
428 self.assertCodeEqual(expected_formatted_code, reformatter.Reformat(uwlines))
429
Bill Wendling9fb475b2016-10-23 02:10:01 -0700430
431if __name__ == '__main__':
432 unittest.main()