1"""Unit tests for the keyword only argument specified in PEP 3102.""" 2 3__author__ = "Jiwon Seo" 4__email__ = "seojiwon at gmail dot com" 5 6import unittest 7 8def posonly_sum(pos_arg1, *arg, **kwarg): 9 return pos_arg1 + sum(arg) + sum(kwarg.values()) 10def keywordonly_sum(*, k1=0, k2): 11 return k1 + k2 12def keywordonly_nodefaults_sum(*, k1, k2): 13 return k1 + k2 14def keywordonly_and_kwarg_sum(*, k1, k2, **kwarg): 15 return k1 + k2 + sum(kwarg.values()) 16def mixedargs_sum(a, b=0, *arg, k1, k2=0): 17 return a + b + k1 + k2 + sum(arg) 18def mixedargs_sum2(a, b=0, *arg, k1, k2=0, **kwargs): 19 return a + b + k1 + k2 + sum(arg) + sum(kwargs.values()) 20 21def sortnum(*nums, reverse=False): 22 return sorted(list(nums), reverse=reverse) 23 24def sortwords(*words, reverse=False, **kwargs): 25 return sorted(list(words), reverse=reverse) 26 27class Foo: 28 def __init__(self, *, k1, k2=0): 29 self.k1 = k1 30 self.k2 = k2 31 def set(self, p1, *, k1, k2): 32 self.k1 = k1 33 self.k2 = k2 34 def sum(self): 35 return self.k1 + self.k2 36 37class KeywordOnlyArgTestCase(unittest.TestCase): 38 def assertRaisesSyntaxError(self, codestr): 39 def shouldRaiseSyntaxError(s): 40 compile(s, "<test>", "single") 41 self.assertRaises(SyntaxError, shouldRaiseSyntaxError, codestr) 42 43 def testSyntaxErrorForFunctionDefinition(self): 44 self.assertRaisesSyntaxError("def f(p, *):\n pass\n") 45 self.assertRaisesSyntaxError("def f(p1, *, p1=100):\n pass\n") 46 self.assertRaisesSyntaxError("def f(p1, *k1, k1=100):\n pass\n") 47 self.assertRaisesSyntaxError("def f(p1, *, k1, k1=100):\n pass\n") 48 self.assertRaisesSyntaxError("def f(p1, *, **k1):\n pass\n") 49 self.assertRaisesSyntaxError("def f(p1, *, k1, **k1):\n pass\n") 50 self.assertRaisesSyntaxError("def f(p1, *, None, **k1):\n pass\n") 51 self.assertRaisesSyntaxError("def f(p, *, (k1, k2), **kw):\n pass\n") 52 53 def testSyntaxForManyArguments(self): 54 # more than 255 positional arguments, should compile ok 55 fundef = "def f(%s):\n pass\n" % ', '.join('i%d' % i for i in range(300)) 56 compile(fundef, "<test>", "single") 57 # more than 255 keyword-only arguments, should compile ok 58 fundef = "def f(*, %s):\n pass\n" % ', '.join('i%d' % i for i in range(300)) 59 compile(fundef, "<test>", "single") 60 61 def testTooManyPositionalErrorMessage(self): 62 def f(a, b=None, *, c=None): 63 pass 64 with self.assertRaises(TypeError) as exc: 65 f(1, 2, 3) 66 expected = (f"{f.__qualname__}() takes from 1 to 2 " 67 "positional arguments but 3 were given") 68 self.assertEqual(str(exc.exception), expected) 69 70 def testSyntaxErrorForFunctionCall(self): 71 self.assertRaisesSyntaxError("f(p, k=1, p2)") 72 self.assertRaisesSyntaxError("f(p, k1=50, *(1,2), k1=100)") 73 74 def testRaiseErrorFuncallWithUnexpectedKeywordArgument(self): 75 self.assertRaises(TypeError, keywordonly_sum, ()) 76 self.assertRaises(TypeError, keywordonly_nodefaults_sum, ()) 77 self.assertRaises(TypeError, Foo, ()) 78 try: 79 keywordonly_sum(k2=100, non_existing_arg=200) 80 self.fail("should raise TypeError") 81 except TypeError: 82 pass 83 try: 84 keywordonly_nodefaults_sum(k2=2) 85 self.fail("should raise TypeError") 86 except TypeError: 87 pass 88 89 def testFunctionCall(self): 90 self.assertEqual(1, posonly_sum(1)) 91 self.assertEqual(1+2, posonly_sum(1,**{"2":2})) 92 self.assertEqual(1+2+3, posonly_sum(1,*(2,3))) 93 self.assertEqual(1+2+3+4, posonly_sum(1,*(2,3),**{"4":4})) 94 95 self.assertEqual(1, keywordonly_sum(k2=1)) 96 self.assertEqual(1+2, keywordonly_sum(k1=1, k2=2)) 97 98 self.assertEqual(1+2, keywordonly_and_kwarg_sum(k1=1, k2=2)) 99 self.assertEqual(1+2+3, keywordonly_and_kwarg_sum(k1=1, k2=2, k3=3)) 100 self.assertEqual(1+2+3+4, 101 keywordonly_and_kwarg_sum(k1=1, k2=2, 102 **{"a":3,"b":4})) 103 104 self.assertEqual(1+2, mixedargs_sum(1, k1=2)) 105 self.assertEqual(1+2+3, mixedargs_sum(1, 2, k1=3)) 106 self.assertEqual(1+2+3+4, mixedargs_sum(1, 2, k1=3, k2=4)) 107 self.assertEqual(1+2+3+4+5, mixedargs_sum(1, 2, 3, k1=4, k2=5)) 108 109 self.assertEqual(1+2, mixedargs_sum2(1, k1=2)) 110 self.assertEqual(1+2+3, mixedargs_sum2(1, 2, k1=3)) 111 self.assertEqual(1+2+3+4, mixedargs_sum2(1, 2, k1=3, k2=4)) 112 self.assertEqual(1+2+3+4+5, mixedargs_sum2(1, 2, 3, k1=4, k2=5)) 113 self.assertEqual(1+2+3+4+5+6, 114 mixedargs_sum2(1, 2, 3, k1=4, k2=5, k3=6)) 115 self.assertEqual(1+2+3+4+5+6, 116 mixedargs_sum2(1, 2, 3, k1=4, **{'k2':5, 'k3':6})) 117 118 self.assertEqual(1, Foo(k1=1).sum()) 119 self.assertEqual(1+2, Foo(k1=1,k2=2).sum()) 120 121 self.assertEqual([1,2,3], sortnum(3,2,1)) 122 self.assertEqual([3,2,1], sortnum(1,2,3, reverse=True)) 123 124 self.assertEqual(['a','b','c'], sortwords('a','c','b')) 125 self.assertEqual(['c','b','a'], sortwords('a','c','b', reverse=True)) 126 self.assertEqual(['c','b','a'], 127 sortwords('a','c','b', reverse=True, ignore='ignore')) 128 129 def testKwDefaults(self): 130 def foo(p1,p2=0, *, k1, k2=0): 131 return p1 + p2 + k1 + k2 132 133 self.assertEqual(2, foo.__code__.co_kwonlyargcount) 134 self.assertEqual({"k2":0}, foo.__kwdefaults__) 135 foo.__kwdefaults__ = {"k1":0} 136 try: 137 foo(1,k1=10) 138 self.fail("__kwdefaults__ is not properly changed") 139 except TypeError: 140 pass 141 142 def test_kwonly_methods(self): 143 class Example: 144 def f(self, *, k1=1, k2=2): 145 return k1, k2 146 147 self.assertEqual(Example().f(k1=1, k2=2), (1, 2)) 148 self.assertEqual(Example.f(Example(), k1=1, k2=2), (1, 2)) 149 self.assertRaises(TypeError, Example.f, k1=1, k2=2) 150 151 def test_issue13343(self): 152 # The Python compiler must scan all symbols of a function to 153 # determine their scope: global, local, cell... 154 # This was not done for the default values of keyword 155 # arguments in a lambda definition, and the following line 156 # used to fail with a SystemError. 157 lambda *, k1=unittest: None 158 159 def test_mangling(self): 160 class X: 161 def f(self, *, __a=42): 162 return __a 163 self.assertEqual(X().f(), 42) 164 165 def test_default_evaluation_order(self): 166 # See issue 16967 167 a = 42 168 with self.assertRaises(NameError) as err: 169 def f(v=a, x=b, *, y=c, z=d): 170 pass 171 self.assertEqual(str(err.exception), "name 'b' is not defined") 172 with self.assertRaises(NameError) as err: 173 f = lambda v=a, x=b, *, y=c, z=d: None 174 self.assertEqual(str(err.exception), "name 'b' is not defined") 175 176 177if __name__ == "__main__": 178 unittest.main() 179