| 1 |
|
| 2 |
|
| 3 |
from __future__ import absolute_import, print_function |
| 4 |
|
| 5 |
import gc |
| 6 |
import operator |
| 7 |
import os.path |
| 8 |
import sys |
| 9 |
import threading |
| 10 |
import time |
| 11 |
import unittest |
| 12 |
|
| 13 |
import lupa |
| 14 |
import lupa.tests |
| 15 |
from lupa.tests import LupaTestCase |
| 16 |
|
| 17 |
try: |
| 18 |
import platform |
| 19 |
IS_PYPY = platform.python_implementation() == 'PyPy' |
| 20 |
except (ImportError, AttributeError): |
| 21 |
IS_PYPY = False |
| 22 |
|
| 23 |
IS_PYTHON2 = sys.version_info[0] < 3 |
| 24 |
not_in_pypy = unittest.skipIf(IS_PYPY, "test not run in PyPy") |
| 25 |
|
| 26 |
try: |
| 27 |
_next = next |
| 28 |
except NameError: |
| 29 |
def _next(o): |
| 30 |
return o.next() |
| 31 |
|
| 32 |
unicode_type = type(b'abc'.decode('ASCII') if IS_PYTHON2 else 'abc') |
| 33 |
|
| 34 |
if IS_PYTHON2: |
| 35 |
unittest.TestCase.assertRaisesRegex = unittest.TestCase.assertRaisesRegexp |
| 36 |
|
| 37 |
|
| 38 |
class SetupLuaRuntimeMixin(object): |
| 39 |
lua_runtime_kwargs = {} |
| 40 |
|
| 41 |
def setUp(self): |
| 42 |
self.lua = self.lupa.LuaRuntime(**self.lua_runtime_kwargs) |
| 43 |
|
| 44 |
def tearDown(self): |
| 45 |
self.lua = None |
| 46 |
gc.collect() |
| 47 |
|
| 48 |
|
| 49 |
class TestLuaRuntimeRefcounting(LupaTestCase): |
| 50 |
def _run_gc_test(self, run_test, off_by_one=False): |
| 51 |
gc.collect() |
| 52 |
old_count = len(gc.get_objects()) |
| 53 |
i = None |
| 54 |
for i in range(100): |
| 55 |
run_test() |
| 56 |
del i |
| 57 |
gc.collect() |
| •58 |
return |
| 59 |
|
| 60 |
new_count = len(gc.get_objects()) |
| 61 |
if off_by_one and old_count == new_count + 1: |
| 62 |
|
| 63 |
self.assertEqual(old_count, new_count + 1) |
| 64 |
elif off_by_one and old_count == new_count + 2 and ( |
| 65 |
sys.version_info[:2] == (3,7) or sys.version_info >= (3,11)): |
| 66 |
|
| 67 |
self.assertEqual(old_count, new_count + 2) |
| 68 |
else: |
| 69 |
self.assertEqual(old_count, new_count) |
| 70 |
|
| 71 |
@not_in_pypy |
| 72 |
def test_runtime_cleanup(self): |
| 73 |
def run_test(): |
| 74 |
lua = self.lupa.LuaRuntime() |
| 75 |
lua_table = lua.eval('{1,2,3,4}') |
| 76 |
del lua |
| 77 |
self.assertEqual(1, lua_table[1]) |
| 78 |
|
| 79 |
self._run_gc_test(run_test) |
| 80 |
|
| 81 |
@not_in_pypy |
| 82 |
def test_pyfunc_refcycle(self): |
| 83 |
def make_refcycle(): |
| 84 |
def use_runtime(): |
| 85 |
return lua.eval('1+1') |
| 86 |
|
| 87 |
lua = self.lupa.LuaRuntime() |
| 88 |
lua.globals()['use_runtime'] = use_runtime |
| 89 |
self.assertEqual(2, lua.eval('use_runtime()')) |
| 90 |
|
| 91 |
self._run_gc_test(make_refcycle) |
| 92 |
|
| 93 |
@not_in_pypy |
| 94 |
def test_attrgetter_refcycle(self): |
| 95 |
def make_refcycle(): |
| 96 |
def get_attr(obj, name): |
| 97 |
lua.eval('1+1') |
| 98 |
return 23 |
| 99 |
|
| 100 |
lua = self.lupa.LuaRuntime(attribute_handlers=(get_attr, None)) |
| 101 |
assert lua.eval('python.eval.huhu') == 23 |
| 102 |
|
| 103 |
|
| 104 |
|
| 105 |
self._run_gc_test(make_refcycle, off_by_one=True) |
| 106 |
|
| 107 |
|
| 108 |
class TestLuaRuntime(SetupLuaRuntimeMixin, LupaTestCase): |
| 109 |
def assertLuaResult(self, lua_expression, result): |
| 110 |
self.assertEqual(self.lua.eval(lua_expression), result) |
| 111 |
|
| 112 |
def test_lua_version(self): |
| 113 |
version = self.lua.lua_version |
| 114 |
self.assertEqual(tuple, type(version)) |
| 115 |
self.assertEqual(5, version[0]) |
| 116 |
self.assertTrue(version[1] >= 1) |
| 117 |
self.assertTrue(version[1] < 10) |
| 118 |
self.assertEqual(version, self.lupa.LUA_VERSION) |
| 119 |
|
| 120 |
def test_lua_implementation(self): |
| 121 |
lua_implementation = self.lua.lua_implementation |
| 122 |
self.assertTrue(lua_implementation.startswith("Lua"), lua_implementation) |
| 123 |
self.assertTrue(lua_implementation.split()[0] in ("Lua", "LuaJIT"), lua_implementation) |
| 124 |
|
| 125 |
def test_lua_gccollect(self): |
| 126 |
self.lua.gccollect() |
| 127 |
|
| 128 |
def test_lua_nogc(self): |
| 129 |
if self.lua.lua_version >= (5,2): |
| 130 |
self.assertTrue(self.lua.eval('collectgarbage("isrunning")')) |
| 131 |
|
| 132 |
with self.lua.nogc(): |
| 133 |
if self.lua.lua_version >= (5,2): |
| 134 |
self.assertFalse(self.lua.eval('collectgarbage("isrunning")')) |
| 135 |
|
| 136 |
if self.lua.lua_version >= (5,2): |
| 137 |
self.assertTrue(self.lua.eval('collectgarbage("isrunning")')) |
| 138 |
|
| 139 |
def test_eval(self): |
| 140 |
self.assertEqual(2, self.lua.eval('1+1')) |
| 141 |
|
| 142 |
def test_eval_multi(self): |
| 143 |
self.assertEqual((1,2,3), self.lua.eval('1,2,3')) |
| 144 |
|
| 145 |
def test_eval_args(self): |
| 146 |
self.assertEqual(2, self.lua.eval('...', 2)) |
| 147 |
|
| 148 |
def test_eval_args_multi(self): |
| 149 |
self.assertEqual((1, 2, 3), self.lua.eval('...', 1, 2, 3)) |
| 150 |
|
| 151 |
def test_eval_name_mode(self): |
| 152 |
self.assertEqual(2, self.lua.eval('1+1', name='plus', mode='t')) |
| 153 |
|
| 154 |
def test_eval_mode_error(self): |
| 155 |
if self.lupa.LUA_VERSION < (5, 2): |
| 156 |
raise unittest.SkipTest("needs lua 5.2+") |
| 157 |
self.assertRaises(self.lupa.LuaSyntaxError, self.lua.eval, '1+1', name='plus', mode='b') |
| 158 |
|
| 159 |
def test_eval_error(self): |
| 160 |
self.assertRaises(self.lupa.LuaError, self.lua.eval, '<INVALIDCODE>') |
| 161 |
|
| 162 |
def test_eval_error_cleanup(self): |
| 163 |
self.assertEqual(2, self.lua.eval('1+1')) |
| 164 |
self.assertRaises(self.lupa.LuaError, self.lua.eval, '<INVALIDCODE>') |
| 165 |
self.assertEqual(2, self.lua.eval('1+1')) |
| 166 |
self.assertRaises(self.lupa.LuaError, self.lua.eval, '<INVALIDCODE>') |
| 167 |
self.assertEqual(2, self.lua.eval('1+1')) |
| 168 |
self.assertEqual(2, self.lua.eval('1+1')) |
| 169 |
|
| 170 |
def test_eval_error_message_decoding(self): |
| 171 |
try: |
| 172 |
self.lua.eval('require "UNKNOWNöMODULEäNAME"') |
| 173 |
except self.lupa.LuaError: |
| 174 |
error = ('%s'.decode('ASCII') if IS_PYTHON2 else '%s') % sys.exc_info()[1] |
| 175 |
else: |
| 176 |
self.fail('expected error not raised') |
| 177 |
expected_message = 'module \'UNKNOWNöMODULEäNAME\' not found' |
| 178 |
if IS_PYTHON2: |
| 179 |
expected_message = expected_message.decode('UTF-8') |
| 180 |
self.assertTrue(expected_message in error, |
| 181 |
'"%s" not found in "%s"' % (expected_message, error)) |
| 182 |
|
| 183 |
def test_execute(self): |
| 184 |
self.assertEqual(2, self.lua.execute('return 1+1')) |
| 185 |
|
| 186 |
def test_execute_mode(self): |
| 187 |
self.assertEqual(2, self.lua.execute('return 1+1', name='return_plus', mode='t')) |
| 188 |
|
| 189 |
def test_execute_mode_error(self): |
| 190 |
if self.lupa.LUA_VERSION < (5, 2): |
| 191 |
raise unittest.SkipTest("needs lua 5.2+") |
| 192 |
self.assertRaises(self.lupa.LuaSyntaxError, self.lua.execute, 'return 1+1', name='plus', mode='b') |
| 193 |
|
| 194 |
def test_execute_function(self): |
| 195 |
self.assertEqual(3, self.lua.execute('f = function(i) return i+1 end; return f(2)')) |
| 196 |
|
| 197 |
def test_execute_tostring_function(self): |
| 198 |
self.assertEqual('function', self.lua.execute('f = function(i) return i+1 end; return tostring(f)')[:8]) |
| 199 |
|
| 200 |
def test_execute_args(self): |
| 201 |
self.assertEqual(2, self.lua.execute('return ...', 2)) |
| 202 |
|
| 203 |
def test_execute_args_multi(self): |
| 204 |
self.assertEqual((1, 2, 3), self.lua.execute('return ...', 1, 2, 3)) |
| 205 |
|
| 206 |
def test_function(self): |
| 207 |
function = self.lua.eval('function() return 1+1 end') |
| 208 |
self.assertNotEqual(None, function) |
| 209 |
self.assertEqual(2, function()) |
| 210 |
|
| 211 |
def test_multiple_functions(self): |
| 212 |
function1 = self.lua.eval('function() return 0+1 end') |
| 213 |
function2 = self.lua.eval('function() return 1+1 end') |
| 214 |
self.assertEqual(1, function1()) |
| 215 |
self.assertEqual(2, function2()) |
| 216 |
function3 = self.lua.eval('function() return 1+2 end') |
| 217 |
self.assertEqual(3, function3()) |
| 218 |
self.assertEqual(2, function2()) |
| 219 |
self.assertEqual(1, function1()) |
| 220 |
|
| 221 |
def test_recursive_function(self): |
| 222 |
fac = self.lua.execute('''\ |
| 223 |
function fac(i) |
| 224 |
if i <= 1 |
| 225 |
then return 1 |
| 226 |
else return i * fac(i-1) |
| 227 |
end |
| 228 |
end |
| 229 |
return fac |
| 230 |
''') |
| 231 |
self.assertNotEqual(None, fac) |
| 232 |
self.assertEqual(6, fac(3)) |
| 233 |
self.assertEqual(3628800, fac(10)) |
| 234 |
|
| 235 |
def test_double_recursive_function(self): |
| 236 |
func_code = '''\ |
| 237 |
function calc(i) |
| 238 |
if i > 2 |
| 239 |
then return calc(i-1) + calc(i-2) + 1 |
| 240 |
else return 1 |
| 241 |
end |
| 242 |
end |
| 243 |
return calc |
| 244 |
''' |
| 245 |
calc = self.lua.execute(func_code) |
| 246 |
self.assertNotEqual(None, calc) |
| 247 |
self.assertEqual(3, calc(3)) |
| 248 |
self.assertEqual(109, calc(10)) |
| 249 |
self.assertEqual(13529, calc(20)) |
| 250 |
|
| 251 |
def test_double_recursive_function_pycallback(self): |
| 252 |
func_code = '''\ |
| 253 |
function calc(pyfunc, i) |
| 254 |
if i > 2 |
| 255 |
then return pyfunc(i) + calc(pyfunc, i-1) + calc(pyfunc, i-2) + 1 |
| 256 |
else return 1 |
| 257 |
end |
| 258 |
end |
| 259 |
return calc |
| 260 |
''' |
| 261 |
def pycallback(i): |
| 262 |
return i**2 |
| 263 |
|
| 264 |
calc = self.lua.execute(func_code) |
| 265 |
|
| 266 |
self.assertNotEqual(None, calc) |
| 267 |
self.assertEqual(12, calc(pycallback, 3)) |
| 268 |
self.assertEqual(1342, calc(pycallback, 10)) |
| 269 |
self.assertEqual(185925, calc(pycallback, 20)) |
| 270 |
|
| 271 |
def test_none(self): |
| 272 |
function = self.lua.eval('function() return python.none end') |
| 273 |
self.assertEqual(None, function()) |
| 274 |
|
| 275 |
def test_pybuiltins(self): |
| 276 |
function = self.lua.eval('function() return python.builtins end') |
| 277 |
try: |
| 278 |
import __builtin__ as builtins |
| 279 |
except ImportError: |
| 280 |
import builtins |
| 281 |
self.assertEqual(builtins, function()) |
| 282 |
|
| 283 |
def test_pybuiltins_disabled(self): |
| 284 |
lua = self.lupa.LuaRuntime(register_builtins=False) |
| 285 |
self.assertEqual(True, lua.eval('python.builtins == nil')) |
| 286 |
|
| 287 |
def test_call_none(self): |
| 288 |
self.assertRaises(TypeError, self.lua.eval, 'python.none()') |
| 289 |
|
| 290 |
def test_call_non_callable(self): |
| 291 |
func = self.lua.eval('function(x) CALLED = 99; return x() end') |
| 292 |
self.assertRaises(TypeError, func, object()) |
| 293 |
self.assertEqual(99, self.lua.eval('CALLED')) |
| 294 |
|
| 295 |
def test_call_str(self): |
| 296 |
self.assertEqual("test-None", self.lua.eval('"test-" .. tostring(python.none)')) |
| 297 |
|
| 298 |
def test_call_str_py(self): |
| 299 |
function = self.lua.eval('function(x) return "test-" .. tostring(x) end') |
| 300 |
self.assertEqual("test-nil", function(None)) |
| 301 |
self.assertEqual("test-1.5", function(1.5)) |
| 302 |
|
| 303 |
def test_call_str_class(self): |
| 304 |
called = [False] |
| 305 |
class test(object): |
| 306 |
def __str__(self): |
| 307 |
called[0] = True |
| 308 |
return 'STR!!' |
| 309 |
|
| 310 |
function = self.lua.eval('function(x) return "test-" .. tostring(x) end') |
| 311 |
self.assertEqual("test-STR!!", function(test())) |
| 312 |
self.assertEqual(True, called[0]) |
| 313 |
|
| 314 |
def test_python_eval(self): |
| 315 |
eval = self.lua.eval('function() return python.eval end')() |
| 316 |
self.assertEqual(2, eval('1+1')) |
| 317 |
self.assertEqual(2, self.lua.eval('python.eval("1+1")')) |
| 318 |
|
| 319 |
def test_python_eval_disabled(self): |
| 320 |
lua = self.lupa.LuaRuntime(register_eval=False) |
| 321 |
self.assertEqual(True, lua.eval('python.eval == nil')) |
| 322 |
|
| 323 |
def test_len_table_array(self): |
| 324 |
table = self.lua.eval('{1,2,3,4,5}') |
| 325 |
self.assertEqual(5, len(table)) |
| 326 |
|
| 327 |
def test_len_table_dict(self): |
| 328 |
table = self.lua.eval('{a=1, b=2, c=3}') |
| 329 |
self.assertEqual(0, len(table)) |
| 330 |
|
| 331 |
def test_table_delattr(self): |
| 332 |
table = self.lua.eval('{a=1, b=2, c=3}') |
| 333 |
self.assertTrue('a' in table) |
| 334 |
del table.a |
| 335 |
self.assertFalse('a' in table) |
| 336 |
|
| 337 |
def test_table_delitem(self): |
| 338 |
table = self.lua.eval('{a=1, b=2, c=3}') |
| 339 |
self.assertTrue('c' in table) |
| 340 |
del table['c'] |
| 341 |
self.assertFalse('c' in table) |
| 342 |
|
| 343 |
def test_table_delitem_special(self): |
| 344 |
table = self.lua.eval('{a=1, b=2, c=3, __attr__=4}') |
| 345 |
self.assertTrue('__attr__' in table) |
| 346 |
del table['__attr__'] |
| 347 |
self.assertFalse('__attr__' in table) |
| 348 |
|
| 349 |
def test_len_table(self): |
| 350 |
table = self.lua.eval('{1,2,3,4, a=1, b=2, c=3}') |
| 351 |
self.assertEqual(4, len(table)) |
| 352 |
|
| 353 |
def test_iter_table(self): |
| 354 |
table = self.lua.eval('{2,3,4,5,6}') |
| 355 |
self.assertEqual([1,2,3,4,5], list(table)) |
| 356 |
|
| 357 |
def test_iter_table_list_repeat(self): |
| 358 |
table = self.lua.eval('{2,3,4,5,6}') |
| 359 |
self.assertEqual([1,2,3,4,5], list(table)) |
| 360 |
self.assertEqual([1,2,3,4,5], list(table)) |
| 361 |
self.assertEqual([1,2,3,4,5], list(table)) |
| 362 |
|
| 363 |
def test_iter_array_table_values(self): |
| 364 |
table = self.lua.eval('{2,3,4,5,6}') |
| 365 |
self.assertEqual([2,3,4,5,6], list(table.values())) |
| 366 |
|
| 367 |
def test_iter_array_table_repeat(self): |
| 368 |
table = self.lua.eval('{2,3,4,5,6}') |
| 369 |
self.assertEqual([2,3,4,5,6], list(table.values())) |
| 370 |
self.assertEqual([2,3,4,5,6], list(table.values())) |
| 371 |
self.assertEqual([2,3,4,5,6], list(table.values())) |
| 372 |
|
| 373 |
def test_iter_multiple_tables(self): |
| 374 |
count = 10 |
| 375 |
table_values = [self.lua.eval('{%s}' % ','.join(map(str, range(2, count+2)))).values() |
| 376 |
for _ in range(4)] |
| 377 |
|
| 378 |
|
| 379 |
l = [[] for _ in range(count)] |
| 380 |
for sublist in l: |
| 381 |
for table in table_values: |
| 382 |
sublist.append(_next(table)) |
| 383 |
|
| 384 |
self.assertEqual([[i]*len(table_values) for i in range(2, count+2)], l) |
| 385 |
|
| 386 |
def test_iter_table_repeat(self): |
| 387 |
count = 10 |
| 388 |
table_values = [self.lua.eval('{%s}' % ','.join(map(str, range(2, count+2)))).values() |
| 389 |
for _ in range(4)] |
| 390 |
|
| 391 |
|
| 392 |
l = [[] for _ in range(count)] |
| 393 |
for table in table_values: |
| 394 |
for sublist in l: |
| 395 |
sublist.append(_next(table)) |
| 396 |
|
| 397 |
self.assertEqual([[i]*len(table_values) for i in range(2,count+2)], l) |
| 398 |
|
| 399 |
def test_iter_table_refcounting(self): |
| 400 |
lua_func = self.lua.eval(''' |
| 401 |
function () |
| 402 |
local t = {} |
| 403 |
t.foo = 'bar' |
| 404 |
t.hello = 'world' |
| 405 |
return t |
| 406 |
end |
| 407 |
''') |
| 408 |
table = lua_func() |
| 409 |
for _ in range(10000): |
| 410 |
list(table.items()) |
| 411 |
|
| 412 |
def test_iter_table_mapping(self): |
| 413 |
keys = list('abcdefg') |
| 414 |
table = self.lua.eval('{%s}' % ','.join('%s=%d' % (c, i) for i, c in enumerate(keys))) |
| 415 |
l = list(table) |
| 416 |
l.sort() |
| 417 |
self.assertEqual(keys, l) |
| 418 |
|
| 419 |
def test_iter_table_mapping_int_keys(self): |
| 420 |
table = self.lua.eval('{%s}' % ','.join('[%d]=%d' % (i, -i) for i in range(10))) |
| 421 |
l = list(table) |
| 422 |
l.sort() |
| 423 |
self.assertEqual(list(range(10)), l) |
| 424 |
|
| 425 |
def test_iter_table_keys(self): |
| 426 |
keys = list('abcdefg') |
| 427 |
table = self.lua.eval('{%s}' % ','.join('%s=%d' % (c, i) for i, c in enumerate(keys))) |
| 428 |
l = list(table.keys()) |
| 429 |
l.sort() |
| 430 |
self.assertEqual(keys, l) |
| 431 |
|
| 432 |
def test_iter_table_keys_int_keys(self): |
| 433 |
table = self.lua.eval('{%s}' % ','.join('[%d]=%d' % (i, -i) for i in range(10))) |
| 434 |
l = list(table.keys()) |
| 435 |
l.sort() |
| 436 |
self.assertEqual(list(range(10)), l) |
| 437 |
|
| 438 |
def test_iter_table_values(self): |
| 439 |
keys = list('abcdefg') |
| 440 |
table = self.lua.eval('{%s}' % ','.join('%s=%d' % (c, i) for i, c in enumerate(keys))) |
| 441 |
l = list(table.values()) |
| 442 |
l.sort() |
| 443 |
self.assertEqual(list(range(len(keys))), l) |
| 444 |
|
| 445 |
def test_iter_table_values_int_keys(self): |
| 446 |
table = self.lua.eval('{%s}' % ','.join('[%d]=%d' % (i, -i) for i in range(10))) |
| 447 |
l = list(table.values()) |
| 448 |
l.sort() |
| 449 |
self.assertEqual(list(range(-9,1)), l) |
| 450 |
|
| 451 |
def test_iter_table_items(self): |
| 452 |
keys = list('abcdefg') |
| 453 |
table = self.lua.eval('{%s}' % ','.join('%s=%d' % (c, i) for i, c in enumerate(keys))) |
| 454 |
l = list(table.items()) |
| 455 |
l.sort() |
| 456 |
self.assertEqual(list(zip(keys,range(len(keys)))), l) |
| 457 |
|
| 458 |
def test_iter_table_items_int_keys(self): |
| 459 |
table = self.lua.eval('{%s}' % ','.join('[%d]=%d' % (i, -i) for i in range(10))) |
| 460 |
l = list(table.items()) |
| 461 |
l.sort() |
| 462 |
self.assertEqual(list(zip(range(10), range(0,-10,-1))), l) |
| 463 |
|
| 464 |
def test_iter_table_values_mixed(self): |
| 465 |
keys = list('abcdefg') |
| 466 |
table = self.lua.eval('{98, 99; %s}' % ','.join('%s=%d' % (c, i) for i, c in enumerate(keys))) |
| 467 |
l = list(table.values()) |
| 468 |
l.sort() |
| 469 |
self.assertEqual(list(range(len(keys))) + [98, 99], l) |
| 470 |
|
| 471 |
def test_error_iter_number(self): |
| 472 |
func = self.lua.eval('1') |
| 473 |
self.assertRaises(TypeError, list, func) |
| 474 |
|
| 475 |
def test_error_iter_function(self): |
| 476 |
func = self.lua.eval('function() return 1 end') |
| 477 |
self.assertRaises(TypeError, list, func) |
| 478 |
|
| 479 |
def test_iter_table_exaust(self): |
| 480 |
table = self.lua.table(1, 2, 3) |
| 481 |
tableiter = iter(table) |
| 482 |
self.assertEqual(next(tableiter), 1) |
| 483 |
self.assertEqual(next(tableiter), 2) |
| 484 |
self.assertEqual(next(tableiter), 3) |
| 485 |
self.assertRaises(StopIteration, next, tableiter) |
| 486 |
self.assertRaises(StopIteration, next, tableiter) |
| 487 |
self.assertRaises(StopIteration, next, tableiter) |
| 488 |
|
| 489 |
def test_string_values(self): |
| 490 |
function = self.lua.eval('function(s) return s .. "abc" end') |
| 491 |
self.assertEqual('ABCabc', function('ABC')) |
| 492 |
|
| 493 |
def test_int_values(self): |
| 494 |
function = self.lua.eval('function(i) return i + 5 end') |
| 495 |
self.assertEqual(3+5, function(3)) |
| 496 |
|
| 497 |
def test_long_values(self): |
| 498 |
try: |
| 499 |
_long = long |
| 500 |
except NameError: |
| 501 |
_long = int |
| 502 |
function = self.lua.eval('function(i) return i + 5 end') |
| 503 |
self.assertEqual(3+5, function(_long(3))) |
| 504 |
|
| 505 |
def test_float_values(self): |
| 506 |
function = self.lua.eval('function(i) return i + 5 end') |
| 507 |
self.assertEqual(float(3)+5, function(float(3))) |
| 508 |
|
| 509 |
def test_str_function(self): |
| 510 |
func = self.lua.eval('function() return 1 end') |
| 511 |
self.assertEqual('<Lua function at ', str(func)[:17]) |
| 512 |
|
| 513 |
def test_str_table(self): |
| 514 |
table = self.lua.eval('{}') |
| 515 |
self.assertEqual('<Lua table at ', str(table)[:14]) |
| 516 |
|
| 517 |
def test_create_table_args(self): |
| 518 |
table = self.lua.table(1,2,3,4,5,6) |
| 519 |
self.assertEqual(1, table[1]) |
| 520 |
self.assertEqual(3, table[3]) |
| 521 |
self.assertEqual(6, table[6]) |
| 522 |
|
| 523 |
self.assertEqual(6, len(table)) |
| 524 |
|
| 525 |
def test_create_table_kwargs(self): |
| 526 |
table = self.lua.table(a=1, b=20, c=300) |
| 527 |
self.assertEqual( 1, table['a']) |
| 528 |
self.assertEqual( 20, table['b']) |
| 529 |
self.assertEqual(300, table['c']) |
| 530 |
|
| 531 |
self.assertEqual(0, len(table)) |
| 532 |
|
| 533 |
def test_create_table_args_kwargs(self): |
| 534 |
table = self.lua.table(1,2,3,4,5,6, a=100, b=200, c=300) |
| 535 |
self.assertEqual(1, table[1]) |
| 536 |
self.assertEqual(3, table[3]) |
| 537 |
self.assertEqual(6, table[6]) |
| 538 |
|
| 539 |
self.assertEqual(100, table['a']) |
| 540 |
self.assertEqual(200, table['b']) |
| 541 |
self.assertEqual(300, table['c']) |
| 542 |
|
| 543 |
self.assertEqual(6, len(table)) |
| 544 |
|
| 545 |
def test_table_from_dict(self): |
| 546 |
table = self.lua.table_from({"foo": 1, "bar": 20, "baz": "spam", None: "python.none"}) |
| 547 |
self.assertEqual( 1, table['foo']) |
| 548 |
self.assertEqual( 20, table['bar']) |
| 549 |
self.assertEqual("spam", table['baz']) |
| 550 |
self.assertEqual("python.none", table[None]) |
| 551 |
|
| 552 |
self.assertEqual(0, len(table)) |
| 553 |
|
| 554 |
def test_table_from_int_keys(self): |
| 555 |
table = self.lua.table_from({1: 5, 2: 10, "foo": "bar"}) |
| 556 |
self.assertEqual(5, table[1]) |
| 557 |
self.assertEqual(10, table[2]) |
| 558 |
self.assertEqual("bar", table["foo"]) |
| 559 |
|
| 560 |
self.assertEqual(2, len(table)) |
| 561 |
|
| 562 |
|
| 563 |
|
| 564 |
|
| 565 |
|
| 566 |
|
| 567 |
|
| 568 |
|
| 569 |
def test_table_from_list(self): |
| 570 |
table = self.lua.table_from([1,2,5,6]) |
| 571 |
self.assertEqual(1, table[1]) |
| 572 |
self.assertEqual(2, table[2]) |
| 573 |
self.assertEqual(5, table[3]) |
| 574 |
self.assertEqual(6, table[4]) |
| 575 |
|
| 576 |
self.assertEqual(4, len(table)) |
| 577 |
|
| 578 |
def test_table_from_iterable(self): |
| 579 |
it = (x for x in range(3)) |
| 580 |
table = self.lua.table_from(it) |
| 581 |
self.assertEqual(0, table[1]) |
| 582 |
self.assertEqual(1, table[2]) |
| 583 |
self.assertEqual(2, table[3]) |
| 584 |
|
| 585 |
self.assertEqual(3, len(table)) |
| 586 |
|
| 587 |
def test_table_from_multiple_dicts(self): |
| 588 |
table = self.lua.table_from({"a": 1, "b": 2}, {"c": 3, "b": 4}) |
| 589 |
self.assertEqual(1, table["a"]) |
| 590 |
self.assertEqual(4, table["b"]) |
| 591 |
self.assertEqual(3, table["c"]) |
| 592 |
|
| 593 |
self.assertEqual(0, len(table)) |
| 594 |
|
| 595 |
def test_table_from_dicts_and_lists(self): |
| 596 |
dct, lst = {"a": 1, "b": 2}, ["foo", "bar"] |
| 597 |
for args in [[dct, lst], [lst, dct]]: |
| 598 |
table = self.lua.table_from(*args) |
| 599 |
self.assertEqual(1, table["a"]) |
| 600 |
self.assertEqual(2, table["b"]) |
| 601 |
self.assertEqual("foo", table[1]) |
| 602 |
self.assertEqual("bar", table[2]) |
| 603 |
|
| 604 |
self.assertEqual(2, len(table)) |
| 605 |
|
| 606 |
def test_table_from_multiple_lists(self): |
| 607 |
table = self.lua.table_from(["foo", "bar"], ["egg", "spam"]) |
| 608 |
self.assertEqual("foo", table[1]) |
| 609 |
self.assertEqual("bar", table[2]) |
| 610 |
self.assertEqual("egg", table[3]) |
| 611 |
self.assertEqual("spam", table[4]) |
| 612 |
|
| 613 |
self.assertEqual(4, len(table)) |
| 614 |
|
| 615 |
def test_table_from_bad(self): |
| 616 |
self.assertRaises(TypeError, self.lua.table_from, 5) |
| 617 |
self.assertRaises(TypeError, self.lua.table_from, None) |
| 618 |
self.assertRaises(TypeError, self.lua.table_from, {"a": 5}, 123) |
| 619 |
|
| 620 |
def test_table_from_nested(self): |
| 621 |
table = self.lua.table_from([[3, 3, 3]], recursive=True) |
| 622 |
self.lua.globals()["data"] = table |
| 623 |
self.assertLuaResult("data[1][1]", 3) |
| 624 |
self.assertLuaResult("data[1][2]", 3) |
| 625 |
self.assertLuaResult("data[1][3]", 3) |
| 626 |
self.assertLuaResult("type(data)", "table") |
| 627 |
self.assertLuaResult("type(data[1])", "table") |
| 628 |
self.assertLuaResult("#data", 1) |
| 629 |
self.assertLuaResult("#data[1]", 3) |
| 630 |
|
| 631 |
def test_table_from_nested2(self): |
| 632 |
table2 = self.lua.table_from([{"a": "foo"}, {"b": 1}], recursive=True) |
| 633 |
self.lua.globals()["data2"] = table2 |
| 634 |
self.assertLuaResult("#data2", 2) |
| 635 |
self.assertLuaResult("data2[1]['a']", "foo") |
| 636 |
self.assertLuaResult("data2[2]['b']", 1) |
| 637 |
|
| 638 |
def test_table_from_table(self): |
| 639 |
table1 = self.lua.eval("{3, 4, foo='bar'}") |
| 640 |
table2 = self.lua.table_from(table1) |
| 641 |
|
| 642 |
self.assertEqual(3, table2[1]) |
| 643 |
self.assertEqual(4, table2[2]) |
| 644 |
self.assertEqual("bar", table2["foo"]) |
| 645 |
|
| 646 |
|
| 647 |
table2["foo"] = "spam" |
| 648 |
self.assertEqual("spam", table2["foo"]) |
| 649 |
self.assertEqual("bar", table1["foo"]) |
| 650 |
|
| 651 |
def test_table_from_table_iter(self): |
| 652 |
table1 = self.lua.eval("{3, 4, foo='bar'}") |
| 653 |
table2 = self.lua.table_from(table1.keys()) |
| 654 |
|
| 655 |
self.assertEqual(len(table2), 3) |
| 656 |
self.assertEqual(list(table2.keys()), [1, 2, 3]) |
| 657 |
self.assertEqual(set(table2.values()), set([1, 2, "foo"])) |
| 658 |
|
| 659 |
def test_table_from_table_iter_indirect(self): |
| 660 |
table1 = self.lua.eval("{3, 4, foo='bar'}") |
| 661 |
table2 = self.lua.table_from(k for k in table1.keys()) |
| 662 |
|
| 663 |
self.assertEqual(len(table2), 3) |
| 664 |
self.assertEqual(list(table2.keys()), [1, 2, 3]) |
| 665 |
self.assertEqual(set(table2.values()), set([1, 2, "foo"])) |
| 666 |
|
| 667 |
def test_table_from_nested_dict(self): |
| 668 |
data = {"a": {"a": "foo"}, "b": {"b": "bar"}} |
| 669 |
table = self.lua.table_from(data, recursive=True) |
| 670 |
self.assertEqual(table["a"]["a"], "foo") |
| 671 |
self.assertEqual(table["b"]["b"], "bar") |
| 672 |
self.lua.globals()["data"] = table |
| 673 |
self.assertLuaResult("data.a.a", "foo") |
| 674 |
self.assertLuaResult("data.b.b", "bar") |
| 675 |
self.assertLuaResult("type(data.a)", "table") |
| 676 |
self.assertLuaResult("type(data.b)", "table") |
| 677 |
|
| 678 |
def test_table_from_nested_list(self): |
| 679 |
data = {"a": {"a": "foo"}, "b": [1, 2, 3]} |
| 680 |
table = self.lua.table_from(data, recursive=True) |
| 681 |
self.assertEqual(table["a"]["a"], "foo") |
| 682 |
self.assertEqual(table["b"][1], 1) |
| 683 |
self.assertEqual(table["b"][2], 2) |
| 684 |
self.assertEqual(table["b"][3], 3) |
| 685 |
self.lua.globals()["data"] = table |
| 686 |
self.assertLuaResult("data.a.a", "foo") |
| 687 |
self.assertLuaResult("#data.b", 3) |
| 688 |
self.lua.eval("assert(#data.b==3, 'failed')") |
| 689 |
self.assertLuaResult("type(data.a)", "table") |
| 690 |
self.assertLuaResult("type(data.b)", "table") |
| 691 |
|
| 692 |
def test_table_from_nested_list_bad(self): |
| 693 |
data = {"a": {"a": "foo"}, "b": [1, 2, 3]} |
| 694 |
table = self.lua.table_from(data) |
| 695 |
self.assertEqual(table["a"]["a"], "foo") |
| 696 |
self.assertEqual(list(table["b"]), [1, 2, 3]) |
| 697 |
self.assertEqual(table["b"][0], 1) |
| 698 |
self.assertEqual(table["b"][1], 2) |
| 699 |
self.assertEqual(table["b"][2], 3) |
| 700 |
self.lua.globals()["data"] = table |
| 701 |
self.assertLuaResult("type(data.a)", "userdata") |
| 702 |
self.assertLuaResult("type(data.b)", "userdata") |
| 703 |
|
| 704 |
def test_table_from_self_ref_obj(self): |
| 705 |
data = {} |
| 706 |
data["key"] = data |
| 707 |
l = [] |
| 708 |
l.append(l) |
| 709 |
data["list"] = l |
| 710 |
table = self.lua.table_from(data, recursive=True) |
| 711 |
self.lua.globals()["data"] = table |
| 712 |
self.assertLuaResult("type(data)", 'table') |
| 713 |
self.assertLuaResult("type(data['key'])",'table') |
| 714 |
self.assertLuaResult("type(data['list'])",'table') |
| 715 |
self.assertLuaResult("data['list']==data['list'][1]", True) |
| 716 |
self.assertLuaResult("type(data['key']['key']['key']['key'])", 'table') |
| 717 |
self.assertLuaResult("type(data['key']['key']['key']['key']['list'])", 'table') |
| 718 |
|
| 719 |
def test_table_from_nested_datastructures(self): |
| 720 |
from itertools import count |
| 721 |
def make_ds(*children): |
| 722 |
yield list(children) |
| 723 |
yield dict(zip(count(), children)) |
| 724 |
yield {chr(ord('A') + i): child for i, child in enumerate(children)} |
| 725 |
|
| 726 |
elements = [1, 2, 'x', 'y'] |
| 727 |
for ds1 in make_ds(*elements): |
| 728 |
for ds2 in make_ds(ds1): |
| 729 |
for ds3 in make_ds(ds1, elements, ds2): |
| 730 |
for ds in make_ds(ds1, ds2, ds3): |
| 731 |
with self.subTest(ds=ds): |
| 732 |
table = self.lua.table_from(ds) |
| 733 |
|
| 734 |
self.assertTrue(list(table)) |
| 735 |
|
| 736 |
|
| 737 |
|
| 738 |
|
| 739 |
|
| 740 |
|
| 741 |
|
| 742 |
|
| 743 |
|
| 744 |
def test_table_contains(self): |
| 745 |
table = self.lua.eval("{foo=5}") |
| 746 |
self.assertTrue("foo" in table) |
| 747 |
self.assertFalse("bar" in table) |
| 748 |
self.assertFalse(5 in table) |
| 749 |
|
| 750 |
def test_getattr(self): |
| 751 |
stringlib = self.lua.eval('string') |
| 752 |
self.assertEqual('abc', stringlib.lower('ABC')) |
| 753 |
|
| 754 |
def test_getitem(self): |
| 755 |
stringlib = self.lua.eval('string') |
| 756 |
self.assertEqual('abc', stringlib['lower']('ABC')) |
| 757 |
|
| 758 |
def test_getattr_table(self): |
| 759 |
table = self.lua.eval('{ const={ name="Pi", value=3.1415927 }, const2={ name="light speed", value=3e8 }, val=1 }') |
| 760 |
self.assertEqual(1, table.val) |
| 761 |
self.assertEqual('Pi', table.const.name) |
| 762 |
self.assertEqual('light speed', table.const2.name) |
| 763 |
self.assertEqual(3e8, table.const2.value) |
| 764 |
|
| 765 |
def test_getitem_table(self): |
| 766 |
table = self.lua.eval('{ const={ name="Pi", value=3.1415927 }, const2={ name="light speed", value=3e8 }, val=1 }') |
| 767 |
self.assertEqual(1, table['val']) |
| 768 |
self.assertEqual('Pi', table['const']['name']) |
| 769 |
self.assertEqual('light speed', table['const2']['name']) |
| 770 |
self.assertEqual(3e8, table['const2']['value']) |
| 771 |
|
| 772 |
def test_getitem_array(self): |
| 773 |
table = self.lua.eval('{1,2,3,4,5,6,7,8,9}') |
| 774 |
self.assertEqual(1, table[1]) |
| 775 |
self.assertEqual(5, table[5]) |
| 776 |
self.assertEqual(9, len(table)) |
| 777 |
|
| 778 |
def test_setitem_array(self): |
| 779 |
table = self.lua.eval('{1,2,3,4,5,6,7,8,9}') |
| 780 |
self.assertEqual(1, table[1]) |
| 781 |
table[1] = 0 |
| 782 |
self.assertEqual(0, table[1]) |
| 783 |
self.assertEqual(2, table[2]) |
| 784 |
self.assertEqual(9, len(table)) |
| 785 |
|
| 786 |
def test_setitem_array_none(self): |
| 787 |
table = self.lua.eval('{1,2}') |
| 788 |
get_none = self.lua.eval('function(t) return t[python.none] end') |
| 789 |
self.assertEqual(2, len(table)) |
| 790 |
self.assertEqual(None, table[None]) |
| 791 |
self.assertEqual(None, get_none(table)) |
| 792 |
table[None] = 123 |
| 793 |
self.assertEqual(123, table[None]) |
| 794 |
self.assertEqual(123, get_none(table)) |
| 795 |
self.assertEqual(2, len(table)) |
| 796 |
|
| 797 |
def test_setitem_array_none_initial(self): |
| 798 |
table = self.lua.eval('{1,python.none,3}') |
| 799 |
get_none = self.lua.eval('function(t) return t[python.none] end') |
| 800 |
self.assertEqual(3, len(table)) |
| 801 |
self.assertEqual(None, table[None]) |
| 802 |
self.assertEqual(None, get_none(table)) |
| 803 |
table[None] = 123 |
| 804 |
self.assertEqual(123, table[None]) |
| 805 |
self.assertEqual(123, get_none(table)) |
| 806 |
self.assertEqual(3, len(table)) |
| 807 |
|
| 808 |
def test_setattr_table(self): |
| 809 |
table = self.lua.eval('{ const={ name="Pi", value=3.1415927 }, const2={ name="light speed", value=3e8 }, val=1 }') |
| 810 |
|
| 811 |
self.assertEqual(1, table.val) |
| 812 |
table.val = 2 |
| 813 |
self.assertEqual(2, table.val) |
| 814 |
|
| 815 |
self.assertEqual('Pi', table.const.name) |
| 816 |
table.const.name = 'POW' |
| 817 |
self.assertEqual('POW', table.const.name) |
| 818 |
|
| 819 |
table_const_name = self.lua.eval('function(t) return t.const.name end') |
| 820 |
self.assertEqual('POW', table_const_name(table)) |
| 821 |
|
| 822 |
def test_setitem_table(self): |
| 823 |
table = self.lua.eval('{ const={ name="Pi", value=3.1415927 }, const2={ name="light speed", value=3e8 }, val=1 }') |
| 824 |
|
| 825 |
self.assertEqual(1, table.val) |
| 826 |
table['val'] = 2 |
| 827 |
self.assertEqual(2, table.val) |
| 828 |
|
| 829 |
get_val = self.lua.eval('function(t) return t.val end') |
| 830 |
self.assertEqual(2, get_val(table)) |
| 831 |
|
| 832 |
self.assertEqual('Pi', table.const.name) |
| 833 |
table['const']['name'] = 'POW' |
| 834 |
self.assertEqual('POW', table.const.name) |
| 835 |
|
| 836 |
get_table_const_name = self.lua.eval('function(t) return t.const.name end') |
| 837 |
self.assertEqual('POW', get_table_const_name(table)) |
| 838 |
|
| 839 |
def test_pygetitem(self): |
| 840 |
lua_func = self.lua.eval('function(x) return x.ATTR end') |
| 841 |
self.assertEqual(123, lua_func({'ATTR': 123})) |
| 842 |
|
| 843 |
def test_pysetitem(self): |
| 844 |
lua_func = self.lua.eval('function(x) x.ATTR = 123 end') |
| 845 |
d = {'ATTR': 321} |
| 846 |
self.assertEqual(321, d['ATTR']) |
| 847 |
lua_func(d) |
| 848 |
self.assertEqual(123, d['ATTR']) |
| 849 |
|
| 850 |
def test_pygetattr(self): |
| 851 |
lua_func = self.lua.eval('function(x) return x.ATTR end') |
| 852 |
class test(object): |
| 853 |
def __init__(self): |
| 854 |
self.ATTR = 5 |
| 855 |
self.assertEqual(test().ATTR, lua_func(test())) |
| 856 |
|
| 857 |
def test_pysetattr(self): |
| 858 |
lua_func = self.lua.eval('function(x) x.ATTR = 123 end') |
| 859 |
class test(object): |
| 860 |
def __init__(self): |
| 861 |
self.ATTR = 5 |
| 862 |
t = test() |
| 863 |
self.assertEqual(5, t.ATTR) |
| 864 |
lua_func(t) |
| 865 |
self.assertEqual(123, t.ATTR) |
| 866 |
|
| 867 |
def test_pygetattr_function(self): |
| 868 |
lua_func = self.lua.eval('function(x) x.ATTR = 123 end') |
| 869 |
def test(): pass |
| 870 |
lua_func(test) |
| 871 |
self.assertEqual(123, test.ATTR) |
| 872 |
|
| 873 |
def test_pysetattr_function(self): |
| 874 |
lua_func = self.lua.eval('function(x) x.ATTR = 123 end') |
| 875 |
def test(): pass |
| 876 |
lua_func(test) |
| 877 |
self.assertEqual(123, test.ATTR) |
| 878 |
|
| 879 |
def test_globals(self): |
| 880 |
lua_globals = self.lua.globals() |
| 881 |
self.assertNotEqual(None, lua_globals.table) |
| 882 |
|
| 883 |
def test_globals_attrs_call(self): |
| 884 |
lua_globals = self.lua.globals() |
| 885 |
self.assertNotEqual(None, lua_globals.string) |
| 886 |
self.assertEqual('test', lua_globals.string.lower("TEST")) |
| 887 |
|
| 888 |
def test_require(self): |
| 889 |
stringlib = self.lua.require('string') |
| 890 |
self.assertNotEqual(None, stringlib) |
| 891 |
self.assertNotEqual(None, stringlib.char) |
| 892 |
|
| 893 |
def test_libraries(self): |
| 894 |
libraries = self.lua.eval('{require, table, io, os, math, string, debug}') |
| 895 |
self.assertEqual(7, len(libraries)) |
| 896 |
self.assertTrue(None not in libraries) |
| 897 |
|
| 898 |
def test_callable_values(self): |
| 899 |
function = self.lua.eval('function(f) return f() + 5 end') |
| 900 |
def test(): |
| 901 |
return 3 |
| 902 |
self.assertEqual(3+5, function(test)) |
| 903 |
|
| 904 |
def test_callable_values_pass_through(self): |
| 905 |
function = self.lua.eval('function(f, n) return f(n) + 5 end') |
| 906 |
def test(n): |
| 907 |
return n |
| 908 |
self.assertEqual(2+5, function(test, 2)) |
| 909 |
|
| 910 |
def test_callable_passthrough(self): |
| 911 |
passthrough = self.lua.eval('function(f) f(); return f end') |
| 912 |
called = [False] |
| 913 |
def test(): |
| 914 |
called[0] = True |
| 915 |
self.assertEqual(test, passthrough(test)) |
| 916 |
self.assertEqual([True], called) |
| 917 |
|
| 918 |
def test_reraise(self): |
| 919 |
function = self.lua.eval('function(f) return f() + 5 end') |
| 920 |
def test(): |
| 921 |
raise ValueError("huhu") |
| 922 |
self.assertRaises(ValueError, function, test) |
| 923 |
|
| 924 |
def test_reraise_pcall(self): |
| 925 |
exception = Exception('test') |
| 926 |
def py_function(): |
| 927 |
raise exception |
| 928 |
function = self.lua.eval( |
| 929 |
'function(p) local r, err = pcall(p); return r, err end' |
| 930 |
) |
| 931 |
self.assertEqual( |
| 932 |
function(py_function), |
| 933 |
(False, exception) |
| 934 |
) |
| 935 |
|
| 936 |
def test_lua_error_after_intercepted_python_exception(self): |
| 937 |
function = self.lua.eval(''' |
| 938 |
function(p) |
| 939 |
pcall(p) |
| 940 |
print(a.b); |
| 941 |
end |
| 942 |
''') |
| 943 |
self.assertRaises( |
| 944 |
self.lupa.LuaError, |
| 945 |
function, |
| 946 |
lambda: 5/0, |
| 947 |
) |
| 948 |
|
| 949 |
def test_attribute_filter(self): |
| 950 |
def attr_filter(obj, name, setting): |
| 951 |
if isinstance(name, unicode_type): |
| 952 |
if not name.startswith('_'): |
| 953 |
return name + '1' |
| 954 |
raise AttributeError('denied') |
| 955 |
|
| 956 |
lua = self.lupa.LuaRuntime(attribute_filter=attr_filter) |
| 957 |
function = lua.eval('function(obj) return obj.__name__ end') |
| 958 |
class X(object): |
| 959 |
a = 0 |
| 960 |
a1 = 1 |
| 961 |
_a = 2 |
| 962 |
__a = 3 |
| 963 |
x = X() |
| 964 |
|
| 965 |
function = self.lua.eval('function(obj) return obj.a end') |
| 966 |
self.assertEqual(function(x), 0) |
| 967 |
function = lua.eval('function(obj) return obj.a end') |
| 968 |
self.assertEqual(function(x), 1) |
| 969 |
|
| 970 |
function = self.lua.eval('function(obj) return obj.__class__ end') |
| 971 |
self.assertEqual(function(x), X) |
| 972 |
function = lua.eval('function(obj) return obj.__class__ end') |
| 973 |
self.assertRaises(AttributeError, function, x) |
| 974 |
|
| 975 |
function = self.lua.eval('function(obj) return obj._a end') |
| 976 |
self.assertEqual(function(x), 2) |
| 977 |
function = lua.eval('function(obj) return obj._a end') |
| 978 |
self.assertRaises(AttributeError, function, x) |
| 979 |
|
| 980 |
function = self.lua.eval('function(obj) return obj._X__a end') |
| 981 |
self.assertEqual(function(x), 3) |
| 982 |
function = lua.eval('function(obj) return obj._X__a end') |
| 983 |
self.assertRaises(AttributeError, function, x) |
| 984 |
|
| 985 |
function = self.lua.eval('function(obj) return obj.a end') |
| 986 |
self.assertEqual(function(x), 0) |
| 987 |
function = lua.eval('function(obj) return obj.a end') |
| 988 |
self.assertEqual(function(x), 1) |
| 989 |
|
| 990 |
def test_lua_type(self): |
| 991 |
x = self.lua.eval('{}') |
| 992 |
self.assertEqual('table', self.lupa.lua_type(x)) |
| 993 |
|
| 994 |
x = self.lua.eval('function() return 1 end') |
| 995 |
self.assertEqual('function', self.lupa.lua_type(x)) |
| 996 |
|
| 997 |
x = self.lua.eval('function() coroutine.yield(1) end') |
| 998 |
self.assertEqual('function', self.lupa.lua_type(x)) |
| 999 |
self.assertEqual('thread', self.lupa.lua_type(x.coroutine())) |
| 1000 |
|
| 1001 |
self.assertEqual(None, self.lupa.lua_type(1)) |
| 1002 |
self.assertEqual(None, self.lupa.lua_type(1.1)) |
| 1003 |
self.assertEqual(None, self.lupa.lua_type('abc')) |
| 1004 |
self.assertEqual(None, self.lupa.lua_type({})) |
| 1005 |
self.assertEqual(None, self.lupa.lua_type([])) |
| 1006 |
self.assertEqual(None, self.lupa.lua_type(self.lupa)) |
| 1007 |
self.assertEqual(None, self.lupa.lua_type(self.lupa.lua_type)) |
| 1008 |
|
| 1009 |
def test_call_from_coroutine(self): |
| 1010 |
lua = self.lua |
| 1011 |
def f(*args, **kwargs): |
| 1012 |
return lua.eval('tostring(...)', args) |
| 1013 |
|
| 1014 |
create_thread = lua.eval(''' |
| 1015 |
function(func) |
| 1016 |
local thread = coroutine.create(function() |
| 1017 |
coroutine.yield(func()); |
| 1018 |
end); |
| 1019 |
return thread; |
| 1020 |
end''') |
| 1021 |
t = create_thread(f)() |
| 1022 |
self.assertEqual(lua.eval('coroutine.resume(...)', t), (True, '()')) |
| 1023 |
|
| 1024 |
def test_call_from_coroutine2(self): |
| 1025 |
lua = self.lua |
| 1026 |
def f(*args, **kwargs): |
| 1027 |
return lua.eval('tostring(...)', args) |
| 1028 |
|
| 1029 |
t = lua.eval(''' |
| 1030 |
function(f) |
| 1031 |
coroutine.yield(f()); |
| 1032 |
end |
| 1033 |
''').coroutine(f) |
| 1034 |
self.assertEqual(lua.eval('coroutine.resume(...)', t, f), (True, '()')) |
| 1035 |
|
| 1036 |
def test_compile(self): |
| 1037 |
lua_func = self.lua.compile('return 1 + 2') |
| 1038 |
self.assertEqual(lua_func(), 3) |
| 1039 |
lua_func = self.lua.compile('return 3 + 2', mode='t') |
| 1040 |
self.assertEqual(lua_func(), 5) |
| 1041 |
lua_func = self.lua.compile('return 1 + 3', name='huhu') |
| 1042 |
self.assertEqual(lua_func(), 4) |
| 1043 |
lua_func = self.lua.compile('return 2 + 3', name='huhu', mode='t') |
| 1044 |
self.assertEqual(lua_func(), 5) |
| 1045 |
self.assertRaises(self.lupa.LuaSyntaxError, self.lua.compile, 'function awd()') |
| 1046 |
|
| 1047 |
|
| 1048 |
class TestAttributesNoAutoEncoding(SetupLuaRuntimeMixin, LupaTestCase): |
| 1049 |
lua_runtime_kwargs = {'encoding': None} |
| 1050 |
|
| 1051 |
def test_pygetitem(self): |
| 1052 |
lua_func = self.lua.eval('function(x) return x.ATTR end') |
| 1053 |
self.assertEqual(123, lua_func({b'ATTR': 123})) |
| 1054 |
|
| 1055 |
def test_pysetitem(self): |
| 1056 |
lua_func = self.lua.eval('function(x) x.ATTR = 123 end') |
| 1057 |
d = {b'ATTR': 321} |
| 1058 |
self.assertEqual(321, d[b'ATTR']) |
| 1059 |
lua_func(d) |
| 1060 |
self.assertEqual(123, d[b'ATTR']) |
| 1061 |
|
| 1062 |
def test_pygetattr(self): |
| 1063 |
lua_func = self.lua.eval('function(x) return x.ATTR end') |
| 1064 |
class test(object): |
| 1065 |
def __init__(self): |
| 1066 |
self.ATTR = 5 |
| 1067 |
self.assertEqual(test().ATTR, lua_func(test())) |
| 1068 |
|
| 1069 |
def test_pysetattr(self): |
| 1070 |
lua_func = self.lua.eval('function(x) x.ATTR = 123 end') |
| 1071 |
class test(object): |
| 1072 |
def __init__(self): |
| 1073 |
self.ATTR = 5 |
| 1074 |
t = test() |
| 1075 |
self.assertEqual(5, t.ATTR) |
| 1076 |
lua_func(t) |
| 1077 |
self.assertEqual(123, t.ATTR) |
| 1078 |
|
| 1079 |
|
| 1080 |
class TestStrNoAutoEncoding(SetupLuaRuntimeMixin, LupaTestCase): |
| 1081 |
lua_runtime_kwargs = {'encoding': None} |
| 1082 |
|
| 1083 |
def test_call_str(self): |
| 1084 |
self.assertEqual(b"test-None", self.lua.eval('"test-" .. tostring(python.none)')) |
| 1085 |
|
| 1086 |
def test_call_str_py(self): |
| 1087 |
function = self.lua.eval('function(x) return "test-" .. tostring(x) end') |
| 1088 |
self.assertEqual(b"test-nil", function(None)) |
| 1089 |
self.assertEqual(b"test-1.5", function(1.5)) |
| 1090 |
|
| 1091 |
def test_call_str_class(self): |
| 1092 |
called = [False] |
| 1093 |
class test(object): |
| 1094 |
def __str__(self): |
| 1095 |
called[0] = True |
| 1096 |
return 'STR!!' |
| 1097 |
|
| 1098 |
function = self.lua.eval('function(x) return "test-" .. tostring(x) end') |
| 1099 |
self.assertEqual(b"test-STR!!", function(test())) |
| 1100 |
self.assertEqual(True, called[0]) |
| 1101 |
|
| 1102 |
|
| 1103 |
class TestAttributeHandlers(LupaTestCase): |
| 1104 |
def setUp(self): |
| 1105 |
self.lua = self.lupa.LuaRuntime() |
| 1106 |
self.lua_handling = self.lupa.LuaRuntime(attribute_handlers=(self.attr_getter, self.attr_setter)) |
| 1107 |
|
| 1108 |
self.x, self.y = self.X(), self.Y() |
| 1109 |
self.d = {'a': "aval", "b": "bval", "c": "cval"} |
| 1110 |
|
| 1111 |
def tearDown(self): |
| 1112 |
self.lua = None |
| 1113 |
gc.collect() |
| 1114 |
|
| 1115 |
class X(object): |
| 1116 |
a = 0 |
| 1117 |
a1 = 1 |
| 1118 |
_a = 2 |
| 1119 |
__a = 3 |
| 1120 |
|
| 1121 |
class Y(object): |
| 1122 |
a = 0 |
| 1123 |
a1 = 1 |
| 1124 |
_a = 2 |
| 1125 |
__a = 3 |
| 1126 |
|
| 1127 |
def attr_getter(self, obj, name): |
| 1128 |
if not isinstance(name, unicode_type): |
| 1129 |
raise AttributeError('bad type for attr_name') |
| 1130 |
if isinstance(obj, self.X): |
| 1131 |
if not name.startswith('_'): |
| 1132 |
value = getattr(obj, name, None) |
| 1133 |
if value is not None: |
| 1134 |
return value + 10 |
| 1135 |
return None |
| 1136 |
else: |
| 1137 |
return "forbidden" |
| 1138 |
elif isinstance(obj, dict): |
| 1139 |
if name == "c": |
| 1140 |
name = "b" |
| 1141 |
return obj.get(name, None) |
| 1142 |
return None |
| 1143 |
|
| 1144 |
def attr_setter(self, obj, name, value): |
| 1145 |
if isinstance(obj, self.Y): |
| 1146 |
return |
| 1147 |
if isinstance(obj, self.X): |
| 1148 |
if name.startswith('_'): |
| 1149 |
return |
| 1150 |
if hasattr(obj, name): |
| 1151 |
setattr(obj, name, value) |
| 1152 |
elif isinstance(obj, dict): |
| 1153 |
if 'forbid_new' in obj and name not in obj: |
| 1154 |
return |
| 1155 |
obj[name] = value |
| 1156 |
|
| 1157 |
def test_legal_arguments(self): |
| 1158 |
self.lupa.LuaRuntime(attribute_filter=None) |
| 1159 |
self.lupa.LuaRuntime(attribute_filter=len) |
| 1160 |
self.lupa.LuaRuntime(attribute_handlers=None) |
| 1161 |
self.lupa.LuaRuntime(attribute_handlers=()) |
| 1162 |
self.lupa.LuaRuntime(attribute_handlers=[len, bool]) |
| 1163 |
self.lupa.LuaRuntime(attribute_handlers=iter([len, bool])) |
| 1164 |
self.lupa.LuaRuntime(attribute_handlers=(None, None)) |
| 1165 |
self.lupa.LuaRuntime(attribute_handlers=iter([None, None])) |
| 1166 |
|
| 1167 |
def test_illegal_arguments(self): |
| 1168 |
self.assertRaises( |
| 1169 |
ValueError, self.lupa.LuaRuntime, attribute_filter=123) |
| 1170 |
self.assertRaises( |
| 1171 |
ValueError, self.lupa.LuaRuntime, attribute_handlers=(1, 2, 3, 4)) |
| 1172 |
self.assertRaises( |
| 1173 |
ValueError, self.lupa.LuaRuntime, attribute_handlers=(1,)) |
| 1174 |
self.assertRaises( |
| 1175 |
ValueError, self.lupa.LuaRuntime, attribute_handlers=(1, 2)) |
| 1176 |
self.assertRaises( |
| 1177 |
ValueError, self.lupa.LuaRuntime, attribute_handlers=(1, len)) |
| 1178 |
self.assertRaises( |
| 1179 |
ValueError, self.lupa.LuaRuntime, attribute_handlers=(len, 2)) |
| 1180 |
self.assertRaises( |
| 1181 |
ValueError, self.lupa.LuaRuntime, attribute_handlers=(len, bool), attribute_filter=bool) |
| 1182 |
|
| 1183 |
def test_attribute_setter_normal(self): |
| 1184 |
function = self.lua_handling.eval("function (obj) obj.a = 100 end") |
| 1185 |
function(self.x) |
| 1186 |
self.assertEqual(self.x.a, 100) |
| 1187 |
|
| 1188 |
def test_attribute_setter_forbid_underscore(self): |
| 1189 |
function = self.lua_handling.eval("function (obj) obj._a = 100 end") |
| 1190 |
function(self.x) |
| 1191 |
self.assertEqual(self.x._a, 2) |
| 1192 |
|
| 1193 |
def test_attribute_setter_readonly_object(self): |
| 1194 |
function = self.lua_handling.eval("function (obj) obj.a1 = 100 end") |
| 1195 |
function(self.y) |
| 1196 |
self.assertEqual(self.y.a1, 1) |
| 1197 |
|
| 1198 |
def test_attribute_setter_dict_create(self): |
| 1199 |
function = self.lua_handling.eval("function (obj) obj['x'] = 'new' end") |
| 1200 |
function(self.d) |
| 1201 |
self.assertEqual(self.d.get('x'), 'new') |
| 1202 |
|
| 1203 |
def test_attribute_setter_forbidden_dict_create(self): |
| 1204 |
self.d['forbid_new'] = True |
| 1205 |
function = self.lua_handling.eval("function (obj) obj['x'] = 'new' end") |
| 1206 |
function(self.d) |
| 1207 |
self.assertEqual(self.d.get('x'), None) |
| 1208 |
|
| 1209 |
def test_attribute_setter_dict_update(self): |
| 1210 |
function = self.lua_handling.eval("function (obj) obj['a'] = 'new' end") |
| 1211 |
function(self.d) |
| 1212 |
self.assertEqual(self.d['a'], 'new') |
| 1213 |
|
| 1214 |
def test_attribute_setter_forbidden_dict_update(self): |
| 1215 |
self.d['forbid_new'] = True |
| 1216 |
function = self.lua_handling.eval("function (obj) obj['a'] = 'new' end") |
| 1217 |
function(self.d) |
| 1218 |
self.assertEqual(self.d['a'], 'new') |
| 1219 |
|
| 1220 |
def test_attribute_getter_forbid_double_underscores(self): |
| 1221 |
function = self.lua_handling.eval('function(obj) return obj.__name__ end') |
| 1222 |
self.assertEqual(function(self.x), "forbidden") |
| 1223 |
|
| 1224 |
function = self.lua.eval('function(obj) return obj.__class__ end') |
| 1225 |
self.assertEqual(function(self.x), self.X) |
| 1226 |
function = self.lua_handling.eval('function(obj) return obj.__class__ end') |
| 1227 |
self.assertEqual(function(self.x), "forbidden") |
| 1228 |
|
| 1229 |
function = self.lua.eval('function(obj) return obj._X__a end') |
| 1230 |
self.assertEqual(function(self.x), 3) |
| 1231 |
function = self.lua_handling.eval('function(obj) return obj._X__a end') |
| 1232 |
self.assertEqual(function(self.x), "forbidden") |
| 1233 |
|
| 1234 |
def test_attribute_getter_mess_with_underscores(self): |
| 1235 |
function = self.lua.eval('function(obj) return obj._a end') |
| 1236 |
self.assertEqual(function(self.x), 2) |
| 1237 |
function = self.lua_handling.eval('function(obj) return obj._a end') |
| 1238 |
self.assertEqual(function(self.x), "forbidden") |
| 1239 |
|
| 1240 |
def test_attribute_getter_replace_values(self): |
| 1241 |
function = self.lua.eval('function(obj) return obj.a end') |
| 1242 |
self.assertEqual(function(self.x), 0) |
| 1243 |
function = self.lua_handling.eval('function(obj) return obj.a end') |
| 1244 |
self.assertEqual(function(self.x), 10) |
| 1245 |
|
| 1246 |
function = self.lua.eval('function(obj) return obj.a end') |
| 1247 |
self.assertEqual(function(self.x), 0) |
| 1248 |
function = self.lua_handling.eval('function(obj) return obj.a end') |
| 1249 |
self.assertEqual(function(self.x), 10) |
| 1250 |
|
| 1251 |
def test_attribute_getter_lenient_retrieval(self): |
| 1252 |
function = self.lua.eval('function(obj) return obj.bad_attr end') |
| 1253 |
self.assertRaises(AttributeError, function, self.y) |
| 1254 |
function = self.lua_handling.eval('function(obj) return obj.bad_attr end') |
| 1255 |
self.assertEqual(function(self.y), None) |
| 1256 |
|
| 1257 |
def test_attribute_getter_normal_dict_retrieval(self): |
| 1258 |
function = self.lua.eval('function(obj) return obj.a end') |
| 1259 |
self.assertEqual(function(self.d), "aval") |
| 1260 |
function = self.lua_handling.eval('function(obj) return obj.a end') |
| 1261 |
self.assertEqual(function(self.d), "aval") |
| 1262 |
|
| 1263 |
def test_attribute_getter_modify_dict_retrival(self): |
| 1264 |
function = self.lua.eval('function(obj) return obj.c end') |
| 1265 |
self.assertEqual(function(self.d), "cval") |
| 1266 |
function = self.lua_handling.eval('function(obj) return obj.c end') |
| 1267 |
self.assertEqual(function(self.d), "bval") |
| 1268 |
|
| 1269 |
def test_attribute_getter_lenient_dict_retrival(self): |
| 1270 |
function = self.lua.eval('function(obj) return obj.g end') |
| 1271 |
self.assertRaises(KeyError, function, self.d) |
| 1272 |
function = self.lua_handling.eval('function(obj) return obj.g end') |
| 1273 |
self.assertEqual(function(self.d), None) |
| 1274 |
|
| 1275 |
|
| 1276 |
class TestPythonObjectsInLua(SetupLuaRuntimeMixin, LupaTestCase): |
| 1277 |
def test_explicit_python_function(self): |
| 1278 |
lua_func = self.lua.eval( |
| 1279 |
'function(func)' |
| 1280 |
' t = {1, 5, 2, 4, 3};' |
| 1281 |
' table.sort(t, python.as_function(func));' |
| 1282 |
' return t end') |
| 1283 |
|
| 1284 |
def compare(a, b): |
| 1285 |
return a < b |
| 1286 |
self.assertEqual([1, 2, 3, 4, 5], list(lua_func(compare))) |
| 1287 |
|
| 1288 |
def test_type_conversion(self): |
| 1289 |
lua_type = self.lua.eval('type') |
| 1290 |
self.assertEqual('number', lua_type(1)) |
| 1291 |
self.assertEqual('string', lua_type("test")) |
| 1292 |
|
| 1293 |
def test_pyobject_wrapping_callable(self): |
| 1294 |
lua_type = self.lua.eval('type') |
| 1295 |
lua_get_call = self.lua.eval('function(obj) return getmetatable(obj).__call end') |
| 1296 |
|
| 1297 |
class Callable(object): |
| 1298 |
def __call__(self): pass |
| 1299 |
def __getitem__(self, item): pass |
| 1300 |
|
| 1301 |
self.assertEqual('userdata', lua_type(Callable())) |
| 1302 |
self.assertNotEqual(None, lua_get_call(Callable())) |
| 1303 |
|
| 1304 |
def test_pyobject_wrapping_getitem(self): |
| 1305 |
lua_type = self.lua.eval('type') |
| 1306 |
lua_get_index = self.lua.eval('function(obj) return getmetatable(obj).__index end') |
| 1307 |
|
| 1308 |
class GetItem(object): |
| 1309 |
def __getitem__(self, item): pass |
| 1310 |
|
| 1311 |
self.assertEqual('userdata', lua_type(GetItem())) |
| 1312 |
self.assertNotEqual(None, lua_get_index(GetItem())) |
| 1313 |
|
| 1314 |
def test_pyobject_wrapping_getattr(self): |
| 1315 |
lua_type = self.lua.eval('type') |
| 1316 |
lua_get_index = self.lua.eval('function(obj) return getmetatable(obj).__index end') |
| 1317 |
|
| 1318 |
class GetAttr(object): |
| 1319 |
pass |
| 1320 |
|
| 1321 |
self.assertEqual('userdata', lua_type(GetAttr())) |
| 1322 |
self.assertNotEqual(None, lua_get_index(GetAttr())) |
| 1323 |
|
| 1324 |
def test_pylist(self): |
| 1325 |
getitem = self.lua.eval('function(L, i) return L[i] end') |
| 1326 |
self.assertEqual(3, getitem([1,2,3], 2)) |
| 1327 |
|
| 1328 |
def test_python_iter_list(self): |
| 1329 |
values = self.lua.eval(''' |
| 1330 |
function(L) |
| 1331 |
local t = {} |
| 1332 |
local i = 1 |
| 1333 |
for value in python.iter(L) do |
| 1334 |
t[i] = value |
| 1335 |
i = i+1 |
| 1336 |
end |
| 1337 |
return t |
| 1338 |
end |
| 1339 |
''') |
| 1340 |
self.assertEqual([1,2,3], list(values([1,2,3]).values())) |
| 1341 |
|
| 1342 |
def test_python_enumerate_list(self): |
| 1343 |
values = self.lua.eval(''' |
| 1344 |
function(L) |
| 1345 |
local t = {} |
| 1346 |
for index, value in python.enumerate(L) do |
| 1347 |
t[ index+1 ] = value |
| 1348 |
end |
| 1349 |
return t |
| 1350 |
end |
| 1351 |
''') |
| 1352 |
self.assertEqual([1,2,3], list(values([1,2,3]).values())) |
| 1353 |
|
| 1354 |
def test_python_enumerate_list_start(self): |
| 1355 |
values = self.lua.eval(''' |
| 1356 |
function(L) |
| 1357 |
local t = {5,6,7} |
| 1358 |
for index, value in python.enumerate(L, 3) do |
| 1359 |
t[ index ] = value |
| 1360 |
end |
| 1361 |
return t |
| 1362 |
end |
| 1363 |
''') |
| 1364 |
self.assertEqual([5,6,1,2,3], list(values([1,2,3]).values())) |
| 1365 |
|
| 1366 |
def test_python_enumerate_list_start_invalid(self): |
| 1367 |
python_enumerate = self.lua.globals().python.enumerate |
| 1368 |
iterator = range(10) |
| 1369 |
self.assertRaises(self.lupa.LuaError, python_enumerate, iterator, "abc") |
| 1370 |
self.assertRaises(self.lupa.LuaError, python_enumerate, iterator, self.lua.table()) |
| 1371 |
self.assertRaises(self.lupa.LuaError, python_enumerate, iterator, python_enumerate) |
| 1372 |
|
| 1373 |
def test_python_iter_dict_items(self): |
| 1374 |
values = self.lua.eval(''' |
| 1375 |
function(d) |
| 1376 |
local t = {} |
| 1377 |
for key, value in python.iterex(d.items()) do |
| 1378 |
t[key] = value |
| 1379 |
end |
| 1380 |
return t |
| 1381 |
end |
| 1382 |
''') |
| 1383 |
table = values(self.lupa.as_attrgetter(dict(a=1, b=2, c=3))) |
| 1384 |
self.assertEqual(1, table['a']) |
| 1385 |
self.assertEqual(2, table['b']) |
| 1386 |
self.assertEqual(3, table['c']) |
| 1387 |
|
| 1388 |
def test_python_iter_list_None(self): |
| 1389 |
values = self.lua.eval(''' |
| 1390 |
function(L) |
| 1391 |
local t = {} |
| 1392 |
local i = 1 |
| 1393 |
for value in python.iter(L) do |
| 1394 |
t[i] = value |
| 1395 |
i = i + 1 |
| 1396 |
end |
| 1397 |
return t |
| 1398 |
end |
| 1399 |
''') |
| 1400 |
self.assertEqual([None, None, None], list(values([None, None, None]).values())) |
| 1401 |
|
| 1402 |
def test_python_iter_list_some_None(self): |
| 1403 |
values = self.lua.eval(''' |
| 1404 |
function(L) |
| 1405 |
local t = {} |
| 1406 |
local i = 1 |
| 1407 |
for value in python.iter(L) do |
| 1408 |
t[i] = value |
| 1409 |
i = i + 1 |
| 1410 |
end |
| 1411 |
return t |
| 1412 |
end |
| 1413 |
''') |
| 1414 |
self.assertEqual([None, 1, None], list(values([None, 1, None]).values())) |
| 1415 |
|
| 1416 |
def test_python_iter_iterator(self): |
| 1417 |
values = self.lua.eval(''' |
| 1418 |
function(L) |
| 1419 |
local t = {} |
| 1420 |
local i = 1 |
| 1421 |
for value in python.iter(L) do |
| 1422 |
t[i] = value |
| 1423 |
i = i+1 |
| 1424 |
end |
| 1425 |
return t |
| 1426 |
end |
| 1427 |
''') |
| 1428 |
self.assertEqual([3, 2, 1], list(values(reversed([1, 2, 3])).values())) |
| 1429 |
|
| 1430 |
|
| 1431 |
class TestLuaCoroutines(SetupLuaRuntimeMixin, LupaTestCase): |
| 1432 |
|
| 1433 |
@unittest.skipIf(IS_PYPY, "attribute access differs in PyPy") |
| 1434 |
def test_coroutine_object(self): |
| 1435 |
f = self.lua.eval("function(N) coroutine.yield(N) end") |
| 1436 |
gen = f.coroutine(5) |
| 1437 |
self.assertRaises(AttributeError, getattr, gen, '__setitem__') |
| 1438 |
self.assertRaises(AttributeError, setattr, gen, 'send', 5) |
| 1439 |
self.assertRaises(AttributeError, setattr, gen, 'no_such_attribute', 5) |
| 1440 |
self.assertRaises(AttributeError, getattr, gen, 'no_such_attribute') |
| 1441 |
self.assertRaises(AttributeError, gen.__getattr__, 'no_such_attribute') |
| 1442 |
|
| 1443 |
self.assertRaises(self.lupa.LuaError, gen.__call__) |
| 1444 |
self.assertTrue(hasattr(gen.send, '__call__')) |
| 1445 |
|
| 1446 |
self.assertRaises(TypeError, operator.itemgetter(1), gen) |
| 1447 |
self.assertRaises(TypeError, gen.__getitem__, 1) |
| 1448 |
|
| 1449 |
def test_coroutine_iter(self): |
| 1450 |
lua_code = '''\ |
| 1451 |
function(N) |
| 1452 |
for i=0,N do |
| 1453 |
if i%2 == 0 then coroutine.yield(0) else coroutine.yield(1) end |
| 1454 |
end |
| 1455 |
end |
| 1456 |
''' |
| 1457 |
f = self.lua.eval(lua_code) |
| 1458 |
gen = f.coroutine(5) |
| 1459 |
self.assertEqual([0,1,0,1,0,1], list(gen)) |
| 1460 |
|
| 1461 |
def test_coroutine_iter_repeat(self): |
| 1462 |
lua_code = '''\ |
| 1463 |
function(N) |
| 1464 |
for i=0,N do |
| 1465 |
if i%2 == 0 then coroutine.yield(0) else coroutine.yield(1) end |
| 1466 |
end |
| 1467 |
end |
| 1468 |
''' |
| 1469 |
f = self.lua.eval(lua_code) |
| 1470 |
gen = f.coroutine(5) |
| 1471 |
self.assertEqual([0,1,0,1,0,1], list(gen)) |
| 1472 |
|
| 1473 |
gen = f.coroutine(5) |
| 1474 |
self.assertEqual([0,1,0,1,0,1], list(gen)) |
| 1475 |
|
| 1476 |
gen = f.coroutine(5) |
| 1477 |
self.assertEqual([0,1,0,1,0,1], list(gen)) |
| 1478 |
|
| 1479 |
def test_coroutine_create_iter(self): |
| 1480 |
lua_code = '''\ |
| 1481 |
coroutine.create( |
| 1482 |
function(N) |
| 1483 |
for i=0,N do |
| 1484 |
if i%2 == 0 then coroutine.yield(0) else coroutine.yield(1) end |
| 1485 |
end |
| 1486 |
end |
| 1487 |
) |
| 1488 |
''' |
| 1489 |
co = self.lua.eval(lua_code) |
| 1490 |
gen = co(5) |
| 1491 |
self.assertEqual([0,1,0,1,0,1], list(gen)) |
| 1492 |
|
| 1493 |
def test_coroutine_create_iter_repeat(self): |
| 1494 |
lua_code = '''\ |
| 1495 |
coroutine.create( |
| 1496 |
function(N) |
| 1497 |
for i=0,N do |
| 1498 |
if i%2 == 0 then coroutine.yield(0) else coroutine.yield(1) end |
| 1499 |
end |
| 1500 |
end |
| 1501 |
) |
| 1502 |
''' |
| 1503 |
co = self.lua.eval(lua_code) |
| 1504 |
|
| 1505 |
gen = co(5) |
| 1506 |
self.assertEqual([0,1,0,1,0,1], list(gen)) |
| 1507 |
|
| 1508 |
gen = co(5) |
| 1509 |
self.assertEqual([0,1,0,1,0,1], list(gen)) |
| 1510 |
|
| 1511 |
gen = co(5) |
| 1512 |
self.assertEqual([0,1,0,1,0,1], list(gen)) |
| 1513 |
|
| 1514 |
def test_coroutine_lua_iter(self): |
| 1515 |
lua_code = '''\ |
| 1516 |
co = coroutine.create( |
| 1517 |
function(N) |
| 1518 |
for i=0,N do |
| 1519 |
if i%2 == 0 then coroutine.yield(0) else coroutine.yield(1) end |
| 1520 |
end |
| 1521 |
end |
| 1522 |
) |
| 1523 |
status, first_value = coroutine.resume(co, 5) |
| 1524 |
return co, status, first_value |
| 1525 |
''' |
| 1526 |
gen, status, first_value = self.lua.execute(lua_code) |
| 1527 |
self.assertTrue(status) |
| 1528 |
self.assertEqual([0,1,0,1,0,1], [first_value] + list(gen)) |
| 1529 |
|
| 1530 |
def test_coroutine_lua_iter_independent(self): |
| 1531 |
lua_code = '''\ |
| 1532 |
function f(N) |
| 1533 |
for i=0,N do |
| 1534 |
coroutine.yield( i%2 ) |
| 1535 |
end |
| 1536 |
end ; |
| 1537 |
co1 = coroutine.create(f) ; |
| 1538 |
co2 = coroutine.create(f) ; |
| 1539 |
|
| 1540 |
status, first_value = coroutine.resume(co2, 5) ; -- starting! |
| 1541 |
|
| 1542 |
return f, co1, co2, status, first_value |
| 1543 |
''' |
| 1544 |
f, co, lua_gen, status, first_value = self.lua.execute(lua_code) |
| 1545 |
|
| 1546 |
|
| 1547 |
gen = f.coroutine(5) |
| 1548 |
self.assertEqual([0,1,0,1,0,1], list(gen)) |
| 1549 |
|
| 1550 |
|
| 1551 |
gen = co(5) |
| 1552 |
self.assertEqual([0,1,0,1,0,1], list(gen)) |
| 1553 |
gen = co(5) |
| 1554 |
self.assertEqual([0,1,0,1,0,1], list(gen)) |
| 1555 |
|
| 1556 |
|
| 1557 |
self.assertTrue(status) |
| 1558 |
self.assertEqual([0,1,0,1,0,1], [first_value] + list(lua_gen)) |
| 1559 |
self.assertEqual([], list(lua_gen)) |
| 1560 |
|
| 1561 |
def test_coroutine_iter_pycall(self): |
| 1562 |
lua_code = '''\ |
| 1563 |
coroutine.create( |
| 1564 |
function(pyfunc, N) |
| 1565 |
for i=0,N do |
| 1566 |
if pyfunc(i) then coroutine.yield(0) else coroutine.yield(1) end |
| 1567 |
end |
| 1568 |
end |
| 1569 |
) |
| 1570 |
''' |
| 1571 |
co = self.lua.eval(lua_code) |
| 1572 |
|
| 1573 |
def pyfunc(i): |
| 1574 |
return i%2 == 0 |
| 1575 |
gen = co(pyfunc, 5) |
| 1576 |
self.assertEqual([0,1,0,1,0,1], list(gen)) |
| 1577 |
|
| 1578 |
def test_coroutine_send(self): |
| 1579 |
lua_code = '''\ |
| 1580 |
function() |
| 1581 |
local i = 0 |
| 1582 |
while coroutine.yield(i) do i = i+1 end |
| 1583 |
return i -- not i+1 ! |
| 1584 |
end |
| 1585 |
''' |
| 1586 |
count = self.lua.eval(lua_code).coroutine() |
| 1587 |
result = [count.send(value) for value in ([None] + [True] * 9 + [False])] |
| 1588 |
self.assertEqual(list(range(10)) + [9], result) |
| 1589 |
self.assertRaises(StopIteration, count.send, True) |
| 1590 |
|
| 1591 |
def test_coroutine_send_with_arguments(self): |
| 1592 |
lua_code = '''\ |
| 1593 |
function(N) |
| 1594 |
local i = 0 |
| 1595 |
while coroutine.yield(i) < N do i = i+1 end |
| 1596 |
return i -- not i+1 ! |
| 1597 |
end |
| 1598 |
''' |
| 1599 |
count = self.lua.eval(lua_code).coroutine(5) |
| 1600 |
result = [] |
| 1601 |
try: |
| 1602 |
for value in ([None] + list(range(10))): |
| 1603 |
result.append(count.send(value)) |
| 1604 |
except StopIteration: |
| 1605 |
pass |
| 1606 |
else: |
| 1607 |
self.assertTrue(False) |
| 1608 |
self.assertEqual(list(range(6)) + [5], result) |
| 1609 |
self.assertRaises(StopIteration, count.send, True) |
| 1610 |
|
| 1611 |
def test_coroutine_status(self): |
| 1612 |
lua_code = '''\ |
| 1613 |
coroutine.create( |
| 1614 |
function(N) |
| 1615 |
for i=0,N do |
| 1616 |
if i%2 == 0 then coroutine.yield(0) else coroutine.yield(1) end |
| 1617 |
end |
| 1618 |
end |
| 1619 |
) |
| 1620 |
''' |
| 1621 |
co = self.lua.eval(lua_code) |
| 1622 |
self.assertTrue(bool(co)) |
| 1623 |
gen = co(1) |
| 1624 |
self.assertTrue(bool(gen)) |
| 1625 |
self.assertEqual(0, _next(gen)) |
| 1626 |
self.assertTrue(bool(gen)) |
| 1627 |
self.assertEqual(1, _next(gen)) |
| 1628 |
self.assertTrue(bool(gen)) |
| 1629 |
self.assertRaises(StopIteration, _next, gen) |
| 1630 |
self.assertFalse(bool(gen)) |
| 1631 |
self.assertRaises(StopIteration, _next, gen) |
| 1632 |
self.assertRaises(StopIteration, _next, gen) |
| 1633 |
self.assertRaises(StopIteration, _next, gen) |
| 1634 |
|
| 1635 |
def test_coroutine_terminate_return(self): |
| 1636 |
lua_code = '''\ |
| 1637 |
coroutine.create( |
| 1638 |
function(N) |
| 1639 |
for i=0,N do |
| 1640 |
if i%2 == 0 then coroutine.yield(0) else coroutine.yield(1) end |
| 1641 |
end |
| 1642 |
return 99 |
| 1643 |
end |
| 1644 |
) |
| 1645 |
''' |
| 1646 |
co = self.lua.eval(lua_code) |
| 1647 |
|
| 1648 |
self.assertTrue(bool(co)) |
| 1649 |
gen = co(1) |
| 1650 |
self.assertTrue(bool(gen)) |
| 1651 |
self.assertEqual(0, _next(gen)) |
| 1652 |
self.assertTrue(bool(gen)) |
| 1653 |
self.assertEqual(1, _next(gen)) |
| 1654 |
self.assertTrue(bool(gen)) |
| 1655 |
self.assertEqual(99, _next(gen)) |
| 1656 |
self.assertFalse(bool(gen)) |
| 1657 |
self.assertRaises(StopIteration, _next, gen) |
| 1658 |
self.assertRaises(StopIteration, _next, gen) |
| 1659 |
self.assertRaises(StopIteration, _next, gen) |
| 1660 |
|
| 1661 |
def test_coroutine_while_status(self): |
| 1662 |
lua_code = '''\ |
| 1663 |
function(N) |
| 1664 |
for i=0,N-1 do |
| 1665 |
if i%2 == 0 then coroutine.yield(0) else coroutine.yield(1) end |
| 1666 |
end |
| 1667 |
if N < 0 then return nil end |
| 1668 |
if N%2 == 0 then return 0 else return 1 end |
| 1669 |
end |
| 1670 |
''' |
| 1671 |
f = self.lua.eval(lua_code) |
| 1672 |
gen = f.coroutine(5) |
| 1673 |
result = [] |
| 1674 |
|
| 1675 |
|
| 1676 |
|
| 1677 |
while gen: |
| 1678 |
result.append(_next(gen)) |
| 1679 |
self.assertEqual([0,1,0,1,0,1], result) |
| 1680 |
|
| 1681 |
|
| 1682 |
class TestLuaCoroutinesWithDebugHooks(SetupLuaRuntimeMixin, LupaTestCase): |
| 1683 |
|
| 1684 |
def _enable_hook(self): |
| 1685 |
self.lua.execute(''' |
| 1686 |
steps = 0 |
| 1687 |
debug.sethook(function () steps = steps + 1 end, '', 1) |
| 1688 |
''') |
| 1689 |
|
| 1690 |
def test_coroutine_yields_callback_debug_hook(self): |
| 1691 |
self.lua.execute(''' |
| 1692 |
func = function() |
| 1693 |
coroutine.yield(function() return 123 end) |
| 1694 |
end |
| 1695 |
''') |
| 1696 |
def _check(): |
| 1697 |
coro = self.lua.eval('func').coroutine() |
| 1698 |
cb = next(coro) |
| 1699 |
self.assertEqual(cb(), 123) |
| 1700 |
|
| 1701 |
|
| 1702 |
_check() |
| 1703 |
|
| 1704 |
|
| 1705 |
self._enable_hook() |
| 1706 |
_check() |
| 1707 |
|
| 1708 |
def test_coroutine_yields_callback_debug_hook_nowrap(self): |
| 1709 |
resume = self.lua.eval("coroutine.resume") |
| 1710 |
self.lua.execute(''' |
| 1711 |
func = function() |
| 1712 |
coroutine.yield(function() return 123 end) |
| 1713 |
end |
| 1714 |
''') |
| 1715 |
def _check(): |
| 1716 |
coro = self.lua.eval('func').coroutine() |
| 1717 |
ok, cb = resume(coro) |
| 1718 |
self.assertEqual(ok, True) |
| 1719 |
self.assertEqual(cb(), 123) |
| 1720 |
|
| 1721 |
|
| 1722 |
_check() |
| 1723 |
|
| 1724 |
|
| 1725 |
self._enable_hook() |
| 1726 |
_check() |
| 1727 |
|
| 1728 |
def test_coroutine_sets_callback_debug_hook(self): |
| 1729 |
self.lua.execute(''' |
| 1730 |
func = function(dct) |
| 1731 |
dct['cb'] = function() return 123 end |
| 1732 |
coroutine.yield() |
| 1733 |
end |
| 1734 |
''') |
| 1735 |
def _check(dct): |
| 1736 |
coro = self.lua.eval('func').coroutine(dct) |
| 1737 |
next(coro) |
| 1738 |
cb = dct['cb'] |
| 1739 |
self.assertEqual(cb(), 123) |
| 1740 |
|
| 1741 |
|
| 1742 |
_check({}) |
| 1743 |
|
| 1744 |
|
| 1745 |
self._enable_hook() |
| 1746 |
|
| 1747 |
|
| 1748 |
_check(self.lua.table_from({})) |
| 1749 |
|
| 1750 |
|
| 1751 |
|
| 1752 |
|
| 1753 |
def test_coroutine_sets_callback_debug_hook_nowrap(self): |
| 1754 |
resume = self.lua.eval("coroutine.resume") |
| 1755 |
self.lua.execute(''' |
| 1756 |
func = function(dct) |
| 1757 |
dct['cb'] = function() return 123 end |
| 1758 |
coroutine.yield() |
| 1759 |
end |
| 1760 |
''') |
| 1761 |
def _check(): |
| 1762 |
dct = {} |
| 1763 |
coro = self.lua.eval('func').coroutine() |
| 1764 |
resume(coro, dct) |
| 1765 |
resume(coro) |
| 1766 |
cb = dct['cb'] |
| 1767 |
self.assertEqual(cb(), 123) |
| 1768 |
|
| 1769 |
|
| 1770 |
_check() |
| 1771 |
|
| 1772 |
|
| 1773 |
self._enable_hook() |
| 1774 |
_check() |
| 1775 |
|
| 1776 |
|
| 1777 |
class TestLuaApplications(LupaTestCase): |
| 1778 |
def tearDown(self): |
| 1779 |
gc.collect() |
| 1780 |
|
| 1781 |
def test_mandelbrot(self): |
| 1782 |
|
| 1783 |
code = '''\ |
| 1784 |
function(N) |
| 1785 |
local char, unpack = string.char, unpack |
| 1786 |
if unpack == nil then unpack = table.unpack end |
| 1787 |
local result = "" |
| 1788 |
local M, ba, bb, buf = 2/N, 2^(N%8+1)-1, 2^(8-N%8), {} |
| 1789 |
for y=0,N-1 do |
| 1790 |
local Ci, b, p = y*M-1, 1, 0 |
| 1791 |
for x=0,N-1 do |
| 1792 |
local Cr = x*M-1.5 |
| 1793 |
local Zr, Zi, Zrq, Ziq = Cr, Ci, Cr*Cr, Ci*Ci |
| 1794 |
b = b + b |
| 1795 |
for i=1,49 do |
| 1796 |
Zi = Zr*Zi*2 + Ci |
| 1797 |
Zr = Zrq-Ziq + Cr |
| 1798 |
Ziq = Zi*Zi |
| 1799 |
Zrq = Zr*Zr |
| 1800 |
if Zrq+Ziq > 4.0 then b = b + 1; break; end |
| 1801 |
end |
| 1802 |
if b >= 256 then p = p + 1; buf[p] = 511 - b; b = 1; end |
| 1803 |
end |
| 1804 |
if b ~= 1 then p = p + 1; buf[p] = (ba-b)*bb; end |
| 1805 |
result = result .. char(unpack(buf, 1, p)) |
| 1806 |
end |
| 1807 |
return result |
| 1808 |
end |
| 1809 |
''' |
| 1810 |
|
| 1811 |
lua = self.lupa.LuaRuntime(encoding=None) |
| 1812 |
lua_mandelbrot = lua.eval(code) |
| 1813 |
|
| 1814 |
image_size = 128 |
| 1815 |
result_bytes = lua_mandelbrot(image_size) |
| 1816 |
self.assertEqual(type(result_bytes), type(''.encode('ASCII'))) |
| 1817 |
self.assertEqual(image_size*image_size//8, len(result_bytes)) |
| 1818 |
|
| 1819 |
|
| 1820 |
|
| 1821 |
|
| 1822 |
|
| 1823 |
|
| 1824 |
|
| 1825 |
|
| 1826 |
|
| 1827 |
|
| 1828 |
|
| 1829 |
class TestLuaRuntimeEncoding(LupaTestCase): |
| 1830 |
def tearDown(self): |
| 1831 |
gc.collect() |
| 1832 |
|
| 1833 |
test_string = '"abcüöä"' |
| 1834 |
if IS_PYTHON2: |
| 1835 |
test_string = test_string.decode('UTF-8') |
| 1836 |
|
| 1837 |
def _encoding_test(self, encoding, expected_length): |
| 1838 |
lua = self.lupa.LuaRuntime(encoding) |
| 1839 |
|
| 1840 |
self.assertEqual(unicode_type, |
| 1841 |
type(lua.eval(self.test_string))) |
| 1842 |
|
| 1843 |
self.assertEqual(self.test_string[1:-1], |
| 1844 |
lua.eval(self.test_string)) |
| 1845 |
|
| 1846 |
self.assertEqual(expected_length, |
| 1847 |
lua.eval('string.len(%s)' % self.test_string)) |
| 1848 |
|
| 1849 |
def test_utf8(self): |
| 1850 |
self._encoding_test('UTF-8', 9) |
| 1851 |
|
| 1852 |
def test_latin9(self): |
| 1853 |
self._encoding_test('ISO-8859-15', 6) |
| 1854 |
|
| 1855 |
def test_stringlib_utf8(self): |
| 1856 |
lua = self.lupa.LuaRuntime('UTF-8') |
| 1857 |
stringlib = lua.eval('string') |
| 1858 |
self.assertEqual('abc', stringlib.lower('ABC')) |
| 1859 |
|
| 1860 |
def test_stringlib_no_encoding(self): |
| 1861 |
lua = self.lupa.LuaRuntime(encoding=None) |
| 1862 |
stringlib = lua.eval('string') |
| 1863 |
self.assertEqual('abc'.encode('ASCII'), stringlib.lower('ABC'.encode('ASCII'))) |
| 1864 |
|
| 1865 |
|
| 1866 |
class TestMultipleLuaRuntimes(LupaTestCase): |
| 1867 |
def tearDown(self): |
| 1868 |
gc.collect() |
| 1869 |
|
| 1870 |
def test_multiple_runtimes(self): |
| 1871 |
lua1 = self.lupa.LuaRuntime() |
| 1872 |
|
| 1873 |
function1 = lua1.eval('function() return 1 end') |
| 1874 |
self.assertNotEqual(None, function1) |
| 1875 |
self.assertEqual(1, function1()) |
| 1876 |
|
| 1877 |
lua2 = self.lupa.LuaRuntime() |
| 1878 |
|
| 1879 |
function2 = lua2.eval('function() return 1+1 end') |
| 1880 |
self.assertNotEqual(None, function2) |
| 1881 |
self.assertEqual(1, function1()) |
| 1882 |
self.assertEqual(2, function2()) |
| 1883 |
|
| 1884 |
lua3 = self.lupa.LuaRuntime() |
| 1885 |
|
| 1886 |
self.assertEqual(1, function1()) |
| 1887 |
self.assertEqual(2, function2()) |
| 1888 |
|
| 1889 |
function3 = lua3.eval('function() return 1+1+1 end') |
| 1890 |
self.assertNotEqual(None, function3) |
| 1891 |
|
| 1892 |
del lua1, lua2, lua3 |
| 1893 |
|
| 1894 |
self.assertEqual(1, function1()) |
| 1895 |
self.assertEqual(2, function2()) |
| 1896 |
self.assertEqual(3, function3()) |
| 1897 |
|
| 1898 |
|
| 1899 |
class TestThreading(LupaTestCase): |
| 1900 |
def tearDown(self): |
| 1901 |
gc.collect() |
| 1902 |
|
| 1903 |
def _run_threads(self, threads, starter=None): |
| 1904 |
for thread in threads: |
| 1905 |
thread.start() |
| 1906 |
if starter is not None: |
| 1907 |
time.sleep(0.1) |
| 1908 |
starter.set() |
| 1909 |
for thread in threads: |
| 1910 |
thread.join() |
| 1911 |
|
| 1912 |
def test_sequential_threading(self): |
| 1913 |
func_code = '''\ |
| 1914 |
function calc(i) |
| 1915 |
if i > 2 |
| 1916 |
then return calc(i-1) + calc(i-2) + 1 |
| 1917 |
else return 1 |
| 1918 |
end |
| 1919 |
end |
| 1920 |
return calc |
| 1921 |
''' |
| 1922 |
lua = self.lupa.LuaRuntime() |
| 1923 |
functions = [ lua.execute(func_code) for _ in range(10) ] |
| 1924 |
results = [None] * len(functions) |
| 1925 |
|
| 1926 |
starter = threading.Event() |
| 1927 |
def test(i, func, *args): |
| 1928 |
starter.wait() |
| 1929 |
results[i] = func(*args) |
| 1930 |
|
| 1931 |
threads = [ threading.Thread(target=test, args=(i, func, 25)) |
| 1932 |
for i, func in enumerate(functions) ] |
| 1933 |
|
| 1934 |
self._run_threads(threads, starter) |
| 1935 |
|
| 1936 |
self.assertEqual(1, len(set(results))) |
| 1937 |
self.assertEqual(150049, results[0]) |
| 1938 |
|
| 1939 |
def test_threading(self): |
| 1940 |
func_code = '''\ |
| 1941 |
function calc(i) |
| 1942 |
if i > 2 |
| 1943 |
then return calc(i-1) + calc(i-2) + 1 |
| 1944 |
else return 1 |
| 1945 |
end |
| 1946 |
end |
| 1947 |
return calc |
| 1948 |
''' |
| 1949 |
runtimes = [ self.lupa.LuaRuntime() for _ in range(10) ] |
| 1950 |
functions = [ lua.execute(func_code) for lua in runtimes ] |
| 1951 |
|
| 1952 |
results = [None] * len(runtimes) |
| 1953 |
|
| 1954 |
def test(i, func, *args): |
| 1955 |
results[i] = func(*args) |
| 1956 |
|
| 1957 |
threads = [ threading.Thread(target=test, args=(i, func, 20)) |
| 1958 |
for i, func in enumerate(functions) ] |
| 1959 |
|
| 1960 |
self._run_threads(threads) |
| 1961 |
|
| 1962 |
self.assertEqual(1, len(set(results))) |
| 1963 |
self.assertEqual(13529, results[0]) |
| 1964 |
|
| 1965 |
def test_threading_pycallback(self): |
| 1966 |
func_code = '''\ |
| 1967 |
function calc(pyfunc, i) |
| 1968 |
if i > 2 |
| 1969 |
then return pyfunc(i) + calc(pyfunc, i-1) + calc(pyfunc, i-2) + 1 |
| 1970 |
else return 1 |
| 1971 |
end |
| 1972 |
end |
| 1973 |
return calc |
| 1974 |
''' |
| 1975 |
runtimes = [ self.lupa.LuaRuntime() for _ in range(10) ] |
| 1976 |
functions = [ lua.execute(func_code) for lua in runtimes ] |
| 1977 |
|
| 1978 |
results = [None] * len(runtimes) |
| 1979 |
|
| 1980 |
def pycallback(i): |
| 1981 |
return i**2 |
| 1982 |
|
| 1983 |
def test(i, func, *args): |
| 1984 |
results[i] = func(*args) |
| 1985 |
|
| 1986 |
threads = [ threading.Thread(target=test, args=(i, luafunc, pycallback, 20)) |
| 1987 |
for i, luafunc in enumerate(functions) ] |
| 1988 |
|
| 1989 |
self._run_threads(threads) |
| 1990 |
|
| 1991 |
self.assertEqual(1, len(set(results))) |
| 1992 |
self.assertEqual(185925, results[0]) |
| 1993 |
|
| 1994 |
def test_threading_iter(self): |
| 1995 |
values = list(range(1,100)) |
| 1996 |
lua = self.lupa.LuaRuntime() |
| 1997 |
table = lua.eval('{%s}' % ','.join(map(str, values))) |
| 1998 |
self.assertEqual(values, list(table)) |
| 1999 |
|
| 2000 |
lua_iter = iter(table) |
| 2001 |
|
| 2002 |
state_lock = threading.Lock() |
| 2003 |
running = [] |
| 2004 |
iterations_done = {} |
| 2005 |
def sync(i): |
| 2006 |
state_lock.acquire() |
| 2007 |
try: |
| 2008 |
status = iterations_done[i] |
| 2009 |
except KeyError: |
| 2010 |
status = iterations_done[i] = [0, threading.Event()] |
| 2011 |
status[0] += 1 |
| 2012 |
state_lock.release() |
| 2013 |
event = status[1] |
| 2014 |
while status[0] < len(running): |
| 2015 |
event.wait(0.1) |
| 2016 |
event.set() |
| 2017 |
|
| 2018 |
l = [] |
| 2019 |
start_event = threading.Event() |
| 2020 |
def extract(n, append = l.append): |
| 2021 |
running.append(n) |
| 2022 |
if len(running) < len(threads): |
| 2023 |
start_event.wait() |
| 2024 |
else: |
| 2025 |
start_event.set() |
| 2026 |
|
| 2027 |
for i, item in enumerate(lua_iter): |
| 2028 |
append(item) |
| 2029 |
sync(i) |
| 2030 |
running.remove(n) |
| 2031 |
|
| 2032 |
threads = [ threading.Thread(target=extract, args=(i,)) |
| 2033 |
for i in range(6) ] |
| 2034 |
self._run_threads(threads) |
| 2035 |
|
| 2036 |
orig = l[:] |
| 2037 |
l.sort() |
| 2038 |
self.assertEqual(values, l) |
| 2039 |
|
| 2040 |
def test_threading_mandelbrot(self): |
| 2041 |
|
| 2042 |
code = '''\ |
| 2043 |
function(N, i, total) |
| 2044 |
local char, unpack = string.char, unpack |
| 2045 |
if unpack == nil then unpack = table.unpack end |
| 2046 |
local result = "" |
| 2047 |
local M, ba, bb, buf = 2/N, 2^(N%8+1)-1, 2^(8-N%8), {} |
| 2048 |
local start_line, end_line = N/total * (i-1), N/total * i - 1 |
| 2049 |
for y=start_line,end_line do |
| 2050 |
local Ci, b, p = y*M-1, 1, 0 |
| 2051 |
for x=0,N-1 do |
| 2052 |
local Cr = x*M-1.5 |
| 2053 |
local Zr, Zi, Zrq, Ziq = Cr, Ci, Cr*Cr, Ci*Ci |
| 2054 |
b = b + b |
| 2055 |
for i=1,49 do |
| 2056 |
Zi = Zr*Zi*2 + Ci |
| 2057 |
Zr = Zrq-Ziq + Cr |
| 2058 |
Ziq = Zi*Zi |
| 2059 |
Zrq = Zr*Zr |
| 2060 |
if Zrq+Ziq > 4.0 then b = b + 1; break; end |
| 2061 |
end |
| 2062 |
if b >= 256 then p = p + 1; buf[p] = 511 - b; b = 1; end |
| 2063 |
end |
| 2064 |
if b ~= 1 then p = p + 1; buf[p] = (ba-b)*bb; end |
| 2065 |
result = result .. char(unpack(buf, 1, p)) |
| 2066 |
end |
| 2067 |
return result |
| 2068 |
end |
| 2069 |
''' |
| 2070 |
|
| 2071 |
empty_bytes_string = ''.encode('ASCII') |
| 2072 |
|
| 2073 |
image_size = 128 |
| 2074 |
thread_count = 4 |
| 2075 |
|
| 2076 |
lua_funcs = [ self.lupa.LuaRuntime(encoding=None).eval(code) |
| 2077 |
for _ in range(thread_count) ] |
| 2078 |
|
| 2079 |
results = [None] * thread_count |
| 2080 |
def mandelbrot(i, lua_func): |
| 2081 |
results[i] = lua_func(image_size, i+1, thread_count) |
| 2082 |
|
| 2083 |
threads = [ threading.Thread(target=mandelbrot, args=(i, lua_func)) |
| 2084 |
for i, lua_func in enumerate(lua_funcs) ] |
| 2085 |
self._run_threads(threads) |
| 2086 |
|
| 2087 |
result_bytes = empty_bytes_string.join(results) |
| 2088 |
|
| 2089 |
self.assertEqual(type(result_bytes), type(empty_bytes_string)) |
| 2090 |
self.assertEqual(image_size*image_size//8, len(result_bytes)) |
| 2091 |
|
| 2092 |
|
| 2093 |
self.assertEqual('\0'.encode('ASCII')*(image_size//8//2), |
| 2094 |
result_bytes[:image_size//8//2]) |
| 2095 |
if IS_PYTHON2: |
| 2096 |
self.assertTrue('\xFF' in result_bytes) |
| 2097 |
else: |
| 2098 |
self.assertTrue('\xFF'.encode('ISO-8859-1') in result_bytes) |
| 2099 |
|
| 2100 |
|
| 2101 |
|
| 2102 |
|
| 2103 |
|
| 2104 |
|
| 2105 |
|
| 2106 |
|
| 2107 |
|
| 2108 |
|
| 2109 |
def test_lua_gc_deadlock(self): |
| 2110 |
|
| 2111 |
lua = self.lupa.LuaRuntime() |
| 2112 |
ref = [lua.eval("{}")] |
| 2113 |
|
| 2114 |
def trigger_gc(ref): |
| 2115 |
del ref[0] |
| 2116 |
|
| 2117 |
thread = threading.Thread(target=trigger_gc, args=[ref]) |
| 2118 |
|
| 2119 |
lua.execute( |
| 2120 |
"start, join = ...; start(); join()", |
| 2121 |
thread.start, |
| 2122 |
thread.join, |
| 2123 |
) |
| 2124 |
assert not thread.is_alive(), "thread didn't finish - deadlock?" |
| 2125 |
|
| 2126 |
|
| 2127 |
class TestDontUnpackTuples(LupaTestCase): |
| 2128 |
def setUp(self): |
| 2129 |
self.lua = self.lupa.LuaRuntime() |
| 2130 |
|
| 2131 |
|
| 2132 |
|
| 2133 |
def tuple_fun(): |
| 2134 |
return "one", "two", "three", "four" |
| 2135 |
self.lua.globals()['fun'] = tuple_fun |
| 2136 |
|
| 2137 |
def tearDown(self): |
| 2138 |
self.lua = None |
| 2139 |
gc.collect() |
| 2140 |
|
| 2141 |
def test_python_function_tuple(self): |
| 2142 |
self.lua.execute("a, b, c = fun()") |
| 2143 |
self.assertEqual(("one", "two", "three", "four"), self.lua.eval("a")) |
| 2144 |
self.assertEqual(None, self.lua.eval("b")) |
| 2145 |
self.assertEqual(None, self.lua.eval("c")) |
| 2146 |
|
| 2147 |
def test_python_function_tuple_exact(self): |
| 2148 |
self.lua.execute("a = fun()") |
| 2149 |
self.assertEqual(("one", "two", "three", "four"), self.lua.eval("a")) |
| 2150 |
|
| 2151 |
|
| 2152 |
class TestUnpackTuples(LupaTestCase): |
| 2153 |
def setUp(self): |
| 2154 |
self.lua = self.lupa.LuaRuntime(unpack_returned_tuples=True) |
| 2155 |
|
| 2156 |
|
| 2157 |
|
| 2158 |
def tuple_fun(): |
| 2159 |
return "one", "two", "three", "four" |
| 2160 |
self.lua.globals()['fun'] = tuple_fun |
| 2161 |
|
| 2162 |
def tearDown(self): |
| 2163 |
self.lua = None |
| 2164 |
gc.collect() |
| 2165 |
|
| 2166 |
def test_python_function_tuple_expansion_exact(self): |
| 2167 |
self.lua.execute("a, b, c, d = fun()") |
| 2168 |
self.assertEqual("one", self.lua.eval("a")) |
| 2169 |
self.assertEqual("two", self.lua.eval("b")) |
| 2170 |
self.assertEqual("three", self.lua.eval("c")) |
| 2171 |
self.assertEqual("four", self.lua.eval("d")) |
| 2172 |
|
| 2173 |
def test_python_function_tuple_expansion_extra_args(self): |
| 2174 |
self.lua.execute("a, b, c, d, e, f = fun()") |
| 2175 |
self.assertTrue(self.lua.eval("a == 'one'")) |
| 2176 |
self.assertTrue(self.lua.eval("b == 'two'")) |
| 2177 |
self.assertTrue(self.lua.eval("c == 'three'")) |
| 2178 |
self.assertTrue(self.lua.eval("d == 'four'")) |
| 2179 |
self.assertTrue(self.lua.eval("e == nil")) |
| 2180 |
self.assertTrue(self.lua.eval("f == nil")) |
| 2181 |
self.assertEqual("one", self.lua.eval("a")) |
| 2182 |
self.assertEqual("two", self.lua.eval("b")) |
| 2183 |
self.assertEqual("three", self.lua.eval("c")) |
| 2184 |
self.assertEqual("four", self.lua.eval("d")) |
| 2185 |
self.assertEqual(None, self.lua.eval("e")) |
| 2186 |
self.assertEqual(None, self.lua.eval("f")) |
| 2187 |
|
| 2188 |
def test_python_function_tuple_expansion_missing_args(self): |
| 2189 |
self.lua.execute("a, b = fun()") |
| 2190 |
self.assertEqual("one", self.lua.eval("a")) |
| 2191 |
self.assertEqual("two", self.lua.eval("b")) |
| 2192 |
|
| 2193 |
def test_translate_None(self): |
| 2194 |
"""Lua does not understand None. Should (almost) never see it.""" |
| 2195 |
self.lua.globals()['f'] = lambda: (None, None) |
| 2196 |
|
| 2197 |
self.lua.execute("x, y = f()") |
| 2198 |
|
| 2199 |
self.assertEqual(None, self.lua.eval("x")) |
| 2200 |
self.assertEqual(self.lua.eval("x"), self.lua.eval("y")) |
| 2201 |
self.assertEqual(self.lua.eval("x"), self.lua.eval("z")) |
| 2202 |
self.assertTrue(self.lua.eval("x == y")) |
| 2203 |
self.assertTrue(self.lua.eval("x == z")) |
| 2204 |
self.assertTrue(self.lua.eval("x == nil")) |
| 2205 |
self.assertTrue(self.lua.eval("nil == z")) |
| 2206 |
|
| 2207 |
def test_python_enumerate_list_unpacked(self): |
| 2208 |
values = self.lua.eval(''' |
| 2209 |
function(L) |
| 2210 |
local t = {} |
| 2211 |
for index, a, b in python.enumerate(L) do |
| 2212 |
assert(a + 30 == b) |
| 2213 |
t[ index+1 ] = a + b |
| 2214 |
end |
| 2215 |
return t |
| 2216 |
end |
| 2217 |
''') |
| 2218 |
self.assertEqual([50, 70, 90], list(values(zip([10, 20, 30], [40, 50, 60])).values())) |
| 2219 |
|
| 2220 |
def test_python_enumerate_list_unpacked_None(self): |
| 2221 |
values = self.lua.eval(''' |
| 2222 |
function(L) |
| 2223 |
local t = {} |
| 2224 |
for index, a, b in python.enumerate(L) do |
| 2225 |
assert(a == nil) |
| 2226 |
t[ index+1 ] = b |
| 2227 |
end |
| 2228 |
return t |
| 2229 |
end |
| 2230 |
''') |
| 2231 |
self.assertEqual([3, 5], list(values(zip([None, None, None], [3, None, 5])).values())) |
| 2232 |
|
| 2233 |
def test_python_enumerate_list_start(self): |
| 2234 |
values = self.lua.eval(''' |
| 2235 |
function(L) |
| 2236 |
local t = {5,6,7} |
| 2237 |
for index, a, b, c in python.enumerate(L, 3) do |
| 2238 |
assert(c == nil) |
| 2239 |
assert(a + 10 == b) |
| 2240 |
t[ index ] = a + b |
| 2241 |
end |
| 2242 |
return t |
| 2243 |
end |
| 2244 |
''') |
| 2245 |
self.assertEqual([5, 6, 30, 50, 70], |
| 2246 |
list(values(zip([10, 20, 30], [20, 30, 40])).values())) |
| 2247 |
|
| 2248 |
|
| 2249 |
class TestMethodCall(LupaTestCase): |
| 2250 |
def setUp(self): |
| 2251 |
|
| 2252 |
self.lua = self.lupa.LuaRuntime(unpack_returned_tuples=True) |
| 2253 |
|
| 2254 |
class C(object): |
| 2255 |
def __init__(self, x): |
| 2256 |
self.x = int(x) |
| 2257 |
|
| 2258 |
def getx(self): |
| 2259 |
return self.x |
| 2260 |
|
| 2261 |
def getx1(self, n): |
| 2262 |
return int(n) + self.x |
| 2263 |
|
| 2264 |
def setx(self, v): |
| 2265 |
self.x = int(v) |
| 2266 |
|
| 2267 |
@classmethod |
| 2268 |
def classmeth(cls, v): |
| 2269 |
return v |
| 2270 |
|
| 2271 |
@staticmethod |
| 2272 |
def staticmeth(v): |
| 2273 |
return v |
| 2274 |
|
| 2275 |
class D(C): |
| 2276 |
pass |
| 2277 |
|
| 2278 |
def f(): |
| 2279 |
return 100 |
| 2280 |
|
| 2281 |
def g(n): |
| 2282 |
return int(n) + 100 |
| 2283 |
|
| 2284 |
x = C(1) |
| 2285 |
self.lua.globals()['C'] = C |
| 2286 |
self.lua.globals()['D'] = D |
| 2287 |
self.lua.globals()['x'] = x |
| 2288 |
self.lua.globals()['f'] = f |
| 2289 |
self.lua.globals()['g'] = g |
| 2290 |
self.lua.globals()['d'] = { 'F': f, "G": g } |
| 2291 |
self.lua.globals()['bound0'] = x.getx |
| 2292 |
self.lua.globals()['bound1'] = x.getx1 |
| 2293 |
|
| 2294 |
def tearDown(self): |
| 2295 |
self.lua = None |
| 2296 |
gc.collect() |
| 2297 |
|
| 2298 |
def test_method_call_as_method(self): |
| 2299 |
self.assertEqual(self.lua.eval("x:getx()"), 1) |
| 2300 |
self.assertEqual(self.lua.eval("x:getx1(2)"), 3) |
| 2301 |
self.lua.execute("x:setx(4)") |
| 2302 |
self.assertEqual(self.lua.eval("x:getx()"), 4) |
| 2303 |
self.assertEqual(self.lua.eval("x:getx1(2)"), 6) |
| 2304 |
|
| 2305 |
def test_method_call_as_attribute(self): |
| 2306 |
self.assertEqual(self.lua.eval("x.getx()"), 1) |
| 2307 |
self.assertEqual(self.lua.eval("x.getx1(2)"), 3) |
| 2308 |
self.lua.execute("x.setx(4)") |
| 2309 |
self.assertEqual(self.lua.eval("x.getx()"), 4) |
| 2310 |
self.assertEqual(self.lua.eval("x.getx1(2)"), 6) |
| 2311 |
|
| 2312 |
def test_method_call_mixed(self): |
| 2313 |
self.assertEqual(self.lua.eval("x.getx()"), 1) |
| 2314 |
self.assertEqual(self.lua.eval("x:getx1(2)"), 3) |
| 2315 |
self.assertEqual(self.lua.eval("x:getx()"), 1) |
| 2316 |
self.assertEqual(self.lua.eval("x.getx1(2)"), 3) |
| 2317 |
|
| 2318 |
self.lua.execute("x:setx(4)") |
| 2319 |
self.assertEqual(self.lua.eval("x:getx()"), 4) |
| 2320 |
self.assertEqual(self.lua.eval("x.getx1(2)"), 6) |
| 2321 |
self.assertEqual(self.lua.eval("x.getx()"), 4) |
| 2322 |
self.assertEqual(self.lua.eval("x:getx1(2)"), 6) |
| 2323 |
|
| 2324 |
self.lua.execute("x.setx(6)") |
| 2325 |
self.assertEqual(self.lua.eval("x.getx()"), 6) |
| 2326 |
self.assertEqual(self.lua.eval("x:getx()"), 6) |
| 2327 |
self.assertEqual(self.lua.eval("x.getx()"), 6) |
| 2328 |
self.assertEqual(self.lua.eval("x.getx1(2)"), 8) |
| 2329 |
self.assertEqual(self.lua.eval("x:getx1(2)"), 8) |
| 2330 |
|
| 2331 |
def test_method_call_function_lookup(self): |
| 2332 |
self.assertEqual(self.lua.eval("f()"), 100) |
| 2333 |
self.assertEqual(self.lua.eval("g(10)"), 110) |
| 2334 |
self.assertEqual(self.lua.eval("d.F()"), 100) |
| 2335 |
self.assertEqual(self.lua.eval("d.G(9)"), 109) |
| 2336 |
|
| 2337 |
def test_method_call_class_hierarchy(self): |
| 2338 |
self.assertEqual(self.lua.eval("C(5).getx()"), 5) |
| 2339 |
self.assertEqual(self.lua.eval("D(5).getx()"), 5) |
| 2340 |
|
| 2341 |
self.assertEqual(self.lua.eval("C(5):getx()"), 5) |
| 2342 |
self.assertEqual(self.lua.eval("D(5):getx()"), 5) |
| 2343 |
|
| 2344 |
def test_method_call_class_methods(self): |
| 2345 |
|
| 2346 |
self.assertEqual(self.lua.eval("C.getx(C(5))"), 5) |
| 2347 |
self.assertEqual(self.lua.eval("C.getx(D(5))"), 5) |
| 2348 |
|
| 2349 |
|
| 2350 |
self.assertEqual(self.lua.eval("C:classmeth(5)"), 5) |
| 2351 |
self.assertEqual(self.lua.eval("C.classmeth(5)"), 5) |
| 2352 |
self.assertEqual(self.lua.eval("C.staticmeth(5)"), 5) |
| 2353 |
|
| 2354 |
def test_method_call_bound(self): |
| 2355 |
self.assertEqual(self.lua.eval("bound0()"), 1) |
| 2356 |
self.assertEqual(self.lua.eval("bound1(3)"), 4) |
| 2357 |
self.assertEqual(self.lua.eval("python.eval('1 .__add__')(1)"), 2) |
| 2358 |
self.assertEqual(self.lua.eval("python.eval('1 .__add__')(2)"), 3) |
| 2359 |
|
| 2360 |
|
| 2361 |
|
| 2362 |
self.assertRaises(TypeError, self.lua.eval, "bound1(x)") |
| 2363 |
|
| 2364 |
|
| 2365 |
|
| 2366 |
|
| 2367 |
|
| 2368 |
|
| 2369 |
@lupa.unpacks_lua_table |
| 2370 |
def func_1(x): |
| 2371 |
return ("x=%s" % (x, )) |
| 2372 |
|
| 2373 |
|
| 2374 |
@lupa.unpacks_lua_table |
| 2375 |
def func_2(x, y): |
| 2376 |
return ("x=%s, y=%s" % (x, y)) |
| 2377 |
|
| 2378 |
|
| 2379 |
@lupa.unpacks_lua_table |
| 2380 |
def func_3(x, y, z='default'): |
| 2381 |
return ("x=%s, y=%s, z=%s" % (x, y, z)) |
| 2382 |
|
| 2383 |
|
| 2384 |
class MyCls_1(object): |
| 2385 |
@lupa.unpacks_lua_table_method |
| 2386 |
def meth(self, x): |
| 2387 |
return ("x=%s" % (x,)) |
| 2388 |
|
| 2389 |
|
| 2390 |
class MyCls_2(object): |
| 2391 |
@lupa.unpacks_lua_table_method |
| 2392 |
def meth(self, x, y): |
| 2393 |
return ("x=%s, y=%s" % (x, y)) |
| 2394 |
|
| 2395 |
|
| 2396 |
class MyCls_3(object): |
| 2397 |
@lupa.unpacks_lua_table_method |
| 2398 |
def meth(self, x, y, z='default'): |
| 2399 |
return ("x=%s, y=%s, z=%s" % (x, y, z)) |
| 2400 |
|
| 2401 |
|
| 2402 |
class KwargsDecoratorTest(SetupLuaRuntimeMixin, LupaTestCase): |
| 2403 |
|
| 2404 |
def __init__(self, *args, **kwargs): |
| 2405 |
super(KwargsDecoratorTest, self).__init__(*args, **kwargs) |
| 2406 |
self.arg1 = func_1 |
| 2407 |
self.arg2 = func_2 |
| 2408 |
self.arg3 = func_3 |
| 2409 |
|
| 2410 |
def assertResult(self, f, call_txt, res_txt): |
| 2411 |
lua_func = self.lua.eval("function (f) return f%s end" % call_txt) |
| 2412 |
self.assertEqual(lua_func(f), res_txt) |
| 2413 |
|
| 2414 |
def assertIncorrect(self, f, call_txt, error=TypeError): |
| 2415 |
lua_func = self.lua.eval("function (f) return f%s end" % call_txt) |
| 2416 |
self.assertRaises(error, lua_func, f) |
| 2417 |
|
| 2418 |
def test_many_args(self): |
| 2419 |
self.assertResult(self.arg2, "{x=1, y=2}", "x=1, y=2") |
| 2420 |
self.assertResult(self.arg2, "{x=2, y=1}", "x=2, y=1") |
| 2421 |
self.assertResult(self.arg2, "{y=1, x=2}", "x=2, y=1") |
| 2422 |
self.assertResult(self.arg2, "(1, 2)", "x=1, y=2") |
| 2423 |
|
| 2424 |
def test_single_arg(self): |
| 2425 |
self.assertResult(self.arg1, "{x=1}", "x=1") |
| 2426 |
self.assertResult(self.arg1, "(1)", "x=1") |
| 2427 |
self.assertResult(self.arg1, "(nil)", "x=None") |
| 2428 |
|
| 2429 |
def test_defaults(self): |
| 2430 |
self.assertResult(self.arg3, "{x=1, y=2}", "x=1, y=2, z=default") |
| 2431 |
self.assertResult(self.arg3, "{x=1, y=2, z=3}", "x=1, y=2, z=3") |
| 2432 |
|
| 2433 |
def test_defaults_incorrect(self): |
| 2434 |
self.assertIncorrect(self.arg3, "{x=1, z=3}") |
| 2435 |
|
| 2436 |
def test_kwargs_unknown(self): |
| 2437 |
self.assertIncorrect(self.arg2, "{x=1, y=2, z=3}") |
| 2438 |
self.assertIncorrect(self.arg2, "{y=2, z=3}") |
| 2439 |
self.assertIncorrect(self.arg1, "{x=1, y=2}") |
| 2440 |
|
| 2441 |
def test_posargs_bad(self): |
| 2442 |
self.assertIncorrect(self.arg1, "(1,2)") |
| 2443 |
self.assertIncorrect(self.arg1, "()") |
| 2444 |
|
| 2445 |
def test_posargs_kwargs(self): |
| 2446 |
self.assertResult(self.arg2, "{5, y=6}", "x=5, y=6") |
| 2447 |
self.assertResult(self.arg2, "{y=6, 5}", "x=5, y=6") |
| 2448 |
self.assertResult(self.arg2, "{5, [2]=6}", "x=5, y=6") |
| 2449 |
self.assertResult(self.arg2, "{[1]=5, [2]=6}", "x=5, y=6") |
| 2450 |
self.assertResult(self.arg2, "{[1]=5, y=6}", "x=5, y=6") |
| 2451 |
|
| 2452 |
self.assertResult(self.arg3, "{x=5, y=6, z=8}", "x=5, y=6, z=8") |
| 2453 |
self.assertResult(self.arg3, "{5, y=6, z=8}", "x=5, y=6, z=8") |
| 2454 |
self.assertResult(self.arg3, "{5, y=6}", "x=5, y=6, z=default") |
| 2455 |
self.assertResult(self.arg3, "{5, 6}", "x=5, y=6, z=default") |
| 2456 |
self.assertResult(self.arg3, "{5, 6, 7}", "x=5, y=6, z=7") |
| 2457 |
self.assertResult(self.arg3, "{z=7, 5, 6}", "x=5, y=6, z=7") |
| 2458 |
|
| 2459 |
def test_posargs_kwargs_bad(self): |
| 2460 |
self.assertIncorrect(self.arg2, "{5, y=6, z=7}") |
| 2461 |
self.assertIncorrect(self.arg2, "{5, [3]=6}", error=IndexError) |
| 2462 |
self.assertIncorrect(self.arg2, "{x=5, [2]=6}", error=IndexError) |
| 2463 |
|
| 2464 |
self.assertIncorrect(self.arg3, "{5, z=7}") |
| 2465 |
self.assertIncorrect(self.arg3, "{5}") |
| 2466 |
|
| 2467 |
def test_posargs_nil(self): |
| 2468 |
self.assertResult(self.arg3, "(5, nil, 6)", "x=5, y=None, z=6") |
| 2469 |
|
| 2470 |
def test_posargs_nil_first(self): |
| 2471 |
self.assertResult(self.arg3, "(nil, nil, 6)", "x=None, y=None, z=6") |
| 2472 |
|
| 2473 |
def test_posargs_nil_last(self): |
| 2474 |
self.assertResult(self.arg3, "(5, nil, nil)", "x=5, y=None, z=None") |
| 2475 |
|
| 2476 |
def test_posargs_kwargs_python_none_last(self): |
| 2477 |
self.assertResult(self.arg3, "{5, python.none, python.none}", "x=5, y=None, z=None") |
| 2478 |
|
| 2479 |
def test_posargs_python_none_last(self): |
| 2480 |
self.assertResult(self.arg3, "(5, python.none, python.none)", "x=5, y=None, z=None") |
| 2481 |
|
| 2482 |
def test_posargs_kwargs_python_none_some(self): |
| 2483 |
self.assertResult(self.arg3, "{python.none, y=python.none, z=6}", "x=None, y=None, z=6") |
| 2484 |
|
| 2485 |
def test_posargs_kwargs_python_none_all(self): |
| 2486 |
self.assertResult(self.arg3, "{x=python.none, y=python.none}", "x=None, y=None, z=default") |
| 2487 |
|
| 2488 |
|
| 2489 |
|
| 2490 |
|
| 2491 |
|
| 2492 |
|
| 2493 |
|
| 2494 |
|
| 2495 |
|
| 2496 |
|
| 2497 |
|
| 2498 |
|
| 2499 |
|
| 2500 |
|
| 2501 |
|
| 2502 |
|
| 2503 |
|
| 2504 |
|
| 2505 |
|
| 2506 |
|
| 2507 |
|
| 2508 |
|
| 2509 |
|
| 2510 |
|
| 2511 |
|
| 2512 |
class MethodKwargsDecoratorTest(KwargsDecoratorTest): |
| 2513 |
|
| 2514 |
def __init__(self, *args, **kwargs): |
| 2515 |
super(MethodKwargsDecoratorTest, self).__init__(*args, **kwargs) |
| 2516 |
self.arg1 = MyCls_1() |
| 2517 |
self.arg2 = MyCls_2() |
| 2518 |
self.arg3 = MyCls_3() |
| 2519 |
|
| 2520 |
def assertResult(self, f, call_txt, res_txt): |
| 2521 |
lua_func = self.lua.eval("function (obj) return obj:meth%s end" % call_txt) |
| 2522 |
self.assertEqual(lua_func(f), res_txt) |
| 2523 |
|
| 2524 |
def assertIncorrect(self, f, call_txt, error=TypeError): |
| 2525 |
lua_func = self.lua.eval("function (obj) return obj:meth%s end" % call_txt) |
| 2526 |
self.assertRaises(error, lua_func, f) |
| 2527 |
|
| 2528 |
|
| 2529 |
class NoEncodingKwargsDecoratorTest(KwargsDecoratorTest): |
| 2530 |
lua_runtime_kwargs = {'encoding': None} |
| 2531 |
|
| 2532 |
|
| 2533 |
class NoEncodingMethodKwargsDecoratorTest(MethodKwargsDecoratorTest): |
| 2534 |
lua_runtime_kwargs = {'encoding': None} |
| 2535 |
|
| 2536 |
|
| 2537 |
|
| 2538 |
|
| 2539 |
|
| 2540 |
try: |
| 2541 |
from thread import start_new_thread, get_ident |
| 2542 |
except ImportError: |
| 2543 |
|
| 2544 |
from _thread import start_new_thread, get_ident |
| 2545 |
|
| 2546 |
|
| 2547 |
def _wait(): |
| 2548 |
|
| 2549 |
time.sleep(0.01) |
| 2550 |
|
| 2551 |
|
| 2552 |
class TestFastRLock(LupaTestCase): |
| 2553 |
"""Copied from CPython's test.lock_tests module |
| 2554 |
""" |
| 2555 |
FastRLock = None |
| 2556 |
|
| 2557 |
def setUp(self): |
| 2558 |
for filename in os.listdir(os.path.dirname(os.path.dirname(__file__))): |
| 2559 |
if filename.startswith('lupa_lua'): |
| 2560 |
try: |
| 2561 |
module_name = "lupa." + filename.partition('.')[0] |
| 2562 |
self.FastRLock = __import__(module_name, fromlist='FastRLock', level=0).FastRLock |
| 2563 |
except ImportError: |
| 2564 |
pass |
| 2565 |
if self.FastRLock is None: |
| 2566 |
self.skipTest("No FastRLock implementation found") |
| 2567 |
self.locktype = self.FastRLock |
| 2568 |
|
| 2569 |
def tearDown(self): |
| 2570 |
gc.collect() |
| 2571 |
|
| 2572 |
class Bunch(object): |
| 2573 |
""" |
| 2574 |
A bunch of threads. |
| 2575 |
""" |
| 2576 |
def __init__(self, f, n, wait_before_exit=False): |
| 2577 |
""" |
| 2578 |
Construct a bunch of `n` threads running the same function `f`. |
| 2579 |
If `wait_before_exit` is True, the threads won't terminate until |
| 2580 |
do_finish() is called. |
| 2581 |
""" |
| 2582 |
self.f = f |
| 2583 |
self.n = n |
| 2584 |
self.started = [] |
| 2585 |
self.finished = [] |
| 2586 |
self._can_exit = not wait_before_exit |
| 2587 |
def task(): |
| 2588 |
tid = get_ident() |
| 2589 |
self.started.append(tid) |
| 2590 |
try: |
| 2591 |
f() |
| 2592 |
finally: |
| 2593 |
self.finished.append(tid) |
| 2594 |
while not self._can_exit: |
| 2595 |
_wait() |
| 2596 |
for i in range(n): |
| 2597 |
start_new_thread(task, ()) |
| 2598 |
|
| 2599 |
def wait_for_started(self): |
| 2600 |
while len(self.started) < self.n: |
| 2601 |
_wait() |
| 2602 |
|
| 2603 |
def wait_for_finished(self): |
| 2604 |
while len(self.finished) < self.n: |
| 2605 |
_wait() |
| 2606 |
|
| 2607 |
def do_finish(self): |
| 2608 |
self._can_exit = True |
| 2609 |
|
| 2610 |
|
| 2611 |
|
| 2612 |
|
| 2613 |
""" |
| 2614 |
Tests for both recursive and non-recursive locks. |
| 2615 |
""" |
| 2616 |
|
| 2617 |
def test_constructor(self): |
| 2618 |
lock = self.locktype() |
| 2619 |
del lock |
| 2620 |
|
| 2621 |
def test_acquire_destroy(self): |
| 2622 |
lock = self.locktype() |
| 2623 |
lock.acquire() |
| 2624 |
del lock |
| 2625 |
|
| 2626 |
def test_acquire_release(self): |
| 2627 |
lock = self.locktype() |
| 2628 |
lock.acquire() |
| 2629 |
lock.release() |
| 2630 |
del lock |
| 2631 |
|
| 2632 |
def test_try_acquire(self): |
| 2633 |
lock = self.locktype() |
| 2634 |
self.assertTrue(lock.acquire(False)) |
| 2635 |
lock.release() |
| 2636 |
|
| 2637 |
def test_try_acquire_contended(self): |
| 2638 |
lock = self.locktype() |
| 2639 |
lock.acquire() |
| 2640 |
result = [] |
| 2641 |
def f(): |
| 2642 |
result.append(lock.acquire(False)) |
| 2643 |
self.Bunch(f, 1).wait_for_finished() |
| 2644 |
self.assertFalse(result[0]) |
| 2645 |
lock.release() |
| 2646 |
|
| 2647 |
def test_acquire_contended(self): |
| 2648 |
lock = self.locktype() |
| 2649 |
lock.acquire() |
| 2650 |
N = 5 |
| 2651 |
def f(): |
| 2652 |
lock.acquire() |
| 2653 |
lock.release() |
| 2654 |
|
| 2655 |
b = self.Bunch(f, N) |
| 2656 |
b.wait_for_started() |
| 2657 |
_wait() |
| 2658 |
self.assertEqual(len(b.finished), 0) |
| 2659 |
lock.release() |
| 2660 |
b.wait_for_finished() |
| 2661 |
self.assertEqual(len(b.finished), N) |
| 2662 |
|
| 2663 |
|
| 2664 |
|
| 2665 |
|
| 2666 |
|
| 2667 |
|
| 2668 |
|
| 2669 |
|
| 2670 |
|
| 2671 |
|
| 2672 |
|
| 2673 |
|
| 2674 |
|
| 2675 |
|
| 2676 |
|
| 2677 |
|
| 2678 |
|
| 2679 |
def test_thread_leak(self): |
| 2680 |
|
| 2681 |
|
| 2682 |
lock = self.locktype() |
| 2683 |
def f(): |
| 2684 |
lock.acquire() |
| 2685 |
lock.release() |
| 2686 |
n = len(threading.enumerate()) |
| 2687 |
|
| 2688 |
|
| 2689 |
self.Bunch(f, 15).wait_for_finished() |
| 2690 |
self.assertEqual(n, len(threading.enumerate())) |
| 2691 |
|
| 2692 |
""" |
| 2693 |
Tests for non-recursive, weak locks |
| 2694 |
(which can be acquired and released from different threads). |
| 2695 |
""" |
| 2696 |
|
| 2697 |
def DISABLED_test_reacquire_non_recursive(self): |
| 2698 |
|
| 2699 |
lock = self.locktype() |
| 2700 |
phase = [] |
| 2701 |
def f(): |
| 2702 |
lock.acquire() |
| 2703 |
phase.append(None) |
| 2704 |
lock.acquire() |
| 2705 |
phase.append(None) |
| 2706 |
start_new_thread(f, ()) |
| 2707 |
while len(phase) == 0: |
| 2708 |
_wait() |
| 2709 |
_wait() |
| 2710 |
self.assertEqual(len(phase), 1) |
| 2711 |
lock.release() |
| 2712 |
while len(phase) == 1: |
| 2713 |
_wait() |
| 2714 |
self.assertEqual(len(phase), 2) |
| 2715 |
|
| 2716 |
def DISABLED_test_different_thread_release_succeeds(self): |
| 2717 |
|
| 2718 |
lock = self.locktype() |
| 2719 |
lock.acquire() |
| 2720 |
def f(): |
| 2721 |
lock.release() |
| 2722 |
b = self.Bunch(f, 1) |
| 2723 |
b.wait_for_finished() |
| 2724 |
lock.acquire() |
| 2725 |
lock.release() |
| 2726 |
|
| 2727 |
""" |
| 2728 |
Tests for recursive locks. |
| 2729 |
""" |
| 2730 |
def test_reacquire(self): |
| 2731 |
lock = self.locktype() |
| 2732 |
lock.acquire() |
| 2733 |
lock.acquire() |
| 2734 |
lock.release() |
| 2735 |
lock.acquire() |
| 2736 |
lock.release() |
| 2737 |
lock.release() |
| 2738 |
|
| 2739 |
def test_release_unacquired(self): |
| 2740 |
|
| 2741 |
lock = self.locktype() |
| 2742 |
self.assertRaises(RuntimeError, lock.release) |
| 2743 |
lock.acquire() |
| 2744 |
lock.acquire() |
| 2745 |
lock.release() |
| 2746 |
lock.acquire() |
| 2747 |
lock.release() |
| 2748 |
lock.release() |
| 2749 |
self.assertRaises(RuntimeError, lock.release) |
| 2750 |
|
| 2751 |
def test_different_thread_release_fails(self): |
| 2752 |
|
| 2753 |
lock = self.locktype() |
| 2754 |
def f(): |
| 2755 |
lock.acquire() |
| 2756 |
b = self.Bunch(f, 1, True) |
| 2757 |
try: |
| 2758 |
self.assertRaises(RuntimeError, lock.release) |
| 2759 |
finally: |
| 2760 |
b.do_finish() |
| 2761 |
|
| 2762 |
def test__is_owned(self): |
| 2763 |
lock = self.locktype() |
| 2764 |
self.assertFalse(lock._is_owned()) |
| 2765 |
lock.acquire() |
| 2766 |
self.assertTrue(lock._is_owned()) |
| 2767 |
lock.acquire() |
| 2768 |
self.assertTrue(lock._is_owned()) |
| 2769 |
result = [] |
| 2770 |
def f(): |
| 2771 |
result.append(lock._is_owned()) |
| 2772 |
self.Bunch(f, 1).wait_for_finished() |
| 2773 |
self.assertFalse(result[0]) |
| 2774 |
lock.release() |
| 2775 |
self.assertTrue(lock._is_owned()) |
| 2776 |
lock.release() |
| 2777 |
self.assertFalse(lock._is_owned()) |
| 2778 |
|
| 2779 |
|
| 2780 |
|
| 2781 |
|
| 2782 |
|
| 2783 |
class TestErrorStackTrace(LupaTestCase): |
| 2784 |
def test_stacktrace(self): |
| 2785 |
lua = self.lupa.LuaRuntime() |
| 2786 |
try: |
| 2787 |
lua.execute("error('abc')") |
| 2788 |
raise RuntimeError("LuaError was not raised") |
| 2789 |
except self.lupa.LuaError as e: |
| 2790 |
exc_message = e.args[0] |
| 2791 |
self.assertIn("stack traceback:", exc_message) |
| 2792 |
self.assertIn("main chunk", exc_message) |
| 2793 |
self.assertIn("error", exc_message) |
| 2794 |
|
| 2795 |
msg_lines = exc_message.splitlines() |
| 2796 |
self.assertIn("error", msg_lines[-1]) |
| 2797 |
self.assertNotIn("main chunk", msg_lines[-1]) |
| 2798 |
self.assertIn("main chunk", msg_lines[-2]) |
| 2799 |
self.assertIn("stack traceback:", msg_lines[-3]) |
| 2800 |
|
| 2801 |
def test_nil_debug(self): |
| 2802 |
lua = self.lupa.LuaRuntime() |
| 2803 |
try: |
| 2804 |
lua.execute("debug = nil") |
| 2805 |
lua.execute("error('abc')") |
| 2806 |
raise RuntimeError("LuaError was not raised") |
| 2807 |
except self.lupa.LuaError as e: |
| 2808 |
self.assertNotIn("stack traceback:", e.args[0]) |
| 2809 |
|
| 2810 |
def test_nil_debug_traceback(self): |
| 2811 |
lua = self.lupa.LuaRuntime() |
| 2812 |
try: |
| 2813 |
lua.execute("debug = nil") |
| 2814 |
lua.execute("error('abc')") |
| 2815 |
raise RuntimeError("LuaError was not raised") |
| 2816 |
except self.lupa.LuaError as e: |
| 2817 |
self.assertNotIn("stack traceback:", e.args[0]) |
| 2818 |
|
| 2819 |
|
| 2820 |
|
| 2821 |
|
| 2822 |
|
| 2823 |
class PythonArgumentsInLuaTest(SetupLuaRuntimeMixin, LupaTestCase): |
| 2824 |
|
| 2825 |
@staticmethod |
| 2826 |
def get_args(*args, **kwargs): |
| 2827 |
return args |
| 2828 |
|
| 2829 |
@staticmethod |
| 2830 |
def get_kwargs(*args, **kwargs): |
| 2831 |
return kwargs |
| 2832 |
|
| 2833 |
@staticmethod |
| 2834 |
def get_none(*args, **kwargs): |
| 2835 |
return None |
| 2836 |
|
| 2837 |
def assertEqualInLua(self, a, b): |
| 2838 |
lua_type_a = self.lupa.lua_type(a) |
| 2839 |
lua_type_b = self.lupa.lua_type(b) |
| 2840 |
if lua_type_a and lua_type_b and lua_type_a == lua_type_b: |
| 2841 |
return self.lua.eval('function(a, b) return a == b end')(a, b) |
| 2842 |
return self.assertEqual(a, b) |
| 2843 |
|
| 2844 |
def assertResult(self, txt, args, kwargs): |
| 2845 |
lua_func = self.lua.eval('function (f) return f(%s) end' % txt) |
| 2846 |
|
| 2847 |
|
| 2848 |
|
| 2849 |
obtained_args = lua_func(self.get_args) |
| 2850 |
self.assertEqual(len(obtained_args), len(args)) |
| 2851 |
for a, b in zip(obtained_args, args): |
| 2852 |
self.assertEqualInLua(a, b) |
| 2853 |
|
| 2854 |
obtained_kwargs = lua_func(self.get_kwargs) |
| 2855 |
self.assertEqual(len(obtained_kwargs), len(kwargs)) |
| 2856 |
for key in kwargs: |
| 2857 |
self.assertEqualInLua(obtained_kwargs[key], kwargs[key]) |
| 2858 |
|
| 2859 |
def assertIncorrect(self, txt, error=TypeError, regex=''): |
| 2860 |
lua_func = self.lua.eval('function (f) return f(%s) end' % txt) |
| 2861 |
self.assertRaisesRegex(error, regex, lua_func, self.get_none) |
| 2862 |
|
| 2863 |
def test_no_table(self): |
| 2864 |
self.assertIncorrect('python.args()', error=self.lupa.LuaError) |
| 2865 |
|
| 2866 |
def test_no_args(self): |
| 2867 |
self.assertResult('python.args{}', (), {}) |
| 2868 |
|
| 2869 |
def test_all_types(self): |
| 2870 |
|
| 2871 |
args = self.lua.eval(''' |
| 2872 |
{ |
| 2873 |
42, |
| 2874 |
false, |
| 2875 |
"spam", |
| 2876 |
function() end, |
| 2877 |
coroutine.create(function() end), |
| 2878 |
{1, 2, 3}, |
| 2879 |
python.none, |
| 2880 |
} |
| 2881 |
''') |
| 2882 |
self.lua.globals()['args'] = args |
| 2883 |
self.assertResult('python.args(args)', tuple(args[i+1] for i in range(len(args))), {}) |
| 2884 |
|
| 2885 |
|
| 2886 |
kwargs = self.lua.table() |
| 2887 |
self.lua.globals()['kwargs'] = kwargs |
| 2888 |
self.lua.execute(''' |
| 2889 |
for _, v in ipairs(args) do |
| 2890 |
kwargs[type(v)] = v |
| 2891 |
end |
| 2892 |
''') |
| 2893 |
self.assertResult('python.args(kwargs)', (), dict(kwargs.items())) |
| 2894 |
|
| 2895 |
|
| 2896 |
for objtype in kwargs: |
| 2897 |
if objtype != 'table': |
| 2898 |
self.assertIncorrect('python.args(kwargs["%s"])' % objtype, |
| 2899 |
error=self.lupa.LuaError, regex="bad argument #1 to 'args'") |
| 2900 |
|
| 2901 |
|
| 2902 |
self.assertIncorrect('python.args{[0] = true}', error=IndexError, regex='table index out of range') |
| 2903 |
self.assertIncorrect('python.args{[2] = true}', error=IndexError, regex='table index out of range') |
| 2904 |
self.assertIncorrect('python.args{[3.14] = true}', regex='table key is neither an integer nor a string') |
| 2905 |
for objtype in kwargs: |
| 2906 |
if objtype not in {'number', 'string'}: |
| 2907 |
self.assertIncorrect('python.args{[kwargs["%s"]] = true}' % objtype, |
| 2908 |
regex='table key is neither an integer nor a string') |
| 2909 |
|
| 2910 |
def test_kwargs_merge(self): |
| 2911 |
self.assertResult('python.args{1, a=1}, python.args{2}, python.args{}, python.args{b=2}', (1, 2), dict(a=1, b=2)) |
| 2912 |
|
| 2913 |
def test_kwargs_merge_conflict(self): |
| 2914 |
self.assertIncorrect('python.args{a=1}, python.args{a=2}', regex='multiple values') |
| 2915 |
|
| 2916 |
|
| 2917 |
class PythonArgumentsInLuaMethodsTest(PythonArgumentsInLuaTest): |
| 2918 |
|
| 2919 |
def get_args(self, *args, **kwargs): |
| 2920 |
return args |
| 2921 |
|
| 2922 |
def get_kwargs(self, *args, **kwargs): |
| 2923 |
return kwargs |
| 2924 |
|
| 2925 |
def get_none(self, *args, **kwargs): |
| 2926 |
return None |
| 2927 |
|
| 2928 |
def test_self_arg(self): |
| 2929 |
self.lua.globals()['self'] = self |
| 2930 |
self.assertResult('python.args{self}', (), {}) |
| 2931 |
self.assertResult('python.args{self, 1, a=2}', (1, ), dict(a=2)) |
| 2932 |
self.assertIncorrect('python.args{self=self}', regex='multiple values') |
| 2933 |
self.assertIncorrect('python.args{self, self=self}', regex='multiple values') |
| 2934 |
|
| 2935 |
|
| 2936 |
|
| 2937 |
|
| 2938 |
|
| 2939 |
class TestTableAccessError(SetupLuaRuntimeMixin, LupaTestCase): |
| 2940 |
def test_error_index_metamethod(self): |
| 2941 |
self.lua.execute(''' |
| 2942 |
t = {} |
| 2943 |
called = 0 |
| 2944 |
setmetatable(t, {__index = function() |
| 2945 |
called = called + 1 |
| 2946 |
error('my error message') |
| 2947 |
end}) |
| 2948 |
''') |
| 2949 |
lua_t = self.lua.eval('t') |
| 2950 |
self.assertRaisesRegex(self.lupa.LuaError, 'my error message', lambda t, k: t[k], lua_t, 'k') |
| 2951 |
self.assertEqual(self.lua.eval('called'), 1) |
| 2952 |
|
| 2953 |
|
| 2954 |
|
| 2955 |
|
| 2956 |
|
| 2957 |
class TestOverflowMixin(SetupLuaRuntimeMixin): |
| 2958 |
def setUp(self): |
| 2959 |
super(TestOverflowMixin, self).setUp() |
| 2960 |
|
| 2961 |
self.maxinteger = self.lupa.LUA_MAXINTEGER |
| 2962 |
self.mininteger = self.lupa.LUA_MININTEGER |
| 2963 |
self.biginteger = (self.maxinteger + 1) << 1 |
| 2964 |
self.maxfloat = sys.float_info.max |
| 2965 |
self.bigfloat = int(self.maxfloat) * 2 |
| 2966 |
|
| 2967 |
assert self.biginteger <= self.maxfloat, "%d can't be cast to float" % self.biginteger |
| 2968 |
|
| 2969 |
self.lua_type = self.lua.eval('type') |
| 2970 |
self.lua_math_type = self.lua.eval('math.type') |
| 2971 |
|
| 2972 |
def tearDown(self): |
| 2973 |
self.lua_type = None |
| 2974 |
self.lua_math_type = None |
| 2975 |
super(TestOverflowMixin, self).tearDown() |
| 2976 |
|
| 2977 |
def test_no_overflow(self): |
| 2978 |
self.assertMathType(0, 'integer') |
| 2979 |
self.assertMathType(10, 'integer') |
| 2980 |
self.assertMathType(-10, 'integer') |
| 2981 |
self.assertMathType(self.maxinteger, 'integer') |
| 2982 |
self.assertMathType(self.mininteger, 'integer') |
| 2983 |
self.assertMathType(0.0, 'float') |
| 2984 |
self.assertMathType(-0.0, 'float') |
| 2985 |
self.assertMathType(10.0, 'float') |
| 2986 |
self.assertMathType(-10.0, 'float') |
| 2987 |
self.assertMathType(3.14, 'float') |
| 2988 |
self.assertMathType(-3.14, 'float') |
| 2989 |
self.assertMathType(self.maxfloat, 'float') |
| 2990 |
self.assertMathType(-self.maxfloat, 'float') |
| 2991 |
|
| 2992 |
def assertMathType(self, number, math_type): |
| 2993 |
self.assertEqual(self.lua_type(number), 'number') |
| 2994 |
if self.lua_math_type is not None: |
| 2995 |
self.assertEqual(self.lua_math_type(number), math_type) |
| 2996 |
|
| 2997 |
|
| 2998 |
class TestOverflowWithoutHandler(TestOverflowMixin, LupaTestCase): |
| 2999 |
lua_runtime_kwargs = dict(overflow_handler=None) |
| 3000 |
|
| 3001 |
def test_overflow(self): |
| 3002 |
self.assertRaises(OverflowError, self.assertMathType, self.biginteger, 'integer') |
| 3003 |
self.assertRaises(OverflowError, self.assertMathType, int(self.maxfloat), 'integer') |
| 3004 |
self.assertRaises(OverflowError, self.assertMathType, self.bigfloat, 'integer') |
| 3005 |
|
| 3006 |
|
| 3007 |
class TestOverflowWithFloatHandler(TestOverflowMixin, LupaTestCase): |
| 3008 |
lua_runtime_kwargs = dict(overflow_handler=float) |
| 3009 |
|
| 3010 |
def test_overflow(self): |
| 3011 |
self.assertMathType(self.biginteger, 'float') |
| 3012 |
self.assertMathType(int(self.maxfloat), 'float') |
| 3013 |
self.assertRaises(OverflowError, self.assertMathType, self.bigfloat, 'float') |
| 3014 |
|
| 3015 |
|
| 3016 |
class TestOverflowWithObjectHandler(TestOverflowMixin, LupaTestCase): |
| 3017 |
def test_overflow(self): |
| 3018 |
self.lua.execute('python.set_overflow_handler(function(o) return o end)') |
| 3019 |
self.assertEqual(self.lua.eval('type')(self.biginteger), 'userdata') |
| 3020 |
|
| 3021 |
|
| 3022 |
class TestFloatOverflowHandlerInLua(TestOverflowMixin, LupaTestCase): |
| 3023 |
def test_overflow(self): |
| 3024 |
self.lua.execute('python.set_overflow_handler(python.builtins.float)') |
| 3025 |
self.assertMathType(self.biginteger, 'float') |
| 3026 |
self.assertMathType(int(self.maxfloat), 'float') |
| 3027 |
self.assertRaises(OverflowError, self.assertMathType, self.bigfloat, 'float') |
| 3028 |
|
| 3029 |
|
| 3030 |
class TestBadOverflowHandlerInPython(LupaTestCase): |
| 3031 |
def test_error(self): |
| 3032 |
self.assertRaises(ValueError, self.lupa.LuaRuntime, overflow_handler=123) |
| 3033 |
|
| 3034 |
|
| 3035 |
class TestBadOverflowHandlerInLua(SetupLuaRuntimeMixin, LupaTestCase): |
| 3036 |
def _test_set_overflow_handler(self, overflow_handler_code): |
| 3037 |
self.assertRaises(self.lupa.LuaError, self.lua.execute, 'python.set_overflow_handler(%s)' % overflow_handler_code) |
| 3038 |
|
| 3039 |
def test_number(self): |
| 3040 |
self._test_set_overflow_handler('123') |
| 3041 |
|
| 3042 |
def test_table(self): |
| 3043 |
self._test_set_overflow_handler('{}') |
| 3044 |
|
| 3045 |
def test_boolean(self): |
| 3046 |
self._test_set_overflow_handler('true') |
| 3047 |
self._test_set_overflow_handler('false') |
| 3048 |
|
| 3049 |
def test_string(self): |
| 3050 |
self._test_set_overflow_handler('"abc"') |
| 3051 |
|
| 3052 |
def test_thread(self): |
| 3053 |
self._test_set_overflow_handler('coroutine.create(function() end)') |
| 3054 |
|
| 3055 |
|
| 3056 |
class TestOverflowHandlerOverwrite(TestOverflowMixin, LupaTestCase): |
| 3057 |
lua_runtime_kwargs = dict(overflow_handler=float) |
| 3058 |
|
| 3059 |
def test_overwrite_in_lua(self): |
| 3060 |
self.lua.execute('python.set_overflow_handler(nil)') |
| 3061 |
self.assertRaises(OverflowError, self.assertMathType, self.biginteger, 'integer') |
| 3062 |
self.assertRaises(OverflowError, self.assertMathType, int(self.maxfloat), 'integer') |
| 3063 |
self.assertRaises(OverflowError, self.assertMathType, self.bigfloat, 'integer') |
| 3064 |
self.lua.set_overflow_handler(float) |
| 3065 |
self.assertMathType(self.biginteger, 'float') |
| 3066 |
self.assertMathType(int(self.maxfloat), 'float') |
| 3067 |
self.assertRaises(OverflowError, self.assertMathType, self.bigfloat, 'float') |
| 3068 |
|
| 3069 |
def test_overwrite_in_python(self): |
| 3070 |
self.lua.set_overflow_handler(None) |
| 3071 |
self.assertRaises(OverflowError, self.assertMathType, self.biginteger, 'integer') |
| 3072 |
self.assertRaises(OverflowError, self.assertMathType, int(self.maxfloat), 'integer') |
| 3073 |
self.assertRaises(OverflowError, self.assertMathType, self.bigfloat, 'integer') |
| 3074 |
self.lua.execute('python.set_overflow_handler(function(o) return python.builtins.float(o) end)') |
| 3075 |
self.assertMathType(self.biginteger, 'float') |
| 3076 |
self.assertMathType(int(self.maxfloat), 'float') |
| 3077 |
self.assertRaises(OverflowError, self.assertMathType, self.bigfloat, 'float') |
| 3078 |
|
| 3079 |
|
| 3080 |
|
| 3081 |
|
| 3082 |
|
| 3083 |
class TestMissingReference(SetupLuaRuntimeMixin, LupaTestCase): |
| 3084 |
def setUp(self): |
| 3085 |
super(TestMissingReference, self).setUp() |
| 3086 |
self.testmissingref = self.lua.eval(''' |
| 3087 |
function(obj, f) |
| 3088 |
local t |
| 3089 |
if newproxy then |
| 3090 |
local p = newproxy(true) |
| 3091 |
t = getmetatable(p) |
| 3092 |
t.obj = obj |
| 3093 |
t.__gc = function(p_) t = getmetatable(p_) end |
| 3094 |
else |
| 3095 |
t = { obj = obj } |
| 3096 |
setmetatable(t, {__gc = function(t_) t = t_ end}) |
| 3097 |
end |
| 3098 |
obj = nil |
| 3099 |
t = nil |
| 3100 |
collectgarbage() |
| 3101 |
assert(t ~= nil) |
| 3102 |
assert(t.obj ~= nil) |
| 3103 |
local ok, ret = pcall(f, t.obj) |
| 3104 |
assert(not ok) |
| 3105 |
assert(tostring(ret):find("deleted python object")) |
| 3106 |
end |
| 3107 |
''') |
| 3108 |
|
| 3109 |
def tearDown(self): |
| 3110 |
self.testmissingref = None |
| 3111 |
super(TestMissingReference, self).tearDown() |
| 3112 |
|
| 3113 |
def test_fallbacks(self): |
| 3114 |
class X(): |
| 3115 |
def __call__(self, *args): |
| 3116 |
return None |
| 3117 |
|
| 3118 |
def assign(var): |
| 3119 |
var = None |
| 3120 |
|
| 3121 |
self.testmissingref({}, lambda o: str(o)) |
| 3122 |
self.testmissingref({}, lambda o: o[1]) |
| 3123 |
self.testmissingref({}, lambda o: self.lupa.as_itemgetter(o)[1]) |
| 3124 |
self.testmissingref({}, lambda o: self.lupa.as_attrgetter(o).items) |
| 3125 |
self.testmissingref({}, lambda o: assign(o[1])) |
| 3126 |
self.testmissingref({}, lambda o: assign(self.lupa.as_itemgetter(o)[1])) |
| 3127 |
self.testmissingref(X(), lambda o: assign(self.lupa.as_attrgetter(o).a)) |
| 3128 |
self.testmissingref(X(), lambda o: o()) |
| 3129 |
|
| 3130 |
def test_functions(self): |
| 3131 |
self.testmissingref({}, print) |
| 3132 |
self.testmissingref({}, iter) |
| 3133 |
self.testmissingref({}, enumerate) |
| 3134 |
self.testmissingref({}, self.lupa.as_itemgetter) |
| 3135 |
self.testmissingref({}, self.lupa.as_attrgetter) |
| 3136 |
|
| 3137 |
|
| 3138 |
|
| 3139 |
|
| 3140 |
|
| 3141 |
class TestLuaObjectString(SetupLuaRuntimeMixin, LupaTestCase): |
| 3142 |
def test_normal_string(self): |
| 3143 |
self.assertIn('Lua table', str(self.lua.eval('{}'))) |
| 3144 |
self.assertIn('Lua function', str(self.lua.eval('print'))) |
| 3145 |
self.assertIn('Lua thread', str(self.lua.execute('local t = coroutine.create(function() end); coroutine.resume(t); return t'))) |
| 3146 |
|
| 3147 |
def test_bad_tostring(self): |
| 3148 |
self.assertRaisesRegex(TypeError, '__tostring returned non-string object', |
| 3149 |
str, self.lua.eval('setmetatable({}, {__tostring = function() end})')) |
| 3150 |
|
| 3151 |
def test_tostring_err(self): |
| 3152 |
self.assertRaises(self.lupa.LuaError, str, self.lua.eval('setmetatable({}, {__tostring = function() error() end})')) |
| 3153 |
|
| 3154 |
|
| 3155 |
|
| 3156 |
|
| 3157 |
|
| 3158 |
class TestMaxMemory(SetupLuaRuntimeMixin, LupaTestCase): |
| 3159 |
lua_runtime_kwargs = {"max_memory": 10000} |
| 3160 |
|
| 3161 |
def setUp(self): |
| 3162 |
|
| 3163 |
if "luajit" in self.lupa.LuaRuntime().lua_implementation.lower(): |
| 3164 |
return self.skipTest("not supported in LuaJIT") |
| 3165 |
return super(TestMaxMemory, self).setUp() |
| 3166 |
|
| 3167 |
def test_getters(self): |
| 3168 |
self.assertEqual(self.lua.get_memory_used(), 0) |
| 3169 |
self.assertGreater(self.lua.get_memory_used(total=True), 0) |
| 3170 |
self.assertEqual(self.lua.get_max_memory(), 10000) |
| 3171 |
self.assertGreater(self.lua.get_max_memory(total=True), 10000) |
| 3172 |
self.lua.set_max_memory(1000000) |
| 3173 |
self.assertEqual(self.lua.get_memory_used(), 0) |
| 3174 |
self.assertGreater(self.lua.get_memory_used(total=True), 0) |
| 3175 |
self.assertEqual(self.lua.get_max_memory(), 1000000) |
| 3176 |
self.assertGreater(self.lua.get_max_memory(total=True), 1000000) |
| 3177 |
self.lua.set_max_memory(1000000, total=True) |
| 3178 |
self.assertEqual(self.lua.get_max_memory(total=True), 1000000) |
| 3179 |
self.assertLess(self.lua.get_max_memory(), 1000000) |
| 3180 |
|
| 3181 |
def test_not_enough_memory(self): |
| 3182 |
self.lua.eval("('a'):rep(50)") |
| 3183 |
self.assertRaises(self.lupa.LuaMemoryError, self.lua.eval, "('a'):rep(50000)") |
| 3184 |
|
| 3185 |
def test_decrease_memory(self): |
| 3186 |
self.lua.set_max_memory(1000000) |
| 3187 |
self.lua.execute("a = ('a'):rep(50000)") |
| 3188 |
self.lua.set_max_memory(10000) |
| 3189 |
self.assertEqual(self.lua.get_max_memory(), 10000) |
| 3190 |
self.assertGreaterEqual(self.lua.get_memory_used(), 50000) |
| 3191 |
self.assertRaises(self.lupa.LuaMemoryError, self.lua.eval, "('b'):rep(10)") |
| 3192 |
del self.lua.globals()["a"] |
| 3193 |
if self.lua.lua_version >= (5, 2): |
| 3194 |
|
| 3195 |
self.lua.eval("('b'):rep(10)") |
| 3196 |
|
| 3197 |
def test_compile_not_enough_memory(self): |
| 3198 |
self.lua.set_max_memory(10) |
| 3199 |
self.assertRaises(self.lupa.LuaMemoryError, self.lua.compile, "_G.a = function() return 'test abcdef' end") |
| 3200 |
|
| 3201 |
def test_unlimited_memory(self): |
| 3202 |
self.lua.set_max_memory(0) |
| 3203 |
self.lua.execute("a = ('a'):rep(50000)") |
| 3204 |
|
| 3205 |
|
| 3206 |
class TestMaxMemoryWithoutSettingIt(SetupLuaRuntimeMixin, LupaTestCase): |
| 3207 |
def test_property(self): |
| 3208 |
self.assertEqual(self.lua.get_max_memory(), None) |
| 3209 |
|
| 3210 |
def test_set_max(self): |
| 3211 |
self.assertRaises(RuntimeError, self.lua.set_max_memory, 10000) |
| 3212 |
|
| 3213 |
|
| 3214 |
|
| 3215 |
|
| 3216 |
|
| 3217 |
def load_tests(loader, standard_tests, pattern): |
| 3218 |
return lupa.tests.build_suite_for_modules(loader, globals()) |
| 3219 |
|
| 3220 |
|
| 3221 |
|
| 3222 |
if __name__ == '__main__': |
| 3223 |
def print_version(): |
| 3224 |
version = lupa.LuaRuntime().lua_implementation |
| 3225 |
print('Running Lupa %s tests against %s.' % (lupa.__version__, version)) |
| 3226 |
|
| 3227 |
print_version() |
| 3228 |
unittest.main() |