• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# Copyright 2016 Google Inc. All Rights Reserved.
2#
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
21
22from yapftests import yapf_test_helper
23
24
25class TestsForFacebookStyle(yapf_test_helper.YAPFTest):
26
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        """)
41    uwlines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
42    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        """)
57    uwlines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
58    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        """)
73    uwlines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
74    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        """)
94    uwlines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
95    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        """)
106    uwlines = yapf_test_helper.ParseAndUnwrap(code)
107    self.assertCodeEqual(code, reformatter.Reformat(uwlines))
108
109  def testDedentTestListGexp(self):
110    unformatted_code = textwrap.dedent("""\
111        try:
112            pass
113        except (
114            IOError, OSError, LookupError, RuntimeError, OverflowError
115        ) as exception:
116            pass
117
118        try:
119            pass
120        except (
121            IOError, OSError, LookupError, RuntimeError, OverflowError,
122        ) as exception:
123            pass
124        """)
125    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))
146
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        """)
163    uwlines = yapf_test_helper.ParseAndUnwrap(pass0_code)
164    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        """)
174    uwlines = yapf_test_helper.ParseAndUnwrap(pass1_code)
175    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        """)
197    uwlines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
198    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        """)
211    uwlines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
212    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        """)
234    uwlines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
235    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        """)
245    uwlines = yapf_test_helper.ParseAndUnwrap(code)
246    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        """)
323    uwlines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
324    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,
332                    LineSource('localhost', xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx)
333                )
334        """)
335    uwlines = yapf_test_helper.ParseAndUnwrap(code)
336    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        """)
349    uwlines = yapf_test_helper.ParseAndUnwrap(code)
350    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        """)
365    uwlines = yapf_test_helper.ParseAndUnwrap(code)
366    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        """)
378    uwlines = yapf_test_helper.ParseAndUnwrap(code)
379    reformatted_code = reformatter.Reformat(uwlines)
380    self.assertCodeEqual(code, reformatted_code)
381
382    uwlines = yapf_test_helper.ParseAndUnwrap(reformatted_code)
383    reformatted_code = reformatter.Reformat(uwlines)
384    self.assertCodeEqual(code, reformatted_code)
385
386  def testCommentWithNewlinesInPrefix(self):
387    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("""\
401        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        """)
412    uwlines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
413    self.assertCodeEqual(expected_formatted_code, reformatter.Reformat(uwlines))
414
415  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
430
431if __name__ == '__main__':
432  unittest.main()
433