test_match.py 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. from sys import version_info
  2. from pyflakes.test.harness import TestCase, skipIf
  3. @skipIf(version_info < (3, 10), "Python >= 3.10 only")
  4. class TestMatch(TestCase):
  5. def test_match_bindings(self):
  6. self.flakes('''
  7. def f():
  8. x = 1
  9. match x:
  10. case 1 as y:
  11. print(f'matched as {y}')
  12. ''')
  13. self.flakes('''
  14. def f():
  15. x = [1, 2, 3]
  16. match x:
  17. case [1, y, 3]:
  18. print(f'matched {y}')
  19. ''')
  20. self.flakes('''
  21. def f():
  22. x = {'foo': 1}
  23. match x:
  24. case {'foo': y}:
  25. print(f'matched {y}')
  26. ''')
  27. def test_match_pattern_matched_class(self):
  28. self.flakes('''
  29. from a import B
  30. match 1:
  31. case B(x=1) as y:
  32. print(f'matched {y}')
  33. ''')
  34. self.flakes('''
  35. from a import B
  36. match 1:
  37. case B(a, x=z) as y:
  38. print(f'matched {y} {a} {z}')
  39. ''')
  40. def test_match_placeholder(self):
  41. self.flakes('''
  42. def f():
  43. match 1:
  44. case _:
  45. print('catchall!')
  46. ''')
  47. def test_match_singleton(self):
  48. self.flakes('''
  49. match 1:
  50. case True:
  51. print('true')
  52. ''')
  53. def test_match_or_pattern(self):
  54. self.flakes('''
  55. match 1:
  56. case 1 | 2:
  57. print('one or two')
  58. ''')
  59. def test_match_star(self):
  60. self.flakes('''
  61. x = [1, 2, 3]
  62. match x:
  63. case [1, *y]:
  64. print(f'captured: {y}')
  65. ''')
  66. def test_match_double_star(self):
  67. self.flakes('''
  68. x = {'foo': 'bar', 'baz': 'womp'}
  69. match x:
  70. case {'foo': k1, **rest}:
  71. print(f'{k1=} {rest=}')
  72. ''')
  73. def test_defined_in_different_branches(self):
  74. self.flakes('''
  75. def f(x):
  76. match x:
  77. case 1:
  78. def y(): pass
  79. case _:
  80. def y(): print(1)
  81. return y
  82. ''')