code stringlengths 1 1.05M | repo_name stringlengths 6 83 | path stringlengths 3 242 | language stringclasses 222
values | license stringclasses 20
values | size int64 1 1.05M |
|---|---|---|---|---|---|
# test builtin hash function
print({1 << 66:1}) # hash big int
print({-(1 << 66):2}) # hash negative big int
# __hash__ returning a large number should be truncated
class F:
def __hash__(self):
return 1 << 70 | 1
print(hash(F()) != 0)
# this had a particular error with internal integer arithmetic of hash function
print(hash(6699999999999999999999999999999999999999999999999999999999999999999999) != 0)
| YifuLiu/AliOS-Things | components/py_engine/tests/basics/builtin_hash_intbig.py | Python | apache-2.0 | 419 |
# test builtin help function
try:
help
except NameError:
print("SKIP")
raise SystemExit
help() # no args
help(help) # help for a function
help(int) # help for a class
help(1) # help for an instance
import micropython
help(micropython) # help for a module
help('modules') # list available modules
print('done') # so last bit of output is predictable
| YifuLiu/AliOS-Things | components/py_engine/tests/basics/builtin_help.py | Python | apache-2.0 | 364 |
# test builtin hex function
print(hex(1))
print(hex(-1))
print(hex(15))
print(hex(-15))
print(hex(12345))
print(hex(0x12345))
| YifuLiu/AliOS-Things | components/py_engine/tests/basics/builtin_hex.py | Python | apache-2.0 | 128 |
# test builtin hex function
print(hex(12345678901234567890))
print(hex(0x12345678901234567890))
| YifuLiu/AliOS-Things | components/py_engine/tests/basics/builtin_hex_intbig.py | Python | apache-2.0 | 97 |
print(id(1) == id(2))
print(id(None) == id(None))
# This can't be true per Python semantics, just CPython implementation detail
#print(id([]) == id([]))
l = [1, 2]
print(id(l) == id(l))
f = lambda:None
print(id(f) == id(f))
| YifuLiu/AliOS-Things | components/py_engine/tests/basics/builtin_id.py | Python | apache-2.0 | 226 |
# test builtin issubclass
class A:
pass
print(issubclass(A, A))
print(issubclass(A, (A,)))
try:
issubclass(A, 1)
except TypeError:
print('TypeError')
try:
issubclass('a', 1)
except TypeError:
print('TypeError')
| YifuLiu/AliOS-Things | components/py_engine/tests/basics/builtin_issubclass.py | Python | apache-2.0 | 235 |
# builtin len
print(len(()))
print(len((1,)))
print(len((1, 2)))
print(len([]))
x = [1, 2, 3]
print(len(x))
f = len
print(f({}))
print(f({1:2, 3:4}))
| YifuLiu/AliOS-Things | components/py_engine/tests/basics/builtin_len1.py | Python | apache-2.0 | 153 |
# test builtin locals()
x = 123
print(locals()['x'])
class A:
y = 1
def f(self):
pass
print('x' in locals())
print(locals()['y'])
print('f' in locals())
| YifuLiu/AliOS-Things | components/py_engine/tests/basics/builtin_locals.py | Python | apache-2.0 | 184 |
print(list(map(lambda x: x & 1, range(-3, 4))))
print(list(map(abs, range(-3, 4))))
print(list(map(tuple, [[i] for i in range(-3, 4)])))
print(list(map(pow, range(4), range(4))))
| YifuLiu/AliOS-Things | components/py_engine/tests/basics/builtin_map.py | Python | apache-2.0 | 179 |
# test builtin min and max functions
try:
min
max
except:
print("SKIP")
raise SystemExit
print(min(0,1))
print(min(1,0))
print(min(0,-1))
print(min(-1,0))
print(max(0,1))
print(max(1,0))
print(max(0,-1))
print(max(-1,0))
print(min([1,2,4,0,-1,2]))
print(max([1,2,4,0,-1,2]))
# test with key function
lst = [2, 1, 3, 4]
print(min(lst, key=lambda x:x))
print(min(lst, key=lambda x:-x))
print(min(1, 2, 3, 4, key=lambda x:-x))
print(min(4, 3, 2, 1, key=lambda x:-x))
print(max(lst, key=lambda x:x))
print(max(lst, key=lambda x:-x))
print(max(1, 2, 3, 4, key=lambda x:-x))
print(max(4, 3, 2, 1, key=lambda x:-x))
# need at least 1 item in the iterable
try:
min([])
except ValueError:
print("ValueError")
# 'default' tests
print(min([1, 2, 3, 4, 5], default=-1))
print(min([], default=-1))
print(max([1, 2, 3, 4, 5], default=-1))
print(max([], default=-1))
# make sure it works with lazy iterables
# can't use Python generators here, as they're not supported
# byy native codegenerator.
print(min(enumerate([]), default=-10))
| YifuLiu/AliOS-Things | components/py_engine/tests/basics/builtin_minmax.py | Python | apache-2.0 | 1,051 |
# test next(iter, default)
try:
next(iter([]), 42)
except TypeError: # 2-argument version not supported
print('SKIP')
raise SystemExit
print(next(iter([]), 42))
print(next(iter(range(0)), 42))
print(next((x for x in [0] if x == 1), 43))
def gen():
yield 1
yield 2
g = gen()
print(next(g, 42))
print(next(g, 43))
print(next(g, 44))
class Gen:
def __init__(self):
self.b = False
def __next__(self):
if self.b:
raise StopIteration
self.b = True
return self.b
g = Gen()
print(next(g, 44))
print(next(g, 45))
| YifuLiu/AliOS-Things | components/py_engine/tests/basics/builtin_next_arg2.py | Python | apache-2.0 | 584 |
# test builtin oct function
print(oct(1))
print(oct(-1))
print(oct(15))
print(oct(-15))
print(oct(12345))
print(oct(0o12345))
| YifuLiu/AliOS-Things | components/py_engine/tests/basics/builtin_oct.py | Python | apache-2.0 | 128 |
# test builtin oct function
print(oct(12345678901234567890))
print(oct(0o12345670123456701234))
| YifuLiu/AliOS-Things | components/py_engine/tests/basics/builtin_oct_intbig.py | Python | apache-2.0 | 97 |
# test builtin ord (whether or not we support unicode)
print(ord('a'))
try:
ord('')
except TypeError:
print("TypeError")
# bytes also work in ord
print(ord(b'a'))
print(ord(b'\x00'))
print(ord(b'\x01'))
print(ord(b'\x7f'))
print(ord(b'\x80'))
print(ord(b'\xff'))
try:
ord(b'')
except TypeError:
print("TypeError")
# argument must be a string
try:
ord(1)
except TypeError:
print('TypeError')
| YifuLiu/AliOS-Things | components/py_engine/tests/basics/builtin_ord.py | Python | apache-2.0 | 421 |
# test overriding builtins
import builtins
# override generic builtin
try:
builtins.abs = lambda x: x + 1
except AttributeError:
print("SKIP")
raise SystemExit
print(abs(1))
# __build_class__ is handled in a special way
orig_build_class = __build_class__
builtins.__build_class__ = lambda x, y: ('class', y)
class A:
pass
print(A)
builtins.__build_class__ = orig_build_class
# __import__ is handled in a special way
def custom_import(name, globals, locals, fromlist, level):
print('import', name, fromlist, level)
class M:
a = 1
b = 2
return M
builtins.__import__ = custom_import
__import__('A', None, None, None, 0)
import a
import a.b
from a import a
from a.b import a, b
from .a import a
from ..a import a, b
| YifuLiu/AliOS-Things | components/py_engine/tests/basics/builtin_override.py | Python | apache-2.0 | 761 |
# test builtin pow() with integral values
# 2 arg version
print(pow(0, 1))
print(pow(1, 0))
print(pow(-2, 3))
print(pow(3, 8))
| YifuLiu/AliOS-Things | components/py_engine/tests/basics/builtin_pow.py | Python | apache-2.0 | 128 |
# test builtin pow() with integral values
# 3 arg version
try:
print(pow(3, 4, 7))
except NotImplementedError:
print("SKIP")
raise SystemExit
# test some edge cases
print(pow(1, 1, 1))
print(pow(0, 1, 1))
print(pow(1, 0, 1))
print(pow(1, 0, 2))
# 3 arg pow is defined to only work on integers
try:
print(pow("x", 5, 6))
except TypeError:
print("TypeError expected")
try:
print(pow(4, "y", 6))
except TypeError:
print("TypeError expected")
try:
print(pow(4, 5, "z"))
except TypeError:
print("TypeError expected")
| YifuLiu/AliOS-Things | components/py_engine/tests/basics/builtin_pow3.py | Python | apache-2.0 | 553 |
# test builtin pow() with integral values
# 3 arg version
try:
print(pow(3, 4, 7))
except NotImplementedError:
print("SKIP")
raise SystemExit
print(pow(555557, 1000002, 1000003))
# Tests for 3 arg pow with large values
# This value happens to be prime
x = 0xd48a1e2a099b1395895527112937a391d02d4a208bce5d74b281cf35a57362502726f79a632f063a83c0eba66196712d963aa7279ab8a504110a668c0fc38a7983c51e6ee7a85cae87097686ccdc359ee4bbf2c583bce524e3f7836bded1c771a4efcb25c09460a862fc98e18f7303df46aaeb34da46b0c4d61d5cd78350f3edb60e6bc4befa712a849
y = 0x3accf60bb1a5365e4250d1588eb0fe6cd81ad495e9063f90880229f2a625e98c59387238670936afb2cafc5b79448e4414d6cd5e9901aa845aa122db58ddd7b9f2b17414600a18c47494ed1f3d49d005a5
print(hex(pow(2, 200, x))) # Should not overflow, just 1 << 200
print(hex(pow(2, x-1, x))) # Should be 1, since x is prime
print(hex(pow(y, x-1, x))) # Should be 1, since x is prime
print(hex(pow(y, y-1, x))) # Should be a 'big value'
print(hex(pow(y, y-1, y))) # Should be a 'big value'
| YifuLiu/AliOS-Things | components/py_engine/tests/basics/builtin_pow3_intbig.py | Python | apache-2.0 | 1,008 |
# test builtin print function
print()
print(None)
print('')
print(1)
print(1, 2)
print(sep='')
print(sep='x')
print(end='')
print(end='x\n')
print(1, sep='')
print(1, end='')
print(1, sep='', end='')
print(1, 2, sep='')
print(1, 2, end='')
print(1, 2, sep='', end='')
print([{1:2}])
| YifuLiu/AliOS-Things | components/py_engine/tests/basics/builtin_print.py | Python | apache-2.0 | 286 |
# test builtin property
try:
property
except:
print("SKIP")
raise SystemExit
# create a property object explicitly
property()
property(1, 2, 3)
# use its accessor methods
p = property()
p.getter(1)
p.setter(2)
p.deleter(3)
# basic use as a decorator
class A:
def __init__(self, x):
self._x = x
@property
def x(self):
print("x get")
return self._x
a = A(1)
print(a.x)
try:
a.x = 2
except AttributeError:
print("AttributeError")
# explicit use within a class
class B:
def __init__(self, x):
self._x = x
def xget(self):
print("x get")
return self._x
def xset(self, value):
print("x set")
self._x = value
def xdel(self):
print("x del")
x = property(xget, xset, xdel)
b = B(3)
print(b.x)
b.x = 4
print(b.x)
del b.x
# full use as a decorator
class C:
def __init__(self, x):
self._x = x
@property
def x(self):
print("x get")
return self._x
@x.setter
def x(self, value):
print("x set")
self._x = value
@x.deleter
def x(self):
print("x del")
c = C(5)
print(c.x)
c.x = 6
print(c.x)
del c.x
# a property that has no get, set or del
class D:
prop = property()
d = D()
try:
d.prop
except AttributeError:
print('AttributeError')
try:
d.prop = 1
except AttributeError:
print('AttributeError')
try:
del d.prop
except AttributeError:
print('AttributeError')
# properties take keyword arguments
class E:
p = property(lambda self: 42, doc="This is truth.")
# not tested for because the other keyword arguments are not accepted
# q = property(fget=lambda self: 21, doc="Half the truth.")
print(E().p)
# a property as an instance member should not be delegated to
class F:
def __init__(self):
self.prop_member = property()
print(type(F().prop_member))
| YifuLiu/AliOS-Things | components/py_engine/tests/basics/builtin_property.py | Python | apache-2.0 | 1,903 |
# test builtin property combined with inheritance
try:
property
except:
print("SKIP")
raise SystemExit
# test property in a base class works for derived classes
class A:
@property
def x(self):
print('A x')
return 123
class B(A):
pass
class C(B):
pass
class D:
pass
class E(C, D):
pass
print(A().x)
print(B().x)
print(C().x)
print(E().x)
# test that we can add a property to base class after creation
class F:
pass
F.foo = property(lambda self: print('foo get'))
class G(F):
pass
F().foo
G().foo
# should be able to add a property to already-subclassed class because it already has one
F.bar = property(lambda self: print('bar get'))
F().bar
G().bar
# test case where class (H here) is already subclassed before adding attributes
class H:
pass
class I(H):
pass
# should be able to add a normal member to already-subclassed class
H.val = 2
print(I().val)
# should be able to add a property to the derived class
I.baz = property(lambda self: print('baz get'))
I().baz
| YifuLiu/AliOS-Things | components/py_engine/tests/basics/builtin_property_inherit.py | Python | apache-2.0 | 1,039 |
# test builtin range type
# print
print(range(4))
# bool
print(bool(range(0)))
print(bool(range(10)))
# len
print(len(range(0)))
print(len(range(4)))
print(len(range(1, 4)))
print(len(range(1, 4, 2)))
print(len(range(1, 4, -1)))
print(len(range(4, 1, -1)))
print(len(range(4, 1, -2)))
# subscr
print(range(4)[0])
print(range(4)[1])
print(range(4)[-1])
# slice
print(range(4)[0:])
print(range(4)[1:])
print(range(4)[1:2])
print(range(4)[1:3])
print(range(4)[1::2])
print(range(4)[1:-2:2])
print(range(1, 4)[:])
print(range(1, 4)[0:])
print(range(1, 4)[1:])
print(range(1, 4)[:-1])
print(range(7, -2, -4)[:])
print(range(1, 100, 5)[5:15:3])
print(range(1, 100, 5)[15:5:-3])
print(range(100, 1, -5)[5:15:3])
print(range(100, 1, -5)[15:5:-3])
# for this case uPy gives a different stop value but the listed elements are still correct
print(list(range(7, -2, -4)[2:-2:]))
# zero step
try:
range(1, 2, 0)
except ValueError:
print("ValueError")
# bad unary op
try:
-range(1)
except TypeError:
print("TypeError")
# bad subscription (can't store)
try:
range(1)[0] = 1
except TypeError:
print("TypeError")
| YifuLiu/AliOS-Things | components/py_engine/tests/basics/builtin_range.py | Python | apache-2.0 | 1,129 |
# test attributes of builtin range type
try:
range(0).start
except AttributeError:
print("SKIP")
raise SystemExit
# attrs
print(range(1, 2, 3).start)
print(range(1, 2, 3).stop)
print(range(1, 2, 3).step)
# bad attr (can't store)
try:
range(4).start = 0
except AttributeError:
print('AttributeError')
| YifuLiu/AliOS-Things | components/py_engine/tests/basics/builtin_range_attrs.py | Python | apache-2.0 | 323 |
# test binary operations on range objects; (in)equality only
# this "feature test" actually tests the implementation but is the best we can do
if range(1) != range(1):
print("SKIP")
raise SystemExit
# basic (in)equality
print(range(1) == range(1))
print(range(1) != range(1))
print(range(1) != range(2))
# empty range
print(range(0) == range(0))
print(range(1, 0) == range(0))
print(range(1, 4, -1) == range(6, 3))
# 1 element range
print(range(1, 4, 10) == range(1, 4, 10))
print(range(1, 4, 10) == range(1, 4, 20))
print(range(1, 4, 10) == range(1, 8, 20))
# more than 1 element
print(range(0, 3, 2) == range(0, 3, 2))
print(range(0, 3, 2) == range(0, 4, 2))
print(range(0, 3, 2) == range(0, 5, 2))
# unsupported binary op
try:
range(1) + 10
except TypeError:
print('TypeError')
| YifuLiu/AliOS-Things | components/py_engine/tests/basics/builtin_range_binop.py | Python | apache-2.0 | 803 |
# test the builtin reverse() function
try:
reversed
except:
print("SKIP")
raise SystemExit
# list
print(list(reversed([])))
print(list(reversed([1])))
print(list(reversed([1, 2, 3])))
# tuple
print(list(reversed(())))
print(list(reversed((1, 2, 3))))
# string
for c in reversed('ab'):
print(c)
# bytes
for b in reversed(b'1234'):
print(b)
# range
for i in reversed(range(3)):
print(i)
# user object
class A:
def __init__(self):
pass
def __len__(self):
return 3
def __getitem__(self, pos):
return pos + 1
for a in reversed(A()):
print(a)
# user object with __reversed__
class B:
def __reversed__(self):
return [1, 2, 3]
print(reversed(B()))
| YifuLiu/AliOS-Things | components/py_engine/tests/basics/builtin_reversed.py | Python | apache-2.0 | 723 |
# test round() with integral values
tests = [
False, True,
0, 1, -1, 10
]
for t in tests:
print(round(t))
| YifuLiu/AliOS-Things | components/py_engine/tests/basics/builtin_round.py | Python | apache-2.0 | 119 |
# test round() with integer values and second arg
# rounding integers is an optional feature so test for it
try:
round(1, -1)
except NotImplementedError:
print('SKIP')
raise SystemExit
tests = [
(1, False), (1, True),
(124, -1), (125, -1), (126, -1),
(5, -1), (15, -1), (25, -1),
(12345, 0), (12345, -1), (12345, 1),
(-1234, 0), (-1234, -1), (-1234, 1),
]
for t in tests:
print(round(*t))
| YifuLiu/AliOS-Things | components/py_engine/tests/basics/builtin_round_int.py | Python | apache-2.0 | 427 |
# test round() with large integer values and second arg
# rounding integers is an optional feature so test for it
try:
round(1, -1)
except NotImplementedError:
print('SKIP')
raise SystemExit
i = 2**70
tests = [
(i, 0), (i, -1), (i, -10), (i, 1),
(-i, 0), (-i, -1), (-i, -10), (-i, 1),
]
for t in tests:
print(round(*t))
| YifuLiu/AliOS-Things | components/py_engine/tests/basics/builtin_round_intbig.py | Python | apache-2.0 | 347 |
class A:
var = 132
def __init__(self):
self.var2 = 34
a = A()
setattr(a, "var", 123)
setattr(a, "var2", 56)
print(a.var)
print(a.var2)
try:
setattr(a, b'var3', 1)
except TypeError:
print('TypeError')
# try setattr on a built-in function
try:
setattr(int, 'to_bytes', 1)
except (AttributeError, TypeError):
# uPy raises AttributeError, CPython raises TypeError
print('AttributeError/TypeError')
| YifuLiu/AliOS-Things | components/py_engine/tests/basics/builtin_setattr.py | Python | apache-2.0 | 436 |
# test builtin slice
# print slice
class A:
def __getitem__(self, idx):
print(idx)
return idx
s = A()[1:2:3]
# check type
print(type(s) is slice)
| YifuLiu/AliOS-Things | components/py_engine/tests/basics/builtin_slice.py | Python | apache-2.0 | 168 |
# test builtin sorted
try:
sorted
set
except:
print("SKIP")
raise SystemExit
print(sorted(set(range(100))))
print(sorted(set(range(100)), key=lambda x: x + 100*(x % 2)))
# need to use keyword argument
try:
sorted([], None)
except TypeError:
print("TypeError")
| YifuLiu/AliOS-Things | components/py_engine/tests/basics/builtin_sorted.py | Python | apache-2.0 | 286 |
# test builtin "sum"
tests = (
(),
[],
[0],
[1],
[0, 1, 2],
range(10),
)
for test in tests:
print(sum(test))
print(sum(test, -2))
| YifuLiu/AliOS-Things | components/py_engine/tests/basics/builtin_sum.py | Python | apache-2.0 | 164 |
# test builtin type
print(type(int))
try:
type()
except TypeError:
print('TypeError')
try:
type(1, 2)
except TypeError:
print('TypeError')
# second arg should be a tuple
try:
type('abc', None, None)
except TypeError:
print('TypeError')
# third arg should be a dict
try:
type('abc', (), None)
except TypeError:
print('TypeError')
# elements of second arg (the bases) should be types
try:
type('abc', (1,), {})
except TypeError:
print('TypeError')
| YifuLiu/AliOS-Things | components/py_engine/tests/basics/builtin_type.py | Python | apache-2.0 | 492 |
try:
zip
set
except NameError:
print("SKIP")
raise SystemExit
print(list(zip()))
print(list(zip([1], set([2, 3]))))
| YifuLiu/AliOS-Things | components/py_engine/tests/basics/builtin_zip.py | Python | apache-2.0 | 133 |
print(bytearray(4))
a = bytearray([1, 2, 200])
print(type(a))
print(a[0], a[2])
print(a[-1])
print(a)
a[2] = 255
print(a[-1])
a.append(10)
print(len(a))
s = 0
for i in a:
s += i
print(s)
print(a[1:])
print(a[:-1])
print(a[2:3])
print(str(bytearray(b"123"), "utf-8"))
# Comparisons
print(bytearray([1]) == bytearray([1]))
print(bytearray([1]) == bytearray([2]))
print(bytearray([1]) == b"1")
print(b"1" == bytearray([1]))
print(bytearray() == bytearray())
b1 = bytearray([1, 2, 3])
b2 = bytearray([1, 2, 3])
b3 = bytearray([1, 3])
print(b1 == b2)
print(b2 != b3)
print(b1 <= b2)
print(b1 <= b3)
print(b1 < b3)
print(b1 >= b2)
print(b3 >= b2)
print(b3 > b2)
print(b1 != b2)
print(b2 == b3)
print(b1 > b2)
print(b1 > b3)
print(b1 >= b3)
print(b1 < b2)
print(b3 < b2)
print(b3 <= b2)
# comparison with other type should return False
print(bytearray() == 1)
# TODO: other comparisons
# __contains__
b = bytearray(b"\0foo\0")
print(b"foo" in b)
print(b"foo\x01" in b)
print(b"" in b)
| YifuLiu/AliOS-Things | components/py_engine/tests/basics/bytearray1.py | Python | apache-2.0 | 990 |
# test bytearray + bytearray
b = bytearray(2)
b[0] = 1
b[1] = 2
print(b + bytearray(2))
# inplace add
b += bytearray(3)
print(b)
# extend
b.extend(bytearray(4))
print(b)
# this inplace add tests the code when the buffer doesn't need to be increased
b = bytearray()
b += b''
| YifuLiu/AliOS-Things | components/py_engine/tests/basics/bytearray_add.py | Python | apache-2.0 | 278 |
# test bytearray.append method
a = bytearray(4)
print(a)
# append should append a single byte
a.append(2)
print(a)
# a should not be modified if append fails
try:
a.append(None)
except TypeError:
print('TypeError')
print(a)
| YifuLiu/AliOS-Things | components/py_engine/tests/basics/bytearray_append.py | Python | apache-2.0 | 235 |
# test construction of bytearray from different objects
print(bytearray(b'123'))
print(bytearray('1234', 'utf-8'))
print(bytearray('12345', 'utf-8', 'strict'))
print(bytearray((1, 2)))
print(bytearray([1, 2]))
| YifuLiu/AliOS-Things | components/py_engine/tests/basics/bytearray_construct.py | Python | apache-2.0 | 211 |
# test construction of bytearray from different objects
try:
from uarray import array
except ImportError:
try:
from array import array
except ImportError:
print("SKIP")
raise SystemExit
# arrays
print(bytearray(array('b', [1, 2])))
print(bytearray(array('h', [0x101, 0x202])))
| YifuLiu/AliOS-Things | components/py_engine/tests/basics/bytearray_construct_array.py | Python | apache-2.0 | 314 |
# test construction of bytearray from different objects
try:
from uarray import array
except ImportError:
try:
from array import array
except ImportError:
print("SKIP")
raise SystemExit
# arrays
print(bytearray(array('h', [1, 2])))
print(bytearray(array('I', [1, 2])))
| YifuLiu/AliOS-Things | components/py_engine/tests/basics/bytearray_construct_endian.py | Python | apache-2.0 | 306 |
try:
print(bytearray(b'').decode())
print(bytearray(b'abc').decode())
except AttributeError:
print("SKIP")
raise SystemExit
| YifuLiu/AliOS-Things | components/py_engine/tests/basics/bytearray_decode.py | Python | apache-2.0 | 140 |
print(bytearray(2**65 - (2**65 - 1)))
| YifuLiu/AliOS-Things | components/py_engine/tests/basics/bytearray_intbig.py | Python | apache-2.0 | 38 |
try:
bytearray()[:] = bytearray()
except TypeError:
print("SKIP")
raise SystemExit
# test slices; only 2 argument version supported by MicroPython at the moment
x = bytearray(range(10))
# Assignment
l = bytearray(x)
l[1:3] = bytearray([10, 20])
print(l)
l = bytearray(x)
l[1:3] = bytearray([10])
print(l)
l = bytearray(x)
l[1:3] = bytearray()
print(l)
l = bytearray(x)
#del l[1:3]
print(l)
l = bytearray(x)
l[:3] = bytearray([10, 20])
print(l)
l = bytearray(x)
l[:3] = bytearray()
print(l)
l = bytearray(x)
#del l[:3]
print(l)
l = bytearray(x)
l[:-3] = bytearray([10, 20])
print(l)
l = bytearray(x)
l[:-3] = bytearray()
print(l)
l = bytearray(x)
#del l[:-3]
print(l)
# slice assignment that extends the array
b = bytearray(2)
b[2:] = bytearray(10)
print(b)
b = bytearray(10)
b[:-1] = bytearray(500)
print(len(b), b[0], b[-1])
# extension with self on RHS
b = bytearray(x)
b[4:] = b
print(b)
# Assignment of bytes to array slice
b = bytearray(2)
b[1:1] = b"12345"
print(b)
# Growth of bytearray via slice extension
b = bytearray(b'12345678')
b.append(57) # expand and add a bit of unused space at end of the bytearray
for i in range(400):
b[-1:] = b'ab' # grow slowly into the unused space
print(len(b), b)
| YifuLiu/AliOS-Things | components/py_engine/tests/basics/bytearray_slice_assign.py | Python | apache-2.0 | 1,231 |
# literals
print(b'123')
print(br'123')
print(rb'123')
print(b'\u1234')
# construction
print(bytes())
print(bytes(b'abc'))
# make sure empty bytes is converted correctly
print(str(bytes(), 'utf-8'))
a = b"123"
print(a)
print(str(a))
print(repr(a))
print(a[0], a[2])
print(a[-1])
print(str(a, "utf-8"))
print(str(a, "utf-8", "ignore"))
try:
str(a, "utf-8", "ignore", "toomuch")
except TypeError:
print("TypeError")
s = 0
for i in a:
s += i
print(s)
print(bytes("abc", "utf-8"))
print(bytes("abc", "utf-8", "replace"))
try:
bytes("abc")
except TypeError:
print("TypeError")
try:
bytes("abc", "utf-8", "replace", "toomuch")
except TypeError:
print("TypeError")
print(bytes(3))
print(bytes([3, 2, 1]))
print(bytes(range(5)))
# Make sure bytes are not mistreated as unicode
x = b"\xff\x8e\xfe}\xfd\x7f"
print(len(x))
print(x[0], x[1], x[2], x[3])
# Make sure init values are not mistreated as unicode chars
# For sequence of known len
print(bytes([128, 255]))
# For sequence of unknown len
print(bytes(iter([128, 255])))
# Shouldn't be able to make bytes with negative length
try:
bytes(-1)
except ValueError:
print('ValueError')
| YifuLiu/AliOS-Things | components/py_engine/tests/basics/bytes.py | Python | apache-2.0 | 1,172 |
# test bytes + other
print(b"123" + b"456")
print(b"123" + b"") # RHS is empty, can be optimised
print(b"" + b"123") # LHS is empty, can be optimised
| YifuLiu/AliOS-Things | components/py_engine/tests/basics/bytes_add.py | Python | apache-2.0 | 152 |
# test bytes + other
try:
import uarray as array
except ImportError:
try:
import array
except ImportError:
print("SKIP")
raise SystemExit
# should be byteorder-neutral
print(b"123" + array.array('h', [0x1515]))
print(b"\x01\x02" + array.array('b', [1, 2]))
| YifuLiu/AliOS-Things | components/py_engine/tests/basics/bytes_add_array.py | Python | apache-2.0 | 295 |
# test bytes + bytearray
print(b"123" + bytearray(2))
print(b"" + bytearray(1)) # LHS is empty but can't be optimised
| YifuLiu/AliOS-Things | components/py_engine/tests/basics/bytes_add_bytearray.py | Python | apache-2.0 | 120 |
# test bytes + other
try:
import uarray as array
except ImportError:
try:
import array
except ImportError:
print("SKIP")
raise SystemExit
print(b"123" + array.array('i', [1]))
| YifuLiu/AliOS-Things | components/py_engine/tests/basics/bytes_add_endian.py | Python | apache-2.0 | 213 |
print(b"" == b"")
print(b"" > b"")
print(b"" < b"")
print(b"" == b"1")
print(b"1" == b"")
print("==")
print(b"" > b"1")
print(b"1" > b"")
print(b"" < b"1")
print(b"1" < b"")
print(b"" >= b"1")
print(b"1" >= b"")
print(b"" <= b"1")
print(b"1" <= b"")
print(b"1" == b"1")
print(b"1" != b"1")
print(b"1" == b"2")
print(b"1" == b"10")
print(b"1" > b"1")
print(b"1" > b"2")
print(b"2" > b"1")
print(b"10" > b"1")
print(b"1/" > b"1")
print(b"1" > b"10")
print(b"1" > b"1/")
print(b"1" < b"1")
print(b"2" < b"1")
print(b"1" < b"2")
print(b"1" < b"10")
print(b"1" < b"1/")
print(b"10" < b"1")
print(b"1/" < b"1")
print(b"1" >= b"1")
print(b"1" >= b"2")
print(b"2" >= b"1")
print(b"10" >= b"1")
print(b"1/" >= b"1")
print(b"1" >= b"10")
print(b"1" >= b"1/")
print(b"1" <= b"1")
print(b"2" <= b"1")
print(b"1" <= b"2")
print(b"1" <= b"10")
print(b"1" <= b"1/")
print(b"10" <= b"1")
print(b"1/" <= b"1")
print(b'o' == b'\n')
| YifuLiu/AliOS-Things | components/py_engine/tests/basics/bytes_compare.py | Python | apache-2.0 | 920 |
print(b"1" == 1)
| YifuLiu/AliOS-Things | components/py_engine/tests/basics/bytes_compare2.py | Python | apache-2.0 | 17 |
# Based on MicroPython config option, comparison of str and bytes
# or vice versa may issue a runtime warning. On CPython, if run as
# "python3 -b", only comparison of str to bytes issues a warning,
# not the other way around (while exactly comparison of bytes to
# str would be the most common error, as in sock.recv(3) == "GET").
# Update: the issue above with CPython apparently happens in REPL,
# when run as a script, both lines issue a warning.
print("123" == b"123")
print(b"123" == "123")
| YifuLiu/AliOS-Things | components/py_engine/tests/basics/bytes_compare3.py | Python | apache-2.0 | 497 |
try:
import uarray as array
except ImportError:
try:
import array
except ImportError:
print("SKIP")
raise SystemExit
print(array.array('b', [1, 2]) in b'\x01\x02\x03')
# CPython gives False here
#print(b"\x01\x02\x03" == array.array("B", [1, 2, 3]))
| YifuLiu/AliOS-Things | components/py_engine/tests/basics/bytes_compare_array.py | Python | apache-2.0 | 287 |
print(b"123" == bytearray(b"123"))
print(b'123' < bytearray(b"124"))
print(b'123' > bytearray(b"122"))
print(bytearray(b"23") in b"1234")
| YifuLiu/AliOS-Things | components/py_engine/tests/basics/bytes_compare_bytearray.py | Python | apache-2.0 | 138 |
# test construction of bytes from different objects
# tuple, list
print(bytes((1, 2)))
print(bytes([1, 2]))
# constructor value out of range
try:
bytes([-1])
except ValueError:
print('ValueError')
# constructor value out of range
try:
bytes([256])
except ValueError:
print('ValueError')
# error in construction
try:
a = bytes([1, 2, 3], 1)
except TypeError:
print('TypeError')
| YifuLiu/AliOS-Things | components/py_engine/tests/basics/bytes_construct.py | Python | apache-2.0 | 405 |
# test construction of bytes from different objects
try:
from uarray import array
except ImportError:
try:
from array import array
except ImportError:
print("SKIP")
raise SystemExit
# arrays
print(bytes(array('b', [1, 2])))
print(bytes(array('h', [0x101, 0x202])))
| YifuLiu/AliOS-Things | components/py_engine/tests/basics/bytes_construct_array.py | Python | apache-2.0 | 302 |
# test construction of bytes from bytearray
print(bytes(bytearray(4)))
| YifuLiu/AliOS-Things | components/py_engine/tests/basics/bytes_construct_bytearray.py | Python | apache-2.0 | 72 |
# test construction of bytes from different objects
try:
from uarray import array
except ImportError:
try:
from array import array
except ImportError:
print("SKIP")
raise SystemExit
# arrays
print(bytes(array('h', [1, 2])))
print(bytes(array('I', [1, 2])))
| YifuLiu/AliOS-Things | components/py_engine/tests/basics/bytes_construct_endian.py | Python | apache-2.0 | 295 |
# test construction of bytes from different objects
# long ints
print(ord(bytes([14953042807679334000 & 0xff])))
| YifuLiu/AliOS-Things | components/py_engine/tests/basics/bytes_construct_intbig.py | Python | apache-2.0 | 114 |
try:
bytes.count
except AttributeError:
print("SKIP")
raise SystemExit
print(b"".count(b""))
print(b"".count(b"a"))
print(b"a".count(b""))
print(b"a".count(b"a"))
print(b"a".count(b"b"))
print(b"b".count(b"a"))
print(b"aaa".count(b""))
print(b"aaa".count(b"a"))
print(b"aaa".count(b"aa"))
print(b"aaa".count(b"aaa"))
print(b"aaa".count(b"aaaa"))
print(b"aaaa".count(b""))
print(b"aaaa".count(b"a"))
print(b"aaaa".count(b"aa"))
print(b"aaaa".count(b"aaa"))
print(b"aaaa".count(b"aaaa"))
print(b"aaaa".count(b"aaaaa"))
print(b"aaa".count(b"", 1))
print(b"aaa".count(b"", 2))
print(b"aaa".count(b"", 3))
print(b"aaa".count(b"", 1, 2))
print(b"asdfasdfaaa".count(b"asdf", -100))
print(b"asdfasdfaaa".count(b"asdf", -8))
print(b"asdf".count(b's', True))
print(b"asdf".count(b'a', True))
print(b"asdf".count(b'a', False))
print(b"asdf".count(b'a', 1 == 2))
print(b"hello world".count(b'l'))
print(b"hello world".count(b'l', 5))
print(b"hello world".count(b'l', 3))
print(b"hello world".count(b'z', 3, 6))
print(b"aaaa".count(b'a'))
print(b"aaaa".count(b'a', 0, 3))
print(b"aaaa".count(b'a', 0, 4))
print(b"aaaa".count(b'a', 0, 5))
print(b"aaaa".count(b'a', 1, 5))
print(b"aaaa".count(b'a', -1, 5))
print(b"abbabba".count(b"abba"))
def t():
return True
print(b"0000".count(b'0', t()))
| YifuLiu/AliOS-Things | components/py_engine/tests/basics/bytes_count.py | Python | apache-2.0 | 1,302 |
print(b"hello world".find(b"ll"))
print(b"hello world".find(b"ll", None))
print(b"hello world".find(b"ll", 1))
print(b"hello world".find(b"ll", 1, None))
print(b"hello world".find(b"ll", None, None))
print(b"hello world".find(b"ll", 1, -1))
print(b"hello world".find(b"ll", 1, 1))
print(b"hello world".find(b"ll", 1, 2))
print(b"hello world".find(b"ll", 1, 3))
print(b"hello world".find(b"ll", 1, 4))
print(b"hello world".find(b"ll", 1, 5))
print(b"hello world".find(b"ll", -100))
print(b"0000".find(b'0'))
print(b"0000".find(b'0', 0))
print(b"0000".find(b'0', 1))
print(b"0000".find(b'0', 2))
print(b"0000".find(b'0', 3))
print(b"0000".find(b'0', 4))
print(b"0000".find(b'0', 5))
print(b"0000".find(b'-1', 3))
print(b"0000".find(b'1', 3))
print(b"0000".find(b'1', 4))
print(b"0000".find(b'1', 5))
# Non-ascii values (make sure not treated as unicode-like)
print(b"\x80abc".find(b"a", 1))
| YifuLiu/AliOS-Things | components/py_engine/tests/basics/bytes_find.py | Python | apache-2.0 | 890 |
# This test requires CPython3.5
try:
b'' % ()
except TypeError:
print("SKIP")
raise SystemExit
print(b"%%" % ())
print(b"=%d=" % 1)
print(b"=%d=%d=" % (1, 2))
print(b"=%s=" % b"str")
print(b"=%r=" % b"str")
| YifuLiu/AliOS-Things | components/py_engine/tests/basics/bytes_format_modulo.py | Python | apache-2.0 | 222 |
# construct a bytes object from a generator
def gen():
for i in range(4):
yield i
print(bytes(gen()))
| YifuLiu/AliOS-Things | components/py_engine/tests/basics/bytes_gen.py | Python | apache-2.0 | 114 |
b1 = b"long bytes long bytes long bytes long bytes long bytes long bytes long bytes long bytes long bytes long bytes long bytes long bytes long bytes long bytes long bytes long bytes long bytes long bytes long bytes long bytes long bytes long bytes long bytes long bytes long bytes long bytes long bytes long bytes long bytes long bytes long bytes long bytes long bytes long bytes long bytes long bytes long bytes long bytes long bytes long bytes long bytes"
b2 = b"concatenated bytes" b"concatenated bytes" b"concatenated bytes" b"concatenated bytes" b"concatenated bytes" b"concatenated bytes" b"concatenated bytes" b"concatenated bytes" b"concatenated bytes" b"concatenated bytes" b"concatenated bytes" b"concatenated bytes" b"concatenated bytes" b"concatenated bytes" b"concatenated bytes" b"concatenated bytes"
| YifuLiu/AliOS-Things | components/py_engine/tests/basics/bytes_large.py | Python | apache-2.0 | 816 |
# basic multiplication
print(b'0' * 5)
# check negative, 0, positive; lhs and rhs multiplication
for i in (-4, -2, 0, 2, 4):
print(i * b'12')
print(b'12' * i)
# check that we don't modify existing object
a = b'123'
c = a * 3
print(a, c)
| YifuLiu/AliOS-Things | components/py_engine/tests/basics/bytes_mult.py | Python | apache-2.0 | 247 |
try:
str.partition
except AttributeError:
print("SKIP")
raise SystemExit
print(b"asdf".partition(b'g'))
print(b"asdf".partition(b'a'))
print(b"asdf".partition(b's'))
print(b"asdf".partition(b'f'))
print(b"asdf".partition(b'd'))
print(b"asdf".partition(b'asd'))
print(b"asdf".partition(b'sdf'))
print(b"asdf".partition(b'as'))
print(b"asdf".partition(b'df'))
print(b"asdf".partition(b'asdf'))
print(b"asdf".partition(b'asdfa'))
print(b"asdf".partition(b'fasdf'))
print(b"asdf".partition(b'fasdfa'))
print(b"abba".partition(b'a'))
print(b"abba".partition(b'b'))
try:
print(b"asdf".partition(1))
except TypeError:
print("Raised TypeError")
else:
print("Did not raise TypeError")
try:
print(b"asdf".partition(b''))
except ValueError:
print("Raised ValueError")
else:
print("Did not raise ValueError")
| YifuLiu/AliOS-Things | components/py_engine/tests/basics/bytes_partition.py | Python | apache-2.0 | 836 |
print(b"".replace(b"a", b"b"))
print(b"aaa".replace(b"a", b"b", 0))
print(b"aaa".replace(b"a", b"b", -5))
print(b"asdfasdf".replace(b"a", b"b"))
print(b"aabbaabbaabbaa".replace(b"aa", b"cc", 3))
print(b"a".replace(b"aa", b"bb"))
print(b"testingtesting".replace(b"ing", b""))
print(b"testINGtesting".replace(b"ing", b"ING!"))
print(b"".replace(b"", b"1"))
print(b"A".replace(b"", b"1"))
print(b"AB".replace(b"", b"1"))
print(b"AB".replace(b"", b"12"))
| YifuLiu/AliOS-Things | components/py_engine/tests/basics/bytes_replace.py | Python | apache-2.0 | 452 |
# default separator (whitespace)
print(b"a b".split())
print(b" a b ".split(None))
print(b" a b ".split(None, 1))
print(b" a b ".split(None, 2))
print(b" a b c ".split(None, 1))
print(b" a b c ".split(None, 0))
print(b" a b c ".split(None, -1))
# empty separator should fail
try:
b"abc".split(b'')
except ValueError:
print("ValueError")
# non-empty separator
print(b"abc".split(b"a"))
print(b"abc".split(b"b"))
print(b"abc".split(b"c"))
print(b"abc".split(b"z"))
print(b"abc".split(b"ab"))
print(b"abc".split(b"bc"))
print(b"abc".split(b"abc"))
print(b"abc".split(b"abcd"))
print(b"abcabc".split(b"bc"))
print(b"abcabc".split(b"bc", 0))
print(b"abcabc".split(b"bc", 1))
print(b"abcabc".split(b"bc", 2))
| YifuLiu/AliOS-Things | components/py_engine/tests/basics/bytes_split.py | Python | apache-2.0 | 752 |
print(b"".strip())
print(b" \t\n\r\v\f".strip())
print(b" T E S T".strip())
print(b"abcabc".strip(b"ce"))
print(b"aaa".strip(b"b"))
print(b"abc efg ".strip(b"g a"))
print(b' spacious '.lstrip())
print(b'www.example.com'.lstrip(b'cmowz.'))
print(b' spacious '.rstrip())
print(b'mississippi'.rstrip(b'ipz'))
# Test that stripping unstrippable string returns original object
s = b"abc"
print(id(s.strip()) == id(s))
| YifuLiu/AliOS-Things | components/py_engine/tests/basics/bytes_strip.py | Python | apache-2.0 | 425 |
# test [...] of bytes
print(b'123'[0])
print(b'123'[1])
print(b'123'[-1])
try:
b'123'[1] = 4
except TypeError:
print('TypeError')
try:
del b'123'[1]
except TypeError:
print('TypeError')
| YifuLiu/AliOS-Things | components/py_engine/tests/basics/bytes_subscr.py | Python | apache-2.0 | 205 |
# basic class
def go():
class C:
def f():
print(1)
def g(self):
print(2)
def set(self, value):
self.value = value
def print(self):
print(self.value)
C.f()
C()
C().g()
o = C()
o.set(3)
o.print()
C.set(o, 4)
C.print(o)
go()
| YifuLiu/AliOS-Things | components/py_engine/tests/basics/class1.py | Python | apache-2.0 | 346 |
# class with __init__
class C1:
def __init__(self):
self.x = 1
c1 = C1()
print(type(c1) == C1)
print(c1.x)
class C2:
def __init__(self, x):
self.x = x
c2 = C2(4)
print(type(c2) == C2)
print(c2.x)
# __init__ should return None
class C3:
def __init__(self):
return 10
try:
C3()
except TypeError:
print('TypeError')
| YifuLiu/AliOS-Things | components/py_engine/tests/basics/class2.py | Python | apache-2.0 | 362 |
# inheritance
class A:
def a():
print('A.a() called')
class B(A):
pass
print(type(A))
print(type(B))
print(issubclass(A, A))
print(issubclass(A, B))
print(issubclass(B, A))
print(issubclass(B, B))
print(isinstance(A(), A))
print(isinstance(A(), B))
print(isinstance(B(), A))
print(isinstance(B(), B))
A.a()
B.a()
| YifuLiu/AliOS-Things | components/py_engine/tests/basics/class3.py | Python | apache-2.0 | 335 |
# test for type.__bases__ implementation
if not hasattr(object, '__bases__'):
print("SKIP")
raise SystemExit
class A:
pass
class B(object):
pass
class C(B):
pass
class D(C, A):
pass
# Check the attribute exists
print(hasattr(A, '__bases__'))
print(hasattr(B, '__bases__'))
print(hasattr(C, '__bases__'))
print(hasattr(D, '__bases__'))
# Check it is always a tuple
print(type(A.__bases__) == tuple)
print(type(B.__bases__) == tuple)
print(type(C.__bases__) == tuple)
print(type(D.__bases__) == tuple)
# Check size
print(len(A.__bases__) == 1)
print(len(B.__bases__) == 1)
print(len(C.__bases__) == 1)
print(len(D.__bases__) == 2)
# Check values
print(A.__bases__[0] == object)
print(B.__bases__[0] == object)
print(C.__bases__[0] == B)
print(D.__bases__[0] == C)
print(D.__bases__[1] == A)
# Object has an empty tuple
print(object.__bases__ == tuple())
| YifuLiu/AliOS-Things | components/py_engine/tests/basics/class_bases.py | Python | apache-2.0 | 886 |
# test for correct binding of self when accessing attr of an instance
class A:
def __init__(self, arg):
self.val = arg
def __str__(self):
return 'A.__str__ ' + str(self.val)
def __call__(self, arg):
return 'A.__call__', arg
def foo(self, arg):
return 'A.foo', self.val, arg
def make_closure(x_in):
x = x_in
def closure(y):
return x, y is c
return closure
class C:
# these act like methods and bind self
def f1(self, arg):
return 'C.f1', self is c, arg
f2 = lambda self, arg: ('C.f2', self is c, arg)
f3 = make_closure('f3') # closure
def f4(self, arg): # generator
yield self is c, arg
# these act like simple variables and don't bind self
f5 = int # builtin type
f6 = abs # builtin function
f7 = A # user type
f8 = A(8) # user instance which is callable
f9 = A(9).foo # user bound method
c = C()
print(c.f1(1))
print(c.f2(2))
print(c.f3())
print(next(c.f4(4)))
print(c.f5(5))
print(c.f6(-6))
print(c.f7(7))
print(c.f8(8))
print(c.f9(9))
# test calling the functions accessed via the class itself
print(C.f5(10))
print(C.f6(-11))
print(C.f7(12))
print(C.f8(13))
print(C.f9(14))
# not working in uPy
#class C(list):
# # this acts like a method and binds self
# f1 = list.extend
#c = C()
#c.f1([3, 1, 2])
#print(c)
| YifuLiu/AliOS-Things | components/py_engine/tests/basics/class_bind_self.py | Python | apache-2.0 | 1,356 |
class foo(object):
def __init__(self, value):
self.x = value
def __eq__(self, other):
print('eq')
return self.x == other.x
def __lt__(self, other):
print('lt')
return self.x < other.x
def __gt__(self, other):
print('gt')
return self.x > other.x
def __le__(self, other):
print('le')
return self.x <= other.x
def __ge__(self, other):
print('ge')
return self.x >= other.x
for i in range(3):
for j in range(3):
print(foo(i) == foo(j))
print(foo(i) < foo(j))
print(foo(i) > foo(j))
print(foo(i) <= foo(j))
print(foo(i) >= foo(j))
| YifuLiu/AliOS-Things | components/py_engine/tests/basics/class_binop.py | Python | apache-2.0 | 687 |
class C1:
def __call__(self, val):
print('call', val)
return 'item'
class C2:
def __getattr__(self, k):
pass
c1 = C1()
print(c1(1))
c2 = C2()
try:
print(c2(1))
except TypeError:
print("TypeError")
| YifuLiu/AliOS-Things | components/py_engine/tests/basics/class_call.py | Python | apache-2.0 | 241 |
# A contains everything
class A:
def __contains__(self, key):
return True
a = A()
print(True in a)
print(1 in a)
print(() in a)
# B contains given things
class B:
def __init__(self, items):
self.items = items
def __contains__(self, key):
return key in self.items
b = B([])
print(1 in b)
b = B([1, 2])
print(1 in b)
print(2 in b)
print(3 in b)
| YifuLiu/AliOS-Things | components/py_engine/tests/basics/class_contains.py | Python | apache-2.0 | 382 |
# test __delattr__ and __setattr__
# feature test for __setattr__/__delattr__
try:
class Test():
def __delattr__(self, attr): pass
del Test().noexist
except AttributeError:
print('SKIP')
raise SystemExit
# this class just prints the calls to see if they were executed
class A():
def __getattr__(self, attr):
print('get', attr)
return 1
def __setattr__(self, attr, val):
print('set', attr, val)
def __delattr__(self, attr):
print('del', attr)
a = A()
# check basic behaviour
print(getattr(a, 'foo'))
setattr(a, 'bar', 2)
delattr(a, 'baz')
# check meta behaviour
getattr(a, '__getattr__') # should not call A.__getattr__
getattr(a, '__setattr__') # should not call A.__getattr__
getattr(a, '__delattr__') # should not call A.__getattr__
setattr(a, '__setattr__', 1) # should call A.__setattr__
delattr(a, '__delattr__') # should call A.__delattr__
# this class acts like a dictionary
class B:
def __init__(self, d):
# store the dict in the class, not instance, so
# we don't get infinite recursion in __getattr_
B.d = d
def __getattr__(self, attr):
if attr in B.d:
return B.d[attr]
else:
raise AttributeError(attr)
def __setattr__(self, attr, value):
B.d[attr] = value
def __delattr__(self, attr):
del B.d[attr]
a = B({"a":1, "b":2})
print(a.a, a.b)
a.a = 3
print(a.a, a.b)
del a.a
try:
print(a.a)
except AttributeError:
print("AttributeError")
# test object.__setattr__
class C:
def __init__(self):
pass
def __setattr__(self, attr, value):
print(attr, "=", value)
def __delattr__(self, attr):
print("del", attr)
c = C()
c.a = 5
try:
print(c.a)
except AttributeError:
print("AttributeError")
object.__setattr__(c, "a", 5)
super(C, c).__setattr__("b", 6)
print(c.a)
print(c.b)
try:
# attribute name must be string
object.__setattr__(c, 5, 5)
except TypeError:
print("TypeError")
# test object.__delattr__
del c.a
print(c.a)
object.__delattr__(c, "a")
try:
print(c.a)
except AttributeError:
print("AttributeError")
super(C, c).__delattr__("b")
try:
print(c.b)
except AttributeError:
print("AttributeError")
try:
object.__delattr__(c, "c")
except AttributeError:
print("AttributeError")
| YifuLiu/AliOS-Things | components/py_engine/tests/basics/class_delattr_setattr.py | Python | apache-2.0 | 2,354 |
class Descriptor:
def __get__(self, obj, cls):
print('get')
print(type(obj) is Main)
print(cls is Main)
return 'result'
def __set__(self, obj, val):
print('set')
print(type(obj) is Main)
print(val)
def __delete__(self, obj):
print('delete')
print(type(obj) is Main)
class Main:
Forward = Descriptor()
m = Main()
try:
m.__class__
except AttributeError:
print("SKIP")
raise SystemExit
r = m.Forward
if 'Descriptor' in repr(r.__class__):
print('SKIP')
raise SystemExit
print(r)
m.Forward = 'a'
del m.Forward
| YifuLiu/AliOS-Things | components/py_engine/tests/basics/class_descriptor.py | Python | apache-2.0 | 619 |
# test __dict__ attribute of a class
if not hasattr(int, "__dict__"):
print("SKIP")
raise SystemExit
# dict of a built-in type
print("from_bytes" in int.__dict__)
# dict of a user class
class Foo:
a = 1
b = "bar"
d = Foo.__dict__
print(d["a"], d["b"])
# dict of a class that has no locals_dict (return empty dict).
d = type(type('')).__dict__
print(d is not None)
| YifuLiu/AliOS-Things | components/py_engine/tests/basics/class_dict.py | Python | apache-2.0 | 389 |
class A():
pass
| YifuLiu/AliOS-Things | components/py_engine/tests/basics/class_emptybases.py | Python | apache-2.0 | 20 |
# test that __getattr__ and instance members don't override builtins
class C:
def __init__(self):
self.__add__ = lambda: print('member __add__')
def __add__(self, x):
print('__add__')
def __getattr__(self, attr):
print('__getattr__', attr)
return None
c = C()
c.add # should call __getattr__
c.__add__() # should load __add__ instance directly
c + 1 # should call __add__ method directly
| YifuLiu/AliOS-Things | components/py_engine/tests/basics/class_getattr.py | Python | apache-2.0 | 433 |
class A:
def __init__(self, x):
print('A init', x)
self.x = x
def f(self):
print(self.x, self.y)
class B(A):
def __init__(self, x, y):
A.__init__(self, x)
print('B init', x, y)
self.y = y
def g(self):
print(self.x, self.y)
A(1)
b = B(1, 2)
b.f()
b.g()
| YifuLiu/AliOS-Things | components/py_engine/tests/basics/class_inherit1.py | Python | apache-2.0 | 328 |
# test multiple inheritance of user classes
class A:
def __init__(self, x):
print('A init', x)
self.x = x
def f(self):
print(self.x)
def f2(self):
print(self.x)
class B:
def __init__(self, x):
print('B init', x)
self.x = x
def f(self):
print(self.x)
def f3(self):
print(self.x)
class Sub(A, B):
def __init__(self):
A.__init__(self, 1)
B.__init__(self, 2)
print('Sub init')
def g(self):
print(self.x)
print(issubclass(Sub, A))
print(issubclass(Sub, B))
o = Sub()
print(o.x)
o.f()
o.f2()
o.f3()
| YifuLiu/AliOS-Things | components/py_engine/tests/basics/class_inherit_mul.py | Python | apache-2.0 | 632 |
# Case 1: Immutable object (e.g. number-like)
# __iadd__ should not be defined, will be emulated using __add__
class A:
def __init__(self, v):
self.v = v
def __add__(self, o):
return A(self.v + o.v)
def __repr__(self):
return "A({})".format(self.v)
a = A(5)
b = a
a += A(3)
print(a)
# Should be original a's value, i.e. A(5)
print(b)
# Case 2: Mutable object (e.g. list-like)
# __iadd__ should be defined
class L:
def __init__(self, v):
self.v = v
def __add__(self, o):
# Should not be caled in this test
print("L.__add__")
return L(self.v + o.v)
def __iadd__(self, o):
self.v += o.v
return self
def __repr__(self):
return "L({})".format(self.v)
c = L([1, 2])
d = c
c += L([3, 4])
print(c)
# Should be updated c's value, i.e. L([1, 2, 3, 4])
print(d)
| YifuLiu/AliOS-Things | components/py_engine/tests/basics/class_inplace_op.py | Python | apache-2.0 | 871 |
# Test inplace special methods enabled by MICROPY_PY_ALL_INPLACE_SPECIAL_METHODS
class A:
def __imul__(self, other):
print("__imul__")
return self
def __imatmul__(self, other):
print("__imatmul__")
return self
def __ifloordiv__(self, other):
print("__ifloordiv__")
return self
def __itruediv__(self, other):
print("__itruediv__")
return self
def __imod__(self, other):
print("__imod__")
return self
def __ipow__(self, other):
print("__ipow__")
return self
def __ior__(self, other):
print("__ior__")
return self
def __ixor__(self, other):
print("__ixor__")
return self
def __iand__(self, other):
print("__iand__")
return self
def __ilshift__(self, other):
print("__ilshift__")
return self
def __irshift__(self, other):
print("__irshift__")
return self
a = A()
try:
a *= None
except TypeError:
print("SKIP")
raise SystemExit
a @= None
a //= None
a /= None
a %= None
a **= None
a |= None
a ^= None
a &= None
a <<= None
a >>= None
# Normal operator should not fallback to inplace operator
try:
a * None
except TypeError:
print("TypeError")
| YifuLiu/AliOS-Things | components/py_engine/tests/basics/class_inplace_op2.py | Python | apache-2.0 | 1,293 |
# test that we can override a class method with an instance method
class A:
def foo(self):
return 1
a = A()
print(a.foo())
a.foo = lambda:2
print(a.foo())
| YifuLiu/AliOS-Things | components/py_engine/tests/basics/class_instance_override.py | Python | apache-2.0 | 169 |
# test class with __getitem__, __setitem__, __delitem__ methods
class C:
def __getitem__(self, item):
print('get', item)
return 'item'
def __setitem__(self, item, value):
print('set', item, value)
def __delitem__(self, item):
print('del', item)
c = C()
print(c[1])
c[1] = 2
del c[3]
# index not supported
class A:
pass
a = A()
try:
a[1]
except TypeError:
print('TypeError')
| YifuLiu/AliOS-Things | components/py_engine/tests/basics/class_item.py | Python | apache-2.0 | 435 |
# converting user instance to buffer
class C:
pass
c = C()
try:
d = bytes(c)
except TypeError:
print('TypeError')
| YifuLiu/AliOS-Things | components/py_engine/tests/basics/class_misc.py | Python | apache-2.0 | 127 |
try:
# If we don't expose object.__new__ (small ports), there's
# nothing to test.
object.__new__
except AttributeError:
print("SKIP")
raise SystemExit
class A:
def __new__(cls):
print("A.__new__")
return super(cls, A).__new__(cls)
def __init__(self):
print("A.__init__")
def meth(self):
print('A.meth')
#print(A.__new__)
#print(A.__init__)
a = A()
a.meth()
a = A.__new__(A)
a.meth()
#print(a.meth)
#print(a.__init__)
#print(a.__new__)
# __new__ should automatically be a staticmethod, so this should work
a = a.__new__(A)
a.meth()
# __new__ returns not an instance of the class (None here), __init__
# should not be called
class B:
def __new__(self, v1, v2):
print("B.__new__", v1, v2)
def __init__(self, v1, v2):
# Should not be called in this test
print("B.__init__", v1, v2)
print("B inst:", B(1, 2))
# Variation of the above, __new__ returns an instance of another class,
# __init__ should not be called
class Dummy: pass
class C:
def __new__(cls):
print("C.__new__")
return Dummy()
def __init__(self):
# Should not be called in this test
print("C.__init__")
c = C()
print(isinstance(c, Dummy))
| YifuLiu/AliOS-Things | components/py_engine/tests/basics/class_new.py | Python | apache-2.0 | 1,254 |
# Test that returning of NotImplemented from binary op methods leads to
# TypeError.
try:
NotImplemented
except NameError:
print("SKIP")
raise SystemExit
class C:
def __init__(self, value):
self.value = value
def __str__(self):
return "C({})".format(self.value)
def __add__(self, rhs):
print(self, '+', rhs)
return NotImplemented
def __sub__(self, rhs):
print(self, '-', rhs)
return NotImplemented
def __lt__(self, rhs):
print(self, '<', rhs)
return NotImplemented
def __neg__(self):
print('-', self)
return NotImplemented
c = C(0)
try:
c + 1
except TypeError:
print("TypeError")
try:
c - 2
except TypeError:
print("TypeError")
try:
c < 1
except TypeError:
print("TypeError")
# NotImplemented isn't handled specially in unary methods
print(-c)
# Test that NotImplemented can be hashed
print(type(hash(NotImplemented)))
| YifuLiu/AliOS-Things | components/py_engine/tests/basics/class_notimpl.py | Python | apache-2.0 | 971 |
# test class with __add__ and __sub__ methods
class C:
def __init__(self, value):
self.value = value
def __add__(self, rhs):
print(self.value, '+', rhs)
def __sub__(self, rhs):
print(self.value, '-', rhs)
c = C(0)
c + 1
c - 2
| YifuLiu/AliOS-Things | components/py_engine/tests/basics/class_number.py | Python | apache-2.0 | 266 |
# test using an OrderedDict as the locals to construct a class
try:
from ucollections import OrderedDict
except ImportError:
try:
from collections import OrderedDict
except ImportError:
print("SKIP")
raise SystemExit
if not hasattr(int, "__dict__"):
print("SKIP")
raise SystemExit
A = type("A", (), OrderedDict(a=1, b=2, c=3, d=4, e=5))
print([k for k in A.__dict__.keys() if not k.startswith("_")])
| YifuLiu/AliOS-Things | components/py_engine/tests/basics/class_ordereddict.py | Python | apache-2.0 | 448 |
class A:
def __init__(self, v):
self.v = v
def __add__(self, o):
if isinstance(o, A):
return A(self.v + o.v)
return A(self.v + o)
def __radd__(self, o):
return A(self.v + o)
def __repr__(self):
return "A({})".format(self.v)
print(A(3) + 1)
print(2 + A(5))
| YifuLiu/AliOS-Things | components/py_engine/tests/basics/class_reverse_op.py | Python | apache-2.0 | 329 |
# test static and class methods
class C:
@staticmethod
def f(rhs):
print('f', rhs)
@classmethod
def g(self, rhs):
print('g', rhs)
# builtin wrapped in staticmethod
@staticmethod
def __sub__(rhs):
print('sub', rhs)
# builtin wrapped in classmethod
@classmethod
def __add__(self, rhs):
print('add', rhs)
# subscript special methods wrapped in staticmethod
@staticmethod
def __getitem__(item):
print('static get', item)
return 'item'
@staticmethod
def __setitem__(item, value):
print('static set', item, value)
@staticmethod
def __delitem__(item):
print('static del', item)
c = C()
c.f(0)
c.g(0)
c - 1
c + 2
print(c[1])
c[1] = 2
del c[3]
| YifuLiu/AliOS-Things | components/py_engine/tests/basics/class_staticclassmethod.py | Python | apache-2.0 | 772 |
# store to class vs instance
class C:
pass
c = C()
c.x = 1
print(c.x)
C.x = 2
C.y = 3
print(c.x, c.y)
print(C.x, C.y)
print(C().x, C().y)
c = C()
print(c.x)
c.x = 4
print(c.x)
| YifuLiu/AliOS-Things | components/py_engine/tests/basics/class_store.py | Python | apache-2.0 | 182 |
# Inspired by urlparse.py from CPython 3.3 stdlib
# There was a bug in MicroPython that under some conditions class stored
# in instance attribute later was returned "bound" as if it was a method,
# which caused class constructor to receive extra argument.
try:
from collections import namedtuple
except ImportError:
try:
from ucollections import namedtuple
except ImportError:
print("SKIP")
raise SystemExit
_DefragResultBase = namedtuple('DefragResult', [ 'foo', 'bar' ])
class _ResultMixinStr(object):
def encode(self):
return self._encoded_counterpart(*(x.encode() for x in self))
class _ResultMixinBytes(object):
def decode(self):
return self._decoded_counterpart(*(x.decode() for x in self))
class DefragResult(_DefragResultBase, _ResultMixinStr):
pass
class DefragResultBytes(_DefragResultBase, _ResultMixinBytes):
pass
DefragResult._encoded_counterpart = DefragResultBytes
DefragResultBytes._decoded_counterpart = DefragResult
# Due to differences in type and native subclass printing,
# the best thing we can do here is to just test that no exceptions
# happen
#print(DefragResult, DefragResult._encoded_counterpart)
#print(DefragResultBytes, DefragResultBytes._decoded_counterpart)
o1 = DefragResult("a", "b")
#print(o1, type(o1))
o2 = DefragResultBytes("a", "b")
#print(o2, type(o2))
#print(o1._encoded_counterpart)
_o1 = o1.encode()
print(_o1[0], _o1[1])
#print(_o1, type(_o1))
print("All's ok")
| YifuLiu/AliOS-Things | components/py_engine/tests/basics/class_store_class.py | Python | apache-2.0 | 1,488 |
class C1:
def __init__(self, value):
self.value = value
def __str__(self):
return "str<C1 {}>".format(self.value)
class C2:
def __init__(self, value):
self.value = value
def __repr__(self):
return "repr<C2 {}>".format(self.value)
class C3:
def __init__(self, value):
self.value = value
def __str__(self):
return "str<C3 {}>".format(self.value)
def __repr__(self):
return "repr<C3 {}>".format(self.value)
c1 = C1(1)
print(c1)
c2 = C2(2)
print(c2)
s11 = str(c1)
print(s11)
# This will use builtin repr(), which uses id(), which is of course different
# between CPython and MicroPython
s12 = repr(c1)
print("C1 object at" in s12)
s21 = str(c2)
print(s21)
s22 = repr(c2)
print(s22)
c3 = C3(1)
print(c3)
| YifuLiu/AliOS-Things | components/py_engine/tests/basics/class_str.py | Python | apache-2.0 | 794 |
class Base:
def __init__(self):
self.a = 1
def meth(self):
print("in Base meth", self.a)
class Sub(Base):
def meth(self):
print("in Sub meth")
return super().meth()
a = Sub()
a.meth()
# printing super
class A:
def p(self):
print(str(super())[:18])
A().p()
# test compiler's handling of long expressions with super
class A:
bar = 123
def foo(self):
print('A foo')
return [1, 2, 3]
class B(A):
def foo(self):
print('B foo')
print(super().bar) # accessing attribute after super()
return super().foo().count(2) # calling a subsequent method
print(B().foo())
# first arg to super must be a type
try:
super(1, 1)
except TypeError:
print('TypeError')
# store/delete of super attribute not allowed
assert hasattr(super(B, B()), 'foo')
try:
super(B, B()).foo = 1
except AttributeError:
print('AttributeError')
try:
del super(B, B()).foo
except AttributeError:
print('AttributeError')
| YifuLiu/AliOS-Things | components/py_engine/tests/basics/class_super.py | Python | apache-2.0 | 1,017 |
# test using the name "super" as a local variable
class A:
def foo(self):
super = [1, 2]
super.pop()
print(super)
A().foo()
| YifuLiu/AliOS-Things | components/py_engine/tests/basics/class_super_aslocal.py | Python | apache-2.0 | 154 |