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 errors from bad operations (unary, binary, etc)
# unsupported unary operators
try:
~bytearray()
except TypeError:
print('TypeError')
# unsupported binary operators
try:
bytearray() // 2
except TypeError:
print('TypeError')
# object with buffer protocol needed on rhs
try:
bytearray(1) + 1
except TypeError:
print('TypeError')
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/basics/op_error_bytearray.py
|
Python
|
apache-2.0
| 360
|
# test errors from bad operations (unary, binary, etc)
def test_exc(code, exc):
try:
exec(code)
print("no exception")
except exc:
print("right exception")
except:
print("wrong exception")
# object with buffer protocol needed on rhs
try:
(1 << 70) in 1
except TypeError:
print('TypeError')
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/basics/op_error_intbig.py
|
Python
|
apache-2.0
| 343
|
# test errors from bad operations with literals
# these raise a SyntaxWarning in CPython; see https://bugs.python.org/issue15248
# unsupported subscription
try:
1[0]
except TypeError:
print("TypeError")
try:
""[""]
except TypeError:
print("TypeError")
# not callable
try:
1()
except TypeError:
print("TypeError")
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/basics/op_error_literal.py
|
Python
|
apache-2.0
| 339
|
# test errors from bad operations (unary, binary, etc)
try:
memoryview
except:
print("SKIP")
raise SystemExit
# unsupported binary operators
try:
m = memoryview(bytearray())
m += bytearray()
except TypeError:
print('TypeError')
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/basics/op_error_memoryview.py
|
Python
|
apache-2.0
| 253
|
# see https://docs.python.org/3/reference/expressions.html#operator-precedence
# '|' is the least binding numeric operator
# '^'
# OK: 1 | (2 ^ 3) = 1 | 1 = 1
# BAD: (1 | 2) ^ 3 = 3 ^ 3 = 0
print(1 | 2 ^ 3)
# '&'
# OK: 3 ^ (2 & 1) = 3 ^ 0 = 3
# BAD: (3 ^ 2) & 1 = 1 & 1 = 1
print(3 ^ 2 & 1)
# '<<', '>>'
# OK: 2 & (3 << 1) = 2 & 6 = 2
# BAD: (2 & 3) << 1 = 2 << 1 = 4
print(2 & 3 << 1)
# OK: 6 & (4 >> 1) = 6 & 2 = 2
# BAD: (6 & 4) >> 1 = 2 >> 1 = 1
print(6 & 4 >> 1)
# '+', '-'
# OK: 1 << (1 + 1) = 1 << 2 = 4
# BAD: (1 << 1) + 1 = 2 + 1 = 3
print(1 << 1 + 1)
# '*', '/', '//', '%'
# OK: 2 + (2 * 2) = 2 + 4 = 6
# BAD: (2 + 2) * 2 = 4 * 2 = 8
print(2 + 2 * 2)
# '+x', '-x', '~x'
# '**'
# OK: -(2**2) = -4
# BAD: (-2)**2 = 4
print(-2**2)
# OK: 2**(-1) = 0.5
print(2**-0)
# (expr...)
print((2 + 2) * 2)
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/basics/op_precedence.py
|
Python
|
apache-2.0
| 818
|
try:
from collections import OrderedDict
except ImportError:
try:
from ucollections import OrderedDict
except ImportError:
print("SKIP")
raise SystemExit
d = OrderedDict([(10, 20), ("b", 100), (1, 2)])
print(len(d))
print(list(d.keys()))
print(list(d.values()))
del d["b"]
print(len(d))
print(list(d.keys()))
print(list(d.values()))
# access remaining elements after deleting
print(d[10], d[1])
# add an element after deleting
d["abc"] = 123
print(len(d))
print(list(d.keys()))
print(list(d.values()))
# pop an element
print(d.popitem())
print(len(d))
print(list(d.keys()))
print(list(d.values()))
# add an element after popping
d["xyz"] = 321
print(len(d))
print(list(d.keys()))
print(list(d.values()))
# pop until empty
print(d.popitem())
print(d.popitem())
try:
d.popitem()
except:
print('empty')
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/basics/ordereddict1.py
|
Python
|
apache-2.0
| 850
|
try:
from collections import OrderedDict
except ImportError:
try:
from ucollections import OrderedDict
except ImportError:
print("SKIP")
raise SystemExit
x = OrderedDict()
y = OrderedDict()
x['a'] = 1
x['b'] = 2
y['a'] = 1
y['b'] = 2
print(x)
print(y)
print(x == y)
z = OrderedDict()
z['b'] = 2
z['a'] = 1
print(y)
print(z)
print(y == z)
del z['b']
z['b'] = 2
print(y)
print(z)
print(y == z)
del x['a']
del y['a']
print(x)
print(y)
print(x == y)
del z['b']
del y['b']
print(y)
print(z)
print(y == z)
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/basics/ordereddict_eq.py
|
Python
|
apache-2.0
| 541
|
# parser tests
try:
compile
except NameError:
print("SKIP")
raise SystemExit
# completely empty string
# uPy and CPy differ for this case
#try:
# compile("", "stdin", "single")
#except SyntaxError:
# print("SyntaxError")
try:
compile("", "stdin", "eval")
except SyntaxError:
print("SyntaxError")
compile("", "stdin", "exec")
# empty continued line
try:
compile("\\\n", "stdin", "single")
except SyntaxError:
print("SyntaxError")
try:
compile("\\\n", "stdin", "eval")
except SyntaxError:
print("SyntaxError")
compile("\\\n", "stdin", "exec")
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/basics/parser.py
|
Python
|
apache-2.0
| 586
|
# tests that differ when running under Python 3.4 vs 3.5/3.6/3.7
try:
exec
except NameError:
print("SKIP")
raise SystemExit
# from basics/fun_kwvarargs.py
# test evaluation order of arguments (in 3.4 it's backwards, 3.5 it's fixed)
def f4(*vargs, **kwargs):
print(vargs, kwargs)
def print_ret(x):
print(x)
return x
f4(*print_ret(['a', 'b']), kw_arg=print_ret(None))
# test evaluation order of dictionary key/value pair (in 3.4 it's backwards)
{print_ret(1):print_ret(2)}
# from basics/syntaxerror.py
def test_syntax(code):
try:
exec(code)
except SyntaxError:
print("SyntaxError")
test_syntax("f(*a, *b)") # can't have multiple * (in 3.5 we can)
test_syntax("f(**a, **b)") # can't have multiple ** (in 3.5 we can)
test_syntax("f(*a, b)") # can't have positional after *
test_syntax("f(**a, b)") # can't have positional after **
test_syntax("() = []") # can't assign to empty tuple (in 3.6 we can)
test_syntax("del ()") # can't delete empty tuple (in 3.6 we can)
# from basics/sys1.py
# uPy prints version 3.4
import usys
print(usys.version[:3])
print(usys.version_info[0], usys.version_info[1])
# from basics/exception1.py
# in 3.7 no comma is printed if there is only 1 arg (in 3.4-3.6 one is printed)
print(repr(IndexError("foo")))
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/basics/python34.py
|
Python
|
apache-2.0
| 1,287
|
# tests for things that only Python 3.6 supports
# underscores in numeric literals
print(100_000)
print(0b1010_0101)
print(0xff_ff)
# underscore supported by int constructor
print(int('1_2_3'))
print(int('0o1_2_3', 8))
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/basics/python36.py
|
Python
|
apache-2.0
| 221
|
# test return statement
def f():
return
print(f())
def g():
return 1
print(g())
def f(x):
return 1 if x else 2
print(f(0), f(1))
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/basics/return1.py
|
Python
|
apache-2.0
| 144
|
# test scoping rules
# explicit global variable
a = 1
def f():
global a
global a, a # should be able to redefine as global
a = 2
f()
print(a)
# explicit nonlocal variable
def f():
a = 1
def g():
nonlocal a
nonlocal a, a # should be able to redefine as nonlocal
a = 2
g()
return a
print(f())
# nonlocal at inner-inner level (h)
def f():
x = 1
def g():
def h():
nonlocal x
return x
return h
return g
print(f()()())
# nonlocal declared at outer level (g), and referenced by inner level (h)
def f():
x = 1
def g():
nonlocal x
def h():
return x
return h
return g
print(f()()())
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/basics/scope.py
|
Python
|
apache-2.0
| 729
|
# test implicit scoping rules
# implicit nonlocal, with variable defined after closure
def f():
def g():
return x # implicit nonlocal
x = 3 # variable defined after function that closes over it
return g
print(f()())
# implicit nonlocal at inner level, with variable defined after closure
def f():
def g():
def h():
return x # implicit nonlocal
return h
x = 4 # variable defined after function that closes over it
return g
print(f()()())
# local variable which should not be implicitly made nonlocal
def f():
x = 0
def g():
x # local because next statement assigns to it
x = 1
g()
try:
f()
except NameError:
print('NameError')
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/basics/scope_implicit.py
|
Python
|
apache-2.0
| 725
|
# make sure type of first arg (self) to a builtin method is checked
list.append
try:
list.append()
except TypeError as e:
print("TypeError")
try:
list.append(1)
except TypeError as e:
print("TypeError")
try:
list.append(1, 2)
except TypeError as e:
print("TypeError")
l = []
list.append(l, 2)
print(l)
try:
getattr(list, "append")(1, 2)
except TypeError as e:
print("TypeError")
l = []
getattr(list, "append")(l, 2)
print(l)
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/basics/self_type_check.py
|
Python
|
apache-2.0
| 464
|
# Basics
a, b = 1, 2
print(a, b)
a, b = (1, 2)
print(a, b)
(a, b) = 1, 2
print(a, b)
(a, b) = (1, 2)
print(a, b)
# Tuples/lists are optimized
a, b = [1, 2]
print(a, b)
[a, b] = 100, 200
print(a, b)
# optimised 3-way swap
a = 1
b = 2
c = 3
a, b, c = b, c, a
print(a, b, c)
try:
a, b, c = (1, 2)
except ValueError:
print("ValueError")
try:
a, b, c = [1, 2, 3, 4]
except ValueError:
print("ValueError")
# Generic iterable object
a, b, c = range(3)
print(a, b, c)
try:
a, b, c = range(2)
except ValueError:
print("ValueError")
try:
a, b, c = range(4)
except ValueError:
print("ValueError")
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/basics/seq_unpack.py
|
Python
|
apache-2.0
| 622
|
s = {1, 2, 3, 4}
print(s.add(5))
print(sorted(s))
s = set()
s.add(0)
s.add(False)
print(s)
s = set()
s.add(False)
s.add(0)
print(s)
s = set()
s.add(1)
s.add(True)
print(s)
s = set()
s.add(True)
s.add(1)
print(s)
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/basics/set_add.py
|
Python
|
apache-2.0
| 216
|
# basic sets
s = {1}
print(s)
s = {3, 4, 3, 1}
print(sorted(s))
# expression in constructor
s = {1 + len(s)}
print(s)
# bools mixed with integers
s = {False, True, 0, 1, 2}
print(len(s))
# Sets are not hashable
try:
{s: 1}
except TypeError:
print("TypeError")
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/basics/set_basic.py
|
Python
|
apache-2.0
| 273
|
# test set binary operations
sets = [set(), {1}, {1, 2}, {1, 2, 3}, {2, 3}, {2, 3, 5}, {5}, {7}]
for s in sets:
for t in sets:
print(sorted(s), '|', sorted(t), '=', sorted(s | t))
print(sorted(s), '^', sorted(t), '=', sorted(s ^ t))
print(sorted(s), '&', sorted(t), '=', sorted(s & t))
print(sorted(s), '-', sorted(t), '=', sorted(s - t))
u = s.copy()
u |= t
print(sorted(s), "|=", sorted(t), '-->', sorted(u))
u = s.copy()
u ^= t
print(sorted(s), "^=", sorted(t), '-->', sorted(u))
u = s.copy()
u &= t
print(sorted(s), "&=", sorted(t), "-->", sorted(u))
u = s.copy()
u -= t
print(sorted(s), "-=", sorted(t), "-->", sorted(u))
print(sorted(s), '==', sorted(t), '=', s == t)
print(sorted(s), '!=', sorted(t), '=', s != t)
print(sorted(s), '>', sorted(t), '=', s > t)
print(sorted(s), '>=', sorted(t), '=', s >= t)
print(sorted(s), '<', sorted(t), '=', s < t)
print(sorted(s), '<=', sorted(t), '=', s <= t)
print(set('abc') == 1)
# make sure inplace operators modify the set
s1 = s2 = set('abc')
s1 |= set('ad')
print(s1 is s2, len(s1))
s1 = s2 = set('abc')
s1 ^= set('ad')
print(s1 is s2, len(s1))
s1 = s2 = set('abc')
s1 &= set('ad')
print(s1 is s2, len(s1))
s1 = s2 = set('abc')
s1 -= set('ad')
print(s1 is s2, len(s1))
# RHS must be a set
try:
print(set('12') >= '1')
except TypeError:
print('TypeError')
# RHS must be a set
try:
print(set('12') <= '123')
except TypeError:
print('TypeError')
# unsupported operator
try:
set('abc') * set('abc')
except TypeError:
print('TypeError')
# unsupported operator with RHS not a set
try:
set('abc') * 2
except TypeError:
print('TypeError')
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/basics/set_binop.py
|
Python
|
apache-2.0
| 1,807
|
s = {1, 2, 3, 4}
print(s.clear())
print(list(s))
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/basics/set_clear.py
|
Python
|
apache-2.0
| 49
|
print({a for a in range(5)})
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/basics/set_comprehension.py
|
Python
|
apache-2.0
| 29
|
for i in 1, 2:
for o in {}, {1}, {2}:
print("{} in {}: {}".format(i, o, i in o))
print("{} not in {}: {}".format(i, o, i not in o))
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/basics/set_containment.py
|
Python
|
apache-2.0
| 152
|
s = {1, 2, 3, 4}
t = s.copy()
s.add(5)
t.add(7)
for i in s, t:
print(sorted(i))
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/basics/set_copy.py
|
Python
|
apache-2.0
| 84
|
l = [1, 2, 3, 4]
s = set(l)
outs = [s.difference(),
s.difference({1}),
s.difference({1}, [1, 2]),
s.difference({1}, {1, 2}, {2, 3})]
for out in outs:
print(sorted(out))
s = set(l)
print(s.difference_update())
print(sorted(s))
print(s.difference_update({1}))
print(sorted(s))
print(s.difference_update({1}, [2]))
print(sorted(s))
s.difference_update(s)
print(s)
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/basics/set_difference.py
|
Python
|
apache-2.0
| 391
|
s = {1, 2}
print(s.discard(1))
print(list(s))
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/basics/set_discard.py
|
Python
|
apache-2.0
| 46
|
s = {1, 2, 3, 4}
print(sorted(s))
print(sorted(s.intersection({1, 3})))
print(sorted(s.intersection([3, 4])))
print(s.intersection_update([1]))
print(sorted(s))
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/basics/set_intersection.py
|
Python
|
apache-2.0
| 162
|
s = {1, 2, 3, 4}
print(s.isdisjoint({1}))
print(s.isdisjoint([2]))
print(s.isdisjoint([]))
print(s.isdisjoint({7,8,9,10}))
print(s.isdisjoint([7,8,9,1]))
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/basics/set_isdisjoint.py
|
Python
|
apache-2.0
| 154
|
sets = [set(), {1}, {1, 2, 3}, {3, 4, 5}, {5, 6, 7}]
args = sets + [[1], [1, 2], [1, 2 ,3]]
for i in sets:
for j in args:
print(i.issubset(j))
print(i.issuperset(j))
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/basics/set_isfooset.py
|
Python
|
apache-2.0
| 186
|
s = {1, 2, 3, 4}
l = list(s)
l.sort()
print(l)
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/basics/set_iter.py
|
Python
|
apache-2.0
| 48
|
i = iter(iter({1, 2, 3}))
print(sorted(i))
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/basics/set_iter_of_iter.py
|
Python
|
apache-2.0
| 43
|
s = {1}
print(s.pop())
try:
print(s.pop(), "!!!")
except KeyError:
pass
else:
print("Failed to raise KeyError")
# this tests an optimisation in mp_set_remove_first
# N must not be equal to one of the values in hash_allocation_sizes
N = 11
s = set(range(N))
while s:
print(s.pop()) # last pop() should trigger the optimisation
for i in range(N):
s.add(i) # check that we can add the numbers back to the set
print(sorted(s))
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/basics/set_pop.py
|
Python
|
apache-2.0
| 444
|
# basic test
s = {1}
print(s.remove(1))
print(list(s))
try:
print(s.remove(1), "!!!")
except KeyError as er:
print('KeyError', er.args[0])
else:
print("failed to raise KeyError")
# test sets of varying size
for n in range(20):
print('testing set with {} items'.format(n))
for i in range(n):
# create set
s = set()
for j in range(n):
s.add(str(j))
print(len(s))
# delete an item
s.remove(str(i))
print(len(s))
# check items
for j in range(n):
if str(j) in s:
if j == i:
print(j, 'in s, but it should not be')
else:
if j != i:
print(j, 'not in s, but it should be')
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/basics/set_remove.py
|
Python
|
apache-2.0
| 767
|
# set object with special methods
s = {1, 2}
print(s.__contains__(1))
print(s.__contains__(3))
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/basics/set_specialmeth.py
|
Python
|
apache-2.0
| 96
|
print(sorted({1,2}.symmetric_difference({2,3})))
print(sorted({1,2}.symmetric_difference([2,3])))
s = {1,2}
print(s.symmetric_difference_update({2,3}))
print(sorted(s))
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/basics/set_symmetric_difference.py
|
Python
|
apache-2.0
| 169
|
# set type
# This doesn't really work as expected, because {None}
# leads SyntaxError during parsing.
try:
set
except NameError:
print("SKIP")
raise SystemExit
print(set)
print(type(set()) == set)
print(type({None}) == set)
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/basics/set_type.py
|
Python
|
apache-2.0
| 240
|
print(sorted({1}.union({2})))
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/basics/set_union.py
|
Python
|
apache-2.0
| 30
|
# test set unary operations
print(bool(set()))
print(bool(set('abc')))
print(len(set()))
print(len(set('abc')))
try:
hash(set('abc'))
except TypeError:
print('TypeError')
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/basics/set_unop.py
|
Python
|
apache-2.0
| 182
|
s = {1}
s.update()
print(s)
s.update([2])
print(sorted(s))
s.update([1,3], [2,2,4])
print(sorted(s))
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/basics/set_update.py
|
Python
|
apache-2.0
| 101
|
# test builtin slice attributes access
# print slice attributes
class A:
def __getitem__(self, idx):
print(idx.start, idx.stop, idx.step)
try:
t = A()[1:2]
except:
print("SKIP")
raise SystemExit
A()[1:2:3]
# test storing to attr (shouldn't be allowed)
class B:
def __getitem__(self, idx):
try:
idx.start = 0
except AttributeError:
print('AttributeError')
B()[:]
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/basics/slice_attrs.py
|
Python
|
apache-2.0
| 435
|
# Test builtin slice indices resolution
# A class that returns an item key
class A:
def __getitem__(self, idx):
return idx
# Make sure that we have slices and .indices()
try:
A()[2:5].indices(10)
except:
print("SKIP")
raise SystemExit
print(A()[:].indices(10))
print(A()[2:].indices(10))
print(A()[:7].indices(10))
print(A()[2:7].indices(10))
print(A()[2:7:2].indices(10))
print(A()[2:7:-2].indices(10))
print(A()[7:2:2].indices(10))
print(A()[7:2:-2].indices(10))
print(A()[2:7:2].indices(5))
print(A()[2:7:-2].indices(5))
print(A()[7:2:2].indices(5))
print(A()[7:2:-2].indices(5))
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/basics/slice_indices.py
|
Python
|
apache-2.0
| 611
|
# test slicing when arguments are bignums
print(list(range(10))[(1<<66)>>65:])
print(list(range(10))[:(1<<66)>>65])
print(list(range(10))[::(1<<66)>>65])
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/basics/slice_intbig.py
|
Python
|
apache-2.0
| 155
|
class A:
def __bool__(self):
print('__bool__')
return True
def __len__(self):
print('__len__')
return 1
class B:
def __len__(self):
print('__len__')
return 0
print(bool(A()))
print(len(A()))
print(bool(B()))
print(len(B()))
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/basics/slots_bool_len.py
|
Python
|
apache-2.0
| 286
|
class A:
def __eq__(self, other):
print("A __eq__ called")
return True
class B:
def __ne__(self, other):
print("B __ne__ called")
return True
class C:
def __eq__(self, other):
print("C __eq__ called")
return False
class D:
def __ne__(self, other):
print("D __ne__ called")
return False
a = A()
b = B()
c = C()
d = D()
def test(s):
print(s)
print(eval(s))
for x in 'abcd':
for y in 'abcd':
test('{} == {}'.format(x,y))
test('{} != {}'.format(x,y))
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/basics/special_comparisons.py
|
Python
|
apache-2.0
| 561
|
class E:
def __repr__(self):
return "E"
def __eq__(self, other):
print('E eq', other)
return 123
class F:
def __repr__(self):
return "F"
def __ne__(self, other):
print('F ne', other)
return -456
print(E() != F())
print(F() != E())
tests = (None, 0, 1, 'a')
for val in tests:
print('==== testing', val)
print(E() == val)
print(val == E())
print(E() != val)
print(val != E())
print(F() == val)
print(val == F())
print(F() != val)
print(val != F())
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/basics/special_comparisons2.py
|
Python
|
apache-2.0
| 552
|
class Cud():
def __init__(self):
print("__init__ called")
def __repr__(self):
print("__repr__ called")
return ""
def __lt__(self, other):
print("__lt__ called")
def __le__(self, other):
print("__le__ called")
def __eq__(self, other):
print("__eq__ called")
def __ne__(self, other):
print("__ne__ called")
def __ge__(self, other):
print("__ge__ called")
def __gt__(self, other):
print("__gt__ called")
def __abs__(self):
print("__abs__ called")
def __add__(self, other):
print("__add__ called")
def __and__(self, other):
print("__and__ called")
def __floordiv__(self, other):
print("__floordiv__ called")
def __index__(self, other):
print("__index__ called")
def __inv__(self):
print("__inv__ called")
def __invert__(self):
print("__invert__ called")
def __lshift__(self, val):
print("__lshift__ called")
def __mod__(self, val):
print("__mod__ called")
def __mul__(self, other):
print("__mul__ called")
def __matmul__(self, other):
print("__matmul__ called")
def __neg__(self):
print("__neg__ called")
def __or__(self, other):
print("__or__ called")
def __pos__(self):
print("__pos__ called")
def __pow__(self, val):
print("__pow__ called")
def __rshift__(self, val):
print("__rshift__ called")
def __sub__(self, other):
print("__sub__ called")
def __truediv__(self, other):
print("__truediv__ called")
def __div__(self, other):
print("__div__ called")
def __xor__(self, other):
print("__xor__ called")
def __iadd__(self, other):
print("__iadd__ called")
return self
def __isub__(self, other):
print("__isub__ called")
return self
def __int__(self):
return 42
cud1 = Cud()
cud2 = Cud()
str(cud1)
cud1 == cud1
cud1 == cud2
cud1 != cud1
cud1 != cud2
cud1 < cud2
cud1 <= cud2
cud1 == cud2
cud1 >= cud2
cud1 > cud2
cud1 + cud2
cud1 - cud2
print(int(cud1))
class BadInt:
def __int__(self):
print("__int__ called")
return None
try:
int(BadInt())
except TypeError:
print("TypeError")
# more in special_methods2.py
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/basics/special_methods.py
|
Python
|
apache-2.0
| 2,366
|
class Cud():
def __init__(self):
#print("__init__ called")
pass
def __repr__(self):
print("__repr__ called")
return ""
def __lt__(self, other):
print("__lt__ called")
def __le__(self, other):
print("__le__ called")
def __eq__(self, other):
print("__eq__ called")
def __ne__(self, other):
print("__ne__ called")
def __ge__(self, other):
print("__ge__ called")
def __gt__(self, other):
print("__gt__ called")
def __abs__(self):
print("__abs__ called")
def __add__(self, other):
print("__add__ called")
def __and__(self, other):
print("__and__ called")
def __floordiv__(self, other):
print("__floordiv__ called")
def __index__(self, other):
print("__index__ called")
def __inv__(self):
print("__inv__ called")
def __invert__(self):
print("__invert__ called")
def __lshift__(self, val):
print("__lshift__ called")
def __mod__(self, val):
print("__mod__ called")
def __mul__(self, other):
print("__mul__ called")
def __matmul__(self, other):
print("__matmul__ called")
def __neg__(self):
print("__neg__ called")
def __or__(self, other):
print("__or__ called")
def __pos__(self):
print("__pos__ called")
def __pow__(self, val):
print("__pow__ called")
def __rshift__(self, val):
print("__rshift__ called")
def __sub__(self, other):
print("__sub__ called")
def __truediv__(self, other):
print("__truediv__ called")
def __div__(self, other):
print("__div__ called")
def __xor__(self, other):
print("__xor__ called")
def __iadd__(self, other):
print("__iadd__ called")
return self
def __isub__(self, other):
print("__isub__ called")
return self
def __dir__(self):
return ['a', 'b', 'c']
cud1 = Cud()
cud2 = Cud()
try:
+cud1
except TypeError:
print("SKIP")
raise SystemExit
# the following require MICROPY_PY_ALL_SPECIAL_METHODS
+cud1
-cud1
~cud1
cud1 * cud2
cud1 @ cud2
cud1 / cud2
cud2 // cud1
cud1 += cud2
cud1 -= cud2
cud1 % 2
cud1 ** 2
cud1 | cud2
cud1 & cud2
cud1 ^ cud2
cud1 << 1
cud1 >> 1
# test that dir() delegates to __dir__ special method
print(dir(cud1))
# test that dir() does not delegate to __dir__ for the type
print('a' in dir(Cud))
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/basics/special_methods2.py
|
Python
|
apache-2.0
| 2,493
|
# test StopIteration interaction with generators
try:
enumerate, exec
except:
print("SKIP")
raise SystemExit
def get_stop_iter_arg(msg, code):
try:
exec(code)
print("FAIL")
except StopIteration as er:
print(msg, er.args)
class A:
def __iter__(self):
return self
def __next__(self):
raise StopIteration(42)
class B:
def __getitem__(self, index):
# argument to StopIteration should get ignored
raise StopIteration(42)
def gen(x):
return x
yield
def gen2(x):
try:
yield
except ValueError:
pass
return x
get_stop_iter_arg("next", "next(A())")
get_stop_iter_arg("iter", "next(iter(B()))")
get_stop_iter_arg("enumerate", "next(enumerate(A()))")
get_stop_iter_arg("map", "next(map(lambda x:x, A()))")
get_stop_iter_arg("zip", "next(zip(A()))")
g = gen(None)
get_stop_iter_arg("generator0", "next(g)")
get_stop_iter_arg("generator1", "next(g)")
g = gen(42)
get_stop_iter_arg("generator0", "next(g)")
get_stop_iter_arg("generator1", "next(g)")
get_stop_iter_arg("send", "gen(None).send(None)")
get_stop_iter_arg("send", "gen(42).send(None)")
g = gen2(None)
next(g)
get_stop_iter_arg("throw", "g.throw(ValueError)")
g = gen2(42)
next(g)
get_stop_iter_arg("throw", "g.throw(ValueError)")
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/basics/stopiteration.py
|
Python
|
apache-2.0
| 1,315
|
# basic strings
# literals
print('abc')
print(r'abc')
print(u'abc')
print(repr('\a\b\t\n\v\f\r'))
print('\z') # unrecognised escape char
# construction
print(str())
print(str('abc'))
# inplace addition
x = 'abc'
print(x)
x += 'def'
print(x)
# binary ops
print('123' + "456")
print('123' * 5)
try:
'123' * '1'
except TypeError:
print('TypeError')
try:
'123' + 1
except TypeError:
print('TypeError')
# subscription
print('abc'[1])
print('abc'[-1])
try:
'abc'[100]
except IndexError:
print('IndexError')
try:
'abc'[-4]
except IndexError:
print('IndexError')
# iter
print(list('str'))
# comparison
print('123' + '789' == '123789')
print('a' + 'b' != 'a' + 'b ')
print('1' + '2' > '2')
print('1' + '2' < '2')
# printing quote char in string
print(repr('\'\"'))
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/basics/string1.py
|
Python
|
apache-2.0
| 796
|
try:
str.center
except:
print("SKIP")
raise SystemExit
print("foo".center(0))
print("foo".center(1))
print("foo".center(3))
print("foo".center(4))
print("foo".center(5))
print("foo".center(6))
print("foo".center(20))
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/basics/string_center.py
|
Python
|
apache-2.0
| 230
|
print("" == "")
print("" > "")
print("" < "")
print("" == "1")
print("1" == "")
print("" > "1")
print("1" > "")
print("" < "1")
print("1" < "")
print("" >= "1")
print("1" >= "")
print("" <= "1")
print("1" <= "")
print("1" == "1")
print("1" != "1")
print("1" == "2")
print("1" == "10")
print("1" > "1")
print("1" > "2")
print("2" > "1")
print("10" > "1")
print("1/" > "1")
print("1" > "10")
print("1" > "1/")
print("1" < "1")
print("2" < "1")
print("1" < "2")
print("1" < "10")
print("1" < "1/")
print("10" < "1")
print("1/" < "1")
print("1" >= "1")
print("1" >= "2")
print("2" >= "1")
print("10" >= "1")
print("1/" >= "1")
print("1" >= "10")
print("1" >= "1/")
print("1" <= "1")
print("2" <= "1")
print("1" <= "2")
print("1" <= "10")
print("1" <= "1/")
print("10" <= "1")
print("1/" <= "1")
# this tests an internal string that doesn't have a hash with a string
# that does have a hash, but the lengths of the two strings are different
try:
import usys as sys
except ImportError:
import sys
print(sys.version == 'a long string that has a hash')
# this special string would have a hash of 0 but is incremented to 1
print('Q+?' == 'Q' + '+?')
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/basics/string_compare.py
|
Python
|
apache-2.0
| 1,156
|
try:
str.count
except AttributeError:
print("SKIP")
raise SystemExit
print("".count(""))
print("".count("a"))
print("a".count(""))
print("a".count("a"))
print("a".count("b"))
print("b".count("a"))
print("aaa".count(""))
print("aaa".count("a"))
print("aaa".count("aa"))
print("aaa".count("aaa"))
print("aaa".count("aaaa"))
print("aaaa".count(""))
print("aaaa".count("a"))
print("aaaa".count("aa"))
print("aaaa".count("aaa"))
print("aaaa".count("aaaa"))
print("aaaa".count("aaaaa"))
print("aaa".count("", 1))
print("aaa".count("", 2))
print("aaa".count("", 3))
print("aaa".count("", 1, 2))
print("asdfasdfaaa".count("asdf", -100))
print("asdfasdfaaa".count("asdf", -8))
print("asdf".count('s', True))
print("asdf".count('a', True))
print("asdf".count('a', False))
print("asdf".count('a', 1 == 2))
print("hello world".count('l'))
print("hello world".count('l', 5))
print("hello world".count('l', 3))
print("hello world".count('z', 3, 6))
print("aaaa".count('a'))
print("aaaa".count('a', 0, 3))
print("aaaa".count('a', 0, 4))
print("aaaa".count('a', 0, 5))
print("aaaa".count('a', 1, 5))
print("aaaa".count('a', -1, 5))
print("abbabba".count("abba"))
def t():
return True
print("0000".count('0', t()))
try:
'abc'.count(1)
except TypeError:
print('TypeError')
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/basics/string_count.py
|
Python
|
apache-2.0
| 1,288
|
# this file has CR line endings to test lexer's conversion of them to LF
# in triple quoted strings
print(repr("""abc
def"""))
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/basics/string_cr_conversion.py
|
Python
|
apache-2.0
| 127
|
# this file has CRLF line endings to test lexer's conversion of them to LF
# in triple quoted strings
print(repr("""abc
def"""))
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/basics/string_crlf_conversion.py
|
Python
|
apache-2.0
| 133
|
print("foobar".endswith("bar"))
print("foobar".endswith("baR"))
print("foobar".endswith("bar1"))
print("foobar".endswith("foobar"))
print("foobar".endswith(""))
print("foobar".endswith("foobarbaz"))
#print("1foobar".startswith("foo", 1))
#print("1foo".startswith("foo", 1))
#print("1foo".startswith("1foo", 1))
#print("1fo".startswith("foo", 1))
#print("1fo".startswith("foo", 10))
try:
"foobar".endswith(1)
except TypeError:
print("TypeError")
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/basics/string_endswith.py
|
Python
|
apache-2.0
| 455
|
# MicroPython doesn't support tuple argument
try:
"foobar".endswith(("bar", "sth"))
except TypeError:
print("TypeError")
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/basics/string_endswith_upy.py
|
Python
|
apache-2.0
| 130
|
a = "a\1b"
print(len(a))
print(ord(a[1]))
print(len("a\123b"))
a = "a\12345b"
print(len(a))
print(ord(a[1]))
a = "a\xffb"
print(len(a))
print(ord(a[1]))
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/basics/string_escape.py
|
Python
|
apache-2.0
| 154
|
print("hello world".find("ll"))
print("hello world".find("ll", None))
print("hello world".find("ll", 1))
print("hello world".find("ll", 1, None))
print("hello world".find("ll", None, None))
print("hello world".find("ll", 1, -1))
print("hello world".find("ll", 1, 1))
print("hello world".find("ll", 1, 2))
print("hello world".find("ll", 1, 3))
print("hello world".find("ll", 1, 4))
print("hello world".find("ll", 1, 5))
print("hello world".find("ll", -100))
print("0000".find('0'))
print("0000".find('0', 0))
print("0000".find('0', 1))
print("0000".find('0', 2))
print("0000".find('0', 3))
print("0000".find('0', 4))
print("0000".find('0', 5))
print("0000".find('-1', 3))
print("0000".find('1', 3))
print("0000".find('1', 4))
print("0000".find('1', 5))
print("aaaaaaaaaaa".find("bbb", 9, 2))
try:
'abc'.find(1)
except TypeError:
print('TypeError')
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/basics/string_find.py
|
Python
|
apache-2.0
| 856
|
# basic functionality test for {} format string
def test(fmt, *args):
print('{:8s}'.format(fmt) + '>' + fmt.format(*args) + '<')
test("}}{{")
test("{}-{}", 1, [4, 5])
test("{0}-{1}", 1, [4, 5])
test("{1}-{0}", 1, [4, 5])
test("{:x}", 1)
test("{!r}", 2)
test("{:x}", 0x10)
test("{!r}", "foo")
test("{!s}", "foo")
test("{0!r:>10s} {0!s:>10s}", "foo")
test("{:4b}", 10)
test("{:4c}", 48)
test("{:4d}", 123)
test("{:4n}", 123)
test("{:4o}", 123)
test("{:4x}", 123)
test("{:4X}", 123)
test("{:4,d}", 12345678)
test("{:#4b}", 10)
test("{:#4o}", 123)
test("{:#4x}", 123)
test("{:#4X}", 123)
test("{:#4d}", 0)
test("{:#4b}", 0)
test("{:#4o}", 0)
test("{:#4x}", 0)
test("{:#4X}", 0)
test("{:<6s}", "ab")
test("{:>6s}", "ab")
test("{:^6s}", "ab")
test("{:.1s}", "ab")
test("{: <6d}", 123)
test("{: <6d}", -123)
test("{:0<6d}", 123)
test("{:0<6d}", -123)
test("{:@<6d}", 123)
test("{:@<6d}", -123)
test("{:@< 6d}", 123)
test("{:@< 6d}", -123)
test("{:@<+6d}", 123)
test("{:@<+6d}", -123)
test("{:@<-6d}", 123)
test("{:@<-6d}", -123)
test("{:@>6d}", -123)
test("{:@<6d}", -123)
test("{:@=6d}", -123)
test("{:06d}", -123)
test("{:>20}", "foo")
test("{:^20}", "foo")
test("{:<20}", "foo")
# formatting bool as int
test('{:d}', False)
test('{:20}', False)
test('{:d}', True)
test('{:20}', True)
# nested format specifiers
print("{:{}}".format(123, '#>10'))
print("{:{}{}{}}".format(123, '#', '>', '10'))
print("{0:{1}{2}}".format(123, '#>', '10'))
print("{text:{align}{width}}".format(text="foo", align="<", width=20))
print("{text:{align}{width}}".format(text="foo", align="^", width=10))
print("{text:{align}{width}}".format(text="foo", align=">", width=30))
print("{foo}/foo".format(foo="bar"))
print("{}".format(123, foo="bar"))
print("{}-{foo}".format(123, foo="bar"))
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/basics/string_format.py
|
Python
|
apache-2.0
| 1,782
|
# comprehensive functionality test for {} format string
int_tests = False # these take a while
char_tests = True
str_tests = True
def test(fmt, *args):
print('{:8s}'.format(fmt) + '>' + fmt.format(*args) + '<')
def test_fmt(conv, fill, alignment, sign, prefix, width, precision, type, arg):
fmt = '{'
if conv:
fmt += '!'
fmt += conv
fmt += ':'
if alignment:
fmt += fill
fmt += alignment
fmt += sign
fmt += prefix
fmt += width
if precision:
fmt += '.'
fmt += precision
fmt += type
fmt += '}'
test(fmt, arg)
if fill == '0' and alignment == '=':
fmt = '{:'
fmt += sign
fmt += prefix
fmt += width
if precision:
fmt += '.'
fmt += precision
fmt += type
fmt += '}'
test(fmt, arg)
if int_tests:
int_nums = (-1234, -123, -12, -1, 0, 1, 12, 123, 1234, True, False)
#int_nums = (-12, -1, 0, 1, 12, True, False)
for type in ('', 'b', 'd', 'o', 'x', 'X'):
for width in ('', '1', '3', '5', '7'):
for alignment in ('', '<', '>', '=', '^'):
for fill in ('', ' ', '0', '@'):
for sign in ('', '+', '-', ' '):
for prefix in ('', '#'):
for num in int_nums:
test_fmt('', fill, alignment, sign, prefix, width, '', type, num)
if char_tests:
for width in ('', '1', '2'):
for alignment in ('', '<', '>', '^'):
for fill in ('', ' ', '0', '@'):
test_fmt('', fill, alignment, '', '', width, '', 'c', 48)
if str_tests:
for conv in ('', 'r', 's'):
for width in ('', '1', '4', '10'):
for alignment in ('', '<', '>', '^'):
for fill in ('', ' ', '0', '@'):
for str in ('', 'a', 'bcd', 'This is a test with a longer string'):
test_fmt(conv, fill, alignment, '', '', width, '', 's', str)
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/basics/string_format2.py
|
Python
|
apache-2.0
| 2,025
|
# tests for errors in {} format string
try:
'{0:0}'.format('zzz')
except (ValueError):
print('ValueError')
try:
'{1:}'.format(1)
except IndexError:
print('IndexError')
try:
'}'.format('zzzz')
except ValueError:
print('ValueError')
# end of format parsing conversion specifier
try:
'{!'.format('a')
except ValueError:
print('ValueError')
# unknown conversion specifier
try:
'abc{!d}'.format('1')
except ValueError:
print('ValueError')
try:
'{abc'.format('zzzz')
except ValueError:
print('ValueError')
# expected ':' after specifier
try:
'{!s :}'.format(2)
except ValueError:
print('ValueError')
try:
'{}{0}'.format(1, 2)
except ValueError:
print('ValueError')
try:
'{1:}'.format(1)
except IndexError:
print('IndexError')
try:
'{ 0 :*^10}'.format(12)
except KeyError:
print('KeyError')
try:
'{0}{}'.format(1)
except ValueError:
print('ValueError')
try:
'{}{}'.format(1)
except IndexError:
print('IndexError')
try:
'{0:+s}'.format('1')
except ValueError:
print('ValueError')
try:
'{0:+c}'.format(1)
except ValueError:
print('ValueError')
try:
'{0:s}'.format(1)
except ValueError:
print('ValueError')
try:
'{:*"1"}'.format('zz')
except ValueError:
print('ValueError')
# unknown format code for str arg
try:
'{:X}'.format('zz')
except ValueError:
print('ValueError')
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/basics/string_format_error.py
|
Python
|
apache-2.0
| 1,415
|
try:
'' % ()
except TypeError:
print("SKIP")
raise SystemExit
print("%%" % ())
print("=%s=" % 1)
print("=%s=%s=" % (1, 2))
print("=%s=" % (1,))
print("=%s=" % [1, 2])
print("=%s=" % "str")
print("=%r=" % "str")
try:
print("=%s=%s=" % 1)
except TypeError:
print("TypeError")
try:
print("=%s=%s=%s=" % (1, 2))
except TypeError:
print("TypeError")
try:
print("=%s=" % (1, 2))
except TypeError:
print("TypeError")
print("%s" % True)
print("%s" % 1)
print("%.1s" % "ab")
print("%r" % True)
print("%r" % 1)
print("%c" % 48)
print("%c" % 'a')
print("%10s" % 'abc')
print("%-10s" % 'abc')
print('%c' % False)
print('%c' % True)
# Should be able to print dicts; in this case they aren't used
# to lookup keywords in formats like %(foo)s
print('%s' % {})
print('%s' % ({},))
# Cases when "*" used and there's not enough values total
try:
print("%*s" % 5)
except TypeError:
print("TypeError")
try:
print("%*.*s" % (1, 15))
except TypeError:
print("TypeError")
print("%(foo)s" % {"foo": "bar", "baz": False})
print("%s %(foo)s %(foo)s" % {"foo": 1})
try:
print("%(foo)s" % {})
except KeyError:
print("KeyError")
# Using in "*" with dict got to fail
try:
print("%(foo)*s" % {"foo": "bar"})
except TypeError:
print("TypeError")
# When using %(foo)s format the single argument must be a dict
try:
'%(foo)s' % 1
except TypeError:
print('TypeError')
try:
'%(foo)s' % ({},)
except TypeError:
print('TypeError')
try:
'%(a' % {'a':1}
except ValueError:
print('ValueError')
try:
'%.*d %.*d' % (20, 5)
except TypeError:
print('TypeError')
try:
a = '%*' % 1
except (ValueError):
print('ValueError')
try:
'%c' % 'aa'
except TypeError:
print('TypeError')
try:
'%l' % 1
except ValueError:
print('ValueError')
try:
'a%' % 1
except ValueError:
print('ValueError')
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/basics/string_format_modulo.py
|
Python
|
apache-2.0
| 1,887
|
# test string modulo formatting with int values
try:
'' % ()
except TypeError:
print("SKIP")
raise SystemExit
# basic cases
print("%d" % 10)
print("%+d" % 10)
print("% d" % 10)
print("%d" % -10)
print("%d" % True)
print("%i" % -10)
print("%i" % True)
print("%u" % -10)
print("%u" % True)
print("%x" % 18)
print("%o" % 18)
print("%X" % 18)
print("%#x" % 18)
print("%#X" % 18)
print("%#6o" % 18)
print("%#6x" % 18)
print("%#06x" % 18)
# with *
print("%*d" % (5, 10))
print("%*.*d" % (2, 2, 20))
print("%*.*d" % (5, 8, 20))
# precision
for val in (-12, 12):
print(">%8.4d<" % val)
print(">% 8.4d<" % val)
print(">%+8.4d<" % val)
print(">%08.4d<" % val)
print(">%-8.4d<" % val)
print(">%-08.4d<" % val)
print(">%-+08.4d<" % val)
# test + option with various amount of padding
for pad in ('', ' ', '0'):
for n in (1, 2, 3):
for val in (-1, 0, 1):
print(('%+' + pad + str(n) + 'd') % val)
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/basics/string_format_modulo_int.py
|
Python
|
apache-2.0
| 952
|
def f():
return 4
def g(_):
return 5
def h():
return 6
print(f'no interpolation')
print(f"no interpolation")
print(f"""no interpolation""")
x, y = 1, 2
print(f'{x}')
print(f'{x:08x}')
print(f'a {x} b {y} c')
print(f'a {x:08x} b {y} c')
print(f'a {"hello"} b')
print(f'a {f() + g("foo") + h()} b')
def foo(a, b):
return f'{x}{y}{a}{b}'
print(foo(7, 8))
# PEP-0498 specifies that '\\' and '#' must be disallowed explicitly, whereas
# MicroPython relies on the syntax error as a result of the substitution.
print(f"\\")
print(f'#')
try:
eval("f'{\}'")
except SyntaxError:
print('SyntaxError')
try:
eval("f'{#}'")
except SyntaxError:
print('SyntaxError')
# PEP-0498 specifies that handling of double braces '{{' or '}}' should
# behave like str.format.
print(f'{{}}')
print(f'{{{4*10}}}', '{40}')
# A single closing brace, unlike str.format should raise a syntax error.
# MicroPython instead raises ValueError at runtime from the substitution.
try:
eval("f'{{}'")
except (ValueError, SyntaxError):
# MicroPython incorrectly raises ValueError here.
print('SyntaxError')
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/basics/string_fstring.py
|
Python
|
apache-2.0
| 1,118
|
# test f-string debug feature {x=}
def f():
return 4
def g(_):
return 5
def h():
return 6
x, y = 1, 2
print(f"{x=}")
print(f"{x=:08x}")
print(f"a {x=} b {y} c")
print(f"a {x=:08x} b {y} c")
print(f'a {f() + g("foo") + h()=} b')
print(f'a {f() + g("foo") + h()=:08x} b')
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/basics/string_fstring_debug.py
|
Python
|
apache-2.0
| 291
|
print("hello world".index("ll"))
print("hello world".index("ll", None))
print("hello world".index("ll", 1))
print("hello world".index("ll", 1, None))
print("hello world".index("ll", None, None))
print("hello world".index("ll", 1, -1))
try:
print("hello world".index("ll", 1, 1))
except ValueError:
print("Raised ValueError")
else:
print("Did not raise ValueError")
try:
print("hello world".index("ll", 1, 2))
except ValueError:
print("Raised ValueError")
else:
print("Did not raise ValueError")
try:
print("hello world".index("ll", 1, 3))
except ValueError:
print("Raised ValueError")
else:
print("Did not raise ValueError")
print("hello world".index("ll", 1, 4))
print("hello world".index("ll", 1, 5))
print("hello world".index("ll", -100))
print("0000".index('0'))
print("0000".index('0', 0))
print("0000".index('0', 1))
print("0000".index('0', 2))
print("0000".index('0', 3))
try:
print("0000".index('0', 4))
except ValueError:
print("Raised ValueError")
else:
print("Did not raise ValueError")
try:
print("0000".index('0', 5))
except ValueError:
print("Raised ValueError")
else:
print("Did not raise ValueError")
try:
print("0000".index('-1', 3))
except ValueError:
print("Raised ValueError")
else:
print("Did not raise ValueError")
try:
print("0000".index('1', 3))
except ValueError:
print("Raised ValueError")
else:
print("Did not raise ValueError")
try:
print("0000".index('1', 4))
except ValueError:
print("Raised ValueError")
else:
print("Did not raise ValueError")
try:
print("0000".index('1', 5))
except ValueError:
print("Raised ValueError")
else:
print("Did not raise ValueError")
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/basics/string_index.py
|
Python
|
apache-2.0
| 1,712
|
print("".isspace())
print(" \t\n\r\v\f".isspace())
print("a".isspace())
print(" \t\n\r\v\fa".isspace())
print("".isalpha())
print("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ".isalpha())
print("0abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ".isalpha())
print("this ".isalpha())
print("".isdigit())
print("0123456789".isdigit())
print("0123456789a".isdigit())
print("0123456789 ".isdigit())
print("".isupper())
print("CHEESE-CAKE WITH ... _FROSTING_*99".isupper())
print("aB".isupper())
print("".islower())
print("cheese-cake with ... _frosting_*99".islower())
print("aB".islower())
print("123".islower())
print("123a".islower())
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/basics/string_istest.py
|
Python
|
apache-2.0
| 645
|
print(','.join(()))
print(','.join(('a',)))
print(','.join(('a', 'b')))
print(','.join([]))
print(','.join(['a']))
print(','.join(['a', 'b']))
print(''.join(''))
print(''.join('abc'))
print(','.join('abc'))
print(','.join('abc' for i in range(5)))
print(b','.join([b'abc', b'123']))
try:
''.join(None)
except TypeError:
print("TypeError")
try:
print(b','.join(['abc', b'123']))
except TypeError:
print("TypeError")
try:
print(','.join([b'abc', b'123']))
except TypeError:
print("TypeError")
# joined by the compiler
print("a" "b")
print("a" '''b''')
print("a" # inline comment
"b")
print("a" \
"b")
# the following should not be joined by the compiler
x = 'a'
'b'
print(x)
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/basics/string_join.py
|
Python
|
apache-2.0
| 713
|
s1 = "long string long string long string long string long string long string long string long string long string long string long string long string long string long string long string long string long string long string long string long string long string long string long string long string long string long string long string long string long string long string long string long string long string long string long string long string long string long string long string long string long string"
s2 = "concatenated string" "concatenated string" "concatenated string" "concatenated string" "concatenated string" "concatenated string" "concatenated string" "concatenated string" "concatenated string" "concatenated string" "concatenated string" "concatenated string" "concatenated string" "concatenated string" "concatenated string" "concatenated string"
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/basics/string_large.py
|
Python
|
apache-2.0
| 856
|
# basic multiplication
print('0' * 5)
# check negative, 0, positive; lhs and rhs multiplication
for i in (-4, -2, 0, 2, 4):
print(i * '12')
print('12' * i)
# check that we don't modify existing object
a = '123'
c = a * 3
print(a, c)
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/basics/string_mult.py
|
Python
|
apache-2.0
| 243
|
try:
str.partition
except AttributeError:
print("SKIP")
raise SystemExit
print("asdf".partition('g'))
print("asdf".partition('a'))
print("asdf".partition('s'))
print("asdf".partition('f'))
print("asdf".partition('d'))
print("asdf".partition('asd'))
print("asdf".partition('sdf'))
print("asdf".partition('as'))
print("asdf".partition('df'))
print("asdf".partition('asdf'))
print("asdf".partition('asdfa'))
print("asdf".partition('fasdf'))
print("asdf".partition('fasdfa'))
print("abba".partition('a'))
print("abba".partition('b'))
try:
print("asdf".partition(1))
except TypeError:
print("Raised TypeError")
else:
print("Did not raise TypeError")
try:
print("asdf".partition(''))
except ValueError:
print("Raised ValueError")
else:
print("Did not raise ValueError")
# Bytes
print(b"abba".partition(b'b'))
try:
print(b"abba".partition('b'))
except TypeError:
print("Raised TypeError")
try:
print("abba".partition(b'b'))
except TypeError:
print("Raised TypeError")
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/basics/string_partition.py
|
Python
|
apache-2.0
| 1,017
|
print("".replace("a", "b"))
print("aaa".replace("b", "c"))
print("aaa".replace("a", "b", 0))
print("aaa".replace("a", "b", -5))
print("asdfasdf".replace("a", "b"))
print("aabbaabbaabbaa".replace("aa", "cc", 3))
print("a".replace("aa", "bb"))
print("testingtesting".replace("ing", ""))
print("testINGtesting".replace("ing", "ING!"))
print("".replace("", "1"))
print("A".replace("", "1"))
print("AB".replace("", "1"))
print("AB".replace("", "12"))
try:
'abc'.replace(1, 2)
except TypeError:
print('TypeError')
try:
'abc'.replace('1', 2)
except TypeError:
print('TypeError')
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/basics/string_replace.py
|
Python
|
apache-2.0
| 591
|
# anything above 0xa0 is printed as Unicode by CPython
# the abobe is CPython implementation detail, stick to ASCII
for c in range(0x80):
print("0x{:02x}: {}".format(c, repr(chr(c))))
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/basics/string_repr.py
|
Python
|
apache-2.0
| 188
|
print("hello world".rfind("ll"))
print("hello world".rfind("ll", None))
print("hello world".rfind("ll", 1))
print("hello world".rfind("ll", 1, None))
print("hello world".rfind("ll", None, None))
print("hello world".rfind("ll", 1, -1))
print("hello world".rfind("ll", 1, 1))
print("hello world".rfind("ll", 1, 2))
print("hello world".rfind("ll", 1, 3))
print("hello world".rfind("ll", 1, 4))
print("hello world".rfind("ll", 1, 5))
print("hello world".rfind("ll", -100))
print("0000".rfind('0'))
print("0000".rfind('0', 0))
print("0000".rfind('0', 1))
print("0000".rfind('0', 2))
print("0000".rfind('0', 3))
print("0000".rfind('0', 4))
print("0000".rfind('0', 5))
print("0000".rfind('-1', 3))
print("0000".rfind('1', 3))
print("0000".rfind('1', 4))
print("0000".rfind('1', 5))
print("aaaaaaaaaaa".rfind("bbb", 9, 2))
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/basics/string_rfind.py
|
Python
|
apache-2.0
| 815
|
print("hello world".rindex("ll"))
print("hello world".rindex("ll", None))
print("hello world".rindex("ll", 1))
print("hello world".rindex("ll", 1, None))
print("hello world".rindex("ll", None, None))
print("hello world".rindex("ll", 1, -1))
try:
print("hello world".rindex("ll", 1, 1))
except ValueError:
print("Raised ValueError")
else:
print("Did not raise ValueError")
try:
print("hello world".rindex("ll", 1, 2))
except ValueError:
print("Raised ValueError")
else:
print("Did not raise ValueError")
try:
print("hello world".rindex("ll", 1, 3))
except ValueError:
print("Raised ValueError")
else:
print("Did not raise ValueError")
print("hello world".rindex("ll", 1, 4))
print("hello world".rindex("ll", 1, 5))
print("hello world".rindex("ll", -100))
print("0000".rindex('0'))
print("0000".rindex('0', 0))
print("0000".rindex('0', 1))
print("0000".rindex('0', 2))
print("0000".rindex('0', 3))
try:
print("0000".rindex('0', 4))
except ValueError:
print("Raised ValueError")
else:
print("Did not raise ValueError")
try:
print("0000".rindex('0', 5))
except ValueError:
print("Raised ValueError")
else:
print("Did not raise ValueError")
try:
print("0000".rindex('-1', 3))
except ValueError:
print("Raised ValueError")
else:
print("Did not raise ValueError")
try:
print("0000".rindex('1', 3))
except ValueError:
print("Raised ValueError")
else:
print("Did not raise ValueError")
try:
print("0000".rindex('1', 4))
except ValueError:
print("Raised ValueError")
else:
print("Did not raise ValueError")
try:
print("0000".rindex('1', 5))
except ValueError:
print("Raised ValueError")
else:
print("Did not raise ValueError")
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/basics/string_rindex.py
|
Python
|
apache-2.0
| 1,735
|
try:
str.partition
except AttributeError:
print("SKIP")
raise SystemExit
print("asdf".rpartition('g'))
print("asdf".rpartition('a'))
print("asdf".rpartition('s'))
print("asdf".rpartition('f'))
print("asdf".rpartition('d'))
print("asdf".rpartition('asd'))
print("asdf".rpartition('sdf'))
print("asdf".rpartition('as'))
print("asdf".rpartition('df'))
print("asdf".rpartition('asdf'))
print("asdf".rpartition('asdfa'))
print("asdf".rpartition('fasdf'))
print("asdf".rpartition('fasdfa'))
print("abba".rpartition('a'))
print("abba".rpartition('b'))
try:
print("asdf".rpartition(1))
except TypeError:
print("Raised TypeError")
else:
print("Did not raise TypeError")
try:
print("asdf".rpartition(''))
except ValueError:
print("Raised ValueError")
else:
print("Did not raise ValueError")
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/basics/string_rpartition.py
|
Python
|
apache-2.0
| 820
|
# default separator (whitespace)
print("a b".rsplit())
#print(" a b ".rsplit(None))
#print(" a b ".rsplit(None, 1))
#print(" a b ".rsplit(None, 2))
#print(" a b c ".rsplit(None, 1))
#print(" a b c ".rsplit(None, 0))
#print(" a b c ".rsplit(None, -1))
# empty separator should fail (this actually delegates to .split())
try:
"abc".rsplit('')
except ValueError:
print("ValueError")
# empty separator should fail (error handled in .rsplit())
try:
'a a a a'.rsplit('', 5)
except ValueError:
print('ValueError')
# bad separator type
try:
'a a a a'.rsplit(1)
except TypeError:
print('TypeError')
# non-empty separator
print("abc".rsplit("a"))
print("abc".rsplit("b"))
print("abc".rsplit("c"))
print("abc".rsplit("z"))
print("abc".rsplit("ab"))
print("abc".rsplit("bc"))
print("abc".rsplit("abc"))
print("abc".rsplit("abcd"))
print("abcabc".rsplit("bc"))
print("abcabc".rsplit("bc", 0))
print("abcabc".rsplit("bc", 1))
print("abcabc".rsplit("bc", 2))
print("10/11/12".rsplit("/", 1))
print("10/11/12".rsplit("/", 2))
print("10/11/12".rsplit("/", 3))
print("10/11/12".rsplit("/", 4))
print("10/11/12".rsplit("/", 5))
print("/*10/*11/*12/*".rsplit("/*", 1))
print("/*10/*11/*12/*".rsplit("/*", 2))
print("/*10/*11/*12/*".rsplit("/*", 3))
print("/*10/*11/*12/*".rsplit("/*", 4))
print("/*10/*11/*12/*".rsplit("/*", 5))
print(b"abcabc".rsplit(b"bc", 2))
# negative "maxsplit" should delegate to .split()
print('abaca'.rsplit('a', -1))
print('abaca'.rsplit('a', -2))
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/basics/string_rsplit.py
|
Python
|
apache-2.0
| 1,526
|
print("123"[0:1])
print("123"[0:2])
print("123"[:1])
print("123"[1:])
# Idiom for copying sequence
print("123"[:])
print("123"[:-1])
# Weird cases
print("123"[0:0])
print("123"[1:0])
print("123"[1:1])
print("123"[-1:-1])
print("123"[-3:])
print("123"[-3:3])
print("123"[0:])
print("123"[:0])
print("123"[:-3])
print("123"[:-4])
# Range check testing, don't segfault, please ;-)
print("123"[:1000000])
print("123"[1000000:])
print("123"[:-1000000])
print("123"[-1000000:])
# No IndexError!
print(""[1:1])
print(""[-1:-1])
# bytes
print(b"123"[0:2])
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/basics/string_slice.py
|
Python
|
apache-2.0
| 555
|
# default separator (whitespace)
print("a b".split())
print(" a b ".split(None))
print(" a b ".split(None, 1))
print(" a b ".split(None, 2))
print(" a b c ".split(None, 1))
print(" a b c ".split(None, 0))
print(" a b c ".split(None, -1))
print("foo\n\t\x07\v\nbar".split())
print("foo\nbar\n".split())
# empty separator should fail
try:
"abc".split('')
except ValueError:
print("ValueError")
# non-empty separator
print("abc".split("a"))
print("abc".split("b"))
print("abc".split("c"))
print("abc".split("z"))
print("abc".split("ab"))
print("abc".split("bc"))
print("abc".split("abc"))
print("abc".split("abcd"))
print("abcabc".split("bc"))
print("abcabc".split("bc", 0))
print("abcabc".split("bc", 1))
print("abcabc".split("bc", 2))
print(b"abcabc".split(b"bc", 2))
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/basics/string_split.py
|
Python
|
apache-2.0
| 817
|
# test string.splitlines() method
try:
str.splitlines
except:
print("SKIP")
raise SystemExit
# test \n as newline
print("foo\nbar".splitlines())
print("foo\nbar\n".splitlines())
print("foo and\nbar\n".splitlines())
print("foo\nbar\n\n".splitlines())
print("foo\n\nbar\n\n".splitlines())
print("\nfoo\nbar\n".splitlines())
# test \r as newline
print("foo\rbar\r".splitlines())
print("\rfoo and\r\rbar\r".splitlines())
# test \r\n as newline
print("foo\r\nbar\r\n".splitlines())
print("\r\nfoo and\r\n\r\nbar\r\n".splitlines())
# test keepends arg
print("foo\nbar".splitlines(True))
print("foo\nbar\n".splitlines(True))
print("foo\nbar\n\n".splitlines(True))
print("foo\rbar".splitlines(keepends=True))
print("foo\rbar\r\r".splitlines(keepends=True))
print("foo\r\nbar".splitlines(keepends=True))
print("foo\r\nbar\r\n\r\n".splitlines(keepends=True))
# test splitting bytes objects
print(b"foo\nbar".splitlines())
print(b"foo\nbar\n".splitlines())
print(b"foo\r\nbar\r\n\r\n".splitlines(True))
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/basics/string_splitlines.py
|
Python
|
apache-2.0
| 1,010
|
print("foobar".startswith("foo"))
print("foobar".startswith("Foo"))
print("foobar".startswith("foo1"))
print("foobar".startswith("foobar"))
print("foobar".startswith(""))
print("1foobar".startswith("foo", 1))
print("1foo".startswith("foo", 1))
print("1foo".startswith("1foo", 1))
print("1fo".startswith("foo", 1))
print("1fo".startswith("foo", 10))
try:
"foobar".startswith(1)
except TypeError:
print("TypeError")
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/basics/string_startswith.py
|
Python
|
apache-2.0
| 424
|
# MicroPython doesn't support tuple argument
try:
"foobar".startswith(("foo", "sth"))
except TypeError:
print("TypeError")
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/basics/string_startswith_upy.py
|
Python
|
apache-2.0
| 132
|
print("".strip())
print(" \t\n\r\v\f".strip())
print(" T E S T".strip())
print("abcabc".strip("ce"))
print("aaa".strip("b"))
print("abc efg ".strip("g a"))
print(' spacious '.lstrip())
print('www.example.com'.lstrip('cmowz.'))
print(' spacious '.rstrip())
print('mississippi'.rstrip('ipz'))
print(b'mississippi'.rstrip(b'ipz'))
try:
print(b'mississippi'.rstrip('ipz'))
except TypeError:
print("TypeError")
try:
print('mississippi'.rstrip(b'ipz'))
except TypeError:
print("TypeError")
# single-char subj string used to give a problem
print("a".strip())
print("a".lstrip())
print("a".rstrip())
print(" a".strip())
print(" a".lstrip())
print(" a".rstrip())
print("a ".strip())
print("a ".lstrip())
print("a ".rstrip())
# \0 used to give a problem
print("\0abc\0".strip())
print("\0abc\0".lstrip())
print("\0abc\0".rstrip())
print("\0abc\0".strip("\0"))
# Test that stripping unstrippable string returns original object
s = "abc"
print(id(s.strip()) == id(s))
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/basics/string_strip.py
|
Python
|
apache-2.0
| 988
|
print("".lower())
print(" t\tn\nr\rv\vf\f".upper())
print(" T E S T".lower())
print("*@a1b2cabc_[]/\\".upper())
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/basics/string_upperlow.py
|
Python
|
apache-2.0
| 112
|
try:
import ustruct as struct
except:
try:
import struct
except ImportError:
print("SKIP")
raise SystemExit
print(struct.calcsize("<bI"))
print(struct.unpack("<bI", b"\x80\0\0\x01\0"))
print(struct.calcsize(">bI"))
print(struct.unpack(">bI", b"\x80\0\0\x01\0"))
# 32-bit little-endian specific
#print(struct.unpack("bI", b"\x80\xaa\x55\xaa\0\0\x01\0"))
print(struct.pack("<l", 1))
print(struct.pack(">l", 1))
print(struct.pack("<i", 1))
print(struct.pack(">i", 1))
print(struct.pack("<h", 1))
print(struct.pack(">h", 1))
print(struct.pack("<b", 1))
print(struct.pack(">b", 1))
print(struct.pack("<bI", -128, 256))
print(struct.pack(">bI", -128, 256))
print(struct.calcsize("100sI"))
print(struct.calcsize("97sI"))
print(struct.unpack("<6sH", b"foo\0\0\0\x12\x34"))
print(struct.pack("<6sH", b"foo", 10000))
s = struct.pack("BHBI", 10, 100, 200, 300)
v = struct.unpack("BHBI", s)
print(v == (10, 100, 200, 300))
# network byte order
print(struct.pack('!i', 123))
# check that we get an error if the buffer is too small
try:
struct.unpack('I', b'\x00\x00\x00')
except:
print('struct.error')
# first arg must be a string
try:
struct.pack(1, 2)
except TypeError:
print('TypeError')
# make sure that unknown types are detected
try:
struct.pack("z", 1)
except:
print("Unknown type")
# Initially repitition counters were supported only for strings,
# but later were implemented for all.
print(struct.unpack("<3B2h", b"foo\x12\x34\xff\xff"))
print(struct.pack("<3B", 1, 2, 3))
# pack_into
buf = bytearray(b'>>>123<<<')
struct.pack_into('<bbb', buf, 3, 0x41, 0x42, 0x43)
print(buf)
struct.pack_into('<bbb', buf, -6, 0x44, 0x45, 0x46)
print(buf)
# check that we get an error if the buffer is too small
try:
struct.pack_into('I', bytearray(1), 0, 0)
except:
print('struct.error')
try:
struct.pack_into('<bbb', buf, 7, 0x41, 0x42, 0x43)
except:
print('struct.error')
try:
struct.pack_into('<bbb', buf, -10, 0x41, 0x42, 0x43)
except:
print('struct.error')
# unpack_from
buf = b'0123456789'
print(struct.unpack_from('<b', buf, 4))
print(struct.unpack_from('<b', buf, -4))
try:
print(struct.unpack_from('<b', buf, 10))
except:
print('struct.error')
try:
print(struct.unpack_from('<b', buf, -11))
except:
print('struct.error')
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/basics/struct1.py
|
Python
|
apache-2.0
| 2,326
|
try:
import ustruct as struct
except:
try:
import struct
except ImportError:
print("SKIP")
raise SystemExit
# check maximum pack on 32-bit machine
print(struct.pack("<I", 2**32 - 1))
print(struct.pack("<I", 0xffffffff))
# long long ints
print(struct.pack("<Q", 1))
print(struct.pack(">Q", 1))
print(struct.pack("<Q", 2**64 - 1))
print(struct.pack(">Q", 2**64 - 1))
print(struct.pack("<Q", 0xffffffffffffffff))
print(struct.pack(">Q", 0xffffffffffffffff))
print(struct.pack("<q", -1))
print(struct.pack(">q", -1))
print(struct.pack("<Q", 1234567890123456789))
print(struct.pack("<q", -1234567890123456789))
print(struct.pack(">Q", 1234567890123456789))
print(struct.pack(">q", -1234567890123456789))
print(struct.unpack("<Q", b"\x12\x34\x56\x78\x90\x12\x34\x56"))
print(struct.unpack(">Q", b"\x12\x34\x56\x78\x90\x12\x34\x56"))
print(struct.unpack("<q", b"\x12\x34\x56\x78\x90\x12\x34\xf6"))
print(struct.unpack(">q", b"\xf2\x34\x56\x78\x90\x12\x34\x56"))
# check maximum unpack
print(struct.unpack("<I", b"\xff\xff\xff\xff"))
print(struct.unpack("<Q", b"\xff\xff\xff\xff\xff\xff\xff\xff"))
# check small int overflow
print(struct.unpack("<i", b'\xff\xff\xff\x7f'))
print(struct.unpack("<q", b'\xff\xff\xff\xff\xff\xff\xff\x7f'))
# test with negative big integers that are actually small in magnitude
bigzero = (1 << 70) - (1 << 70)
for endian in "<>":
for type_ in "bhiq":
fmt = endian + type_
b = struct.pack(fmt, -2 + bigzero)
print(fmt, b, struct.unpack(fmt, b))
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/basics/struct1_intbig.py
|
Python
|
apache-2.0
| 1,535
|
# test ustruct with a count specified before the type
try:
import ustruct as struct
except:
try:
import struct
except ImportError:
print("SKIP")
raise SystemExit
print(struct.calcsize('0s'))
print(struct.unpack('0s', b''))
print(struct.pack('0s', b'123'))
print(struct.calcsize('2s'))
print(struct.unpack('2s', b'12'))
print(struct.pack('2s', b'123'))
print(struct.calcsize('2H'))
print(struct.unpack('<2H', b'1234'))
print(struct.pack('<2H', 258, 515))
print(struct.calcsize('0s1s0H2H'))
print(struct.unpack('<0s1s0H2H', b'01234'))
print(struct.pack('<0s1s0H2H', b'abc', b'abc', 258, 515))
# check that we get an error if the buffer is too small
try:
struct.unpack('2H', b'\x00\x00')
except:
print('Exception')
try:
struct.pack_into('2I', bytearray(4), 0, 0)
except:
print('Exception')
# check that unknown types raise an exception
try:
struct.unpack('z', b'1')
except:
print('Exception')
try:
struct.pack('z', (b'1',))
except:
print('Exception')
try:
struct.calcsize('0z')
except:
print('Exception')
# check that a count without a type specifier raises an exception
try:
struct.calcsize('1')
except:
print('Exception')
try:
struct.pack('1')
except:
print('Exception')
try:
struct.pack_into('1', bytearray(4), 0, 'xx')
except:
print('Exception')
try:
struct.unpack('1', 'xx')
except:
print('Exception')
try:
struct.unpack_from('1', 'xx')
except:
print('Exception')
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/basics/struct2.py
|
Python
|
apache-2.0
| 1,497
|
# test ustruct and endian specific things
try:
import ustruct as struct
except:
try:
import struct
except ImportError:
print("SKIP")
raise SystemExit
# unpack/unpack_from with unaligned native type
buf = b'0123456789'
print(struct.unpack('h', memoryview(buf)[1:3]))
print(struct.unpack_from('i', buf, 1))
print(struct.unpack_from('@i', buf, 1))
print(struct.unpack_from('@ii', buf, 1))
# pack_into with unaligned native type
buf = bytearray(b'>----<<<<<<<')
struct.pack_into('i', buf, 1, 0x30313233)
print(buf)
struct.pack_into('@ii', buf, 3, 0x34353637, 0x41424344)
print(buf)
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/basics/struct_endian.py
|
Python
|
apache-2.0
| 617
|
# test MicroPython-specific features of struct
try:
import ustruct as struct
except:
try:
import struct
except ImportError:
print("SKIP")
raise SystemExit
class A():
pass
# pack and unpack objects
o = A()
s = struct.pack("<O", o)
o2 = struct.unpack("<O", s)
print(o is o2[0])
# pack can accept less arguments than required for the format spec
print(struct.pack('<2I', 1))
# pack and unpack pointer to a string
# This requires uctypes to get the address of the string and instead of
# putting this in a dedicated test that can be skipped we simply pass
# if the import fails.
try:
import uctypes
o = uctypes.addressof('abc')
s = struct.pack("<S", o)
o2 = struct.unpack("<S", s)
assert o2[0] == 'abc'
except ImportError:
pass
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/basics/struct_micropython.py
|
Python
|
apache-2.0
| 793
|
# Calling an inherited classmethod
class Base:
@classmethod
def foo(cls):
print(cls.__name__)
try:
Base.__name__
except AttributeError:
print("SKIP")
raise SystemExit
class Sub(Base):
pass
Sub.foo()
# overriding a member and accessing it via a classmethod
class A(object):
foo = 0
@classmethod
def bar(cls):
print(cls.foo)
def baz(self):
print(self.foo)
class B(A):
foo = 1
B.bar() # class calling classmethod
B().bar() # instance calling classmethod
B().baz() # instance calling normal method
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/basics/subclass_classmethod.py
|
Python
|
apache-2.0
| 573
|
class mylist(list):
pass
a = mylist([1, 2, 5])
# Test setting instance attr
a.attr = "something"
# Test base type __str__
print(a)
# Test getting instance attr
print(a.attr)
# Test base type ->subscr
print(a[-1])
a[0] = -1
print(a)
# Test another base type unary op
print(len(a))
# Test binary op of base type, with 2nd arg being raw base type
print(a + [20, 30, 40])
# Test binary op of base type, with 2nd arg being same class as 1st arg
# TODO: Faults
#print(a + a)
def foo():
print("hello from foo")
try:
class myfunc(type(foo)):
pass
except TypeError:
print("TypeError")
# multiple bases with layout conflict
try:
class A(type, tuple):
None
except TypeError:
print('TypeError')
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/basics/subclass_native1.py
|
Python
|
apache-2.0
| 728
|
class Base1:
def __init__(self, *args):
print("Base1.__init__", args)
class Clist1(Base1, list):
pass
a = Clist1()
print(len(a))
# Not compliant - list assignment should happen in list.__init__, which is not called
# because there's Base1.__init__, but we assign in list.__new__
#a = Clist1([1, 2, 3])
#print(len(a))
print("---")
class Clist2(list, Base1):
pass
# Not compliant - should call list.__init__, but we don't have it
#a = Clist2()
#print(len(a))
# Not compliant - should call list.__init__, but we don't have it
#a = Clist2([1, 2, 3])
#print(len(a))
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/basics/subclass_native2_list.py
|
Python
|
apache-2.0
| 587
|
class Base1:
def __init__(self, *args):
print("Base1.__init__", args)
class Ctuple1(Base1, tuple):
pass
a = Ctuple1()
print(len(a))
a = Ctuple1([1, 2, 3])
print(len(a))
print("---")
class Ctuple2(tuple, Base1):
pass
a = Ctuple2()
print(len(a))
a = Ctuple2([1, 2, 3])
print(len(a))
a = tuple([1,2,3])
b = Ctuple1([1,2,3])
c = Ctuple2([1,2,3])
print(a == b)
print(b == c)
print(c == a)
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/basics/subclass_native2_tuple.py
|
Python
|
apache-2.0
| 411
|
# test subclassing a native exception
class MyExc(Exception):
pass
e = MyExc(100, "Some error")
print(e)
print(repr(e))
print(e.args)
try:
raise MyExc("Some error", 1)
except MyExc as e:
print("Caught exception:", repr(e))
try:
raise MyExc("Some error2", 2)
except Exception as e:
print("Caught exception:", repr(e))
try:
raise MyExc("Some error2")
except:
print("Caught user exception")
class MyStopIteration(StopIteration):
pass
print(MyStopIteration().value)
print(MyStopIteration(1).value)
class Iter:
def __iter__(self):
return self
def __next__(self):
# This exception will stop the "yield from", with a value of 3
raise MyStopIteration(3)
def gen():
print((yield from Iter()))
return 4
try:
next(gen())
except StopIteration as er:
print(er.args)
class MyOSError(OSError):
pass
print(MyOSError().errno)
print(MyOSError(1, "msg").errno)
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/basics/subclass_native3.py
|
Python
|
apache-2.0
| 948
|
# Test calling non-special method inherited from native type
class mylist(list):
pass
l = mylist([1, 2, 3])
print(l)
l.append(10)
print(l)
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/basics/subclass_native4.py
|
Python
|
apache-2.0
| 145
|
# Subclass from 2 bases explicitly subclasses from object
class Base1(object):
pass
class Base2(object):
pass
class Sub(Base1, Base2):
pass
o = Sub()
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/basics/subclass_native5.py
|
Python
|
apache-2.0
| 166
|
# test when we subclass a type with the buffer protocol
class my_bytes(bytes):
pass
b1 = my_bytes([0, 1])
b2 = my_bytes([2, 3])
b3 = bytes([4, 5])
# addition will use the buffer protocol on the RHS
print(b1 + b2)
print(b1 + b3)
print(b3 + b1)
# bytes construction will use the buffer protocol
print(bytes(b1))
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/basics/subclass_native_buffer.py
|
Python
|
apache-2.0
| 318
|
# test calling a subclass of a native class that supports calling
# For this test we need a native class that can be subclassed (has make_new)
# and is callable (has call). The only one available is machine.Signal, which
# in turns needs PinBase.
try:
try:
import umachine as machine
except ImportError:
import machine
machine.PinBase
machine.Signal
except:
print("SKIP")
raise SystemExit
class Pin(machine.PinBase):
#def __init__(self):
# self.v = 0
def value(self, v=None):
return 42
class MySignal(machine.Signal):
pass
s = MySignal(Pin())
# apply call to the subclass, which should call the native base
print(s())
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/basics/subclass_native_call.py
|
Python
|
apache-2.0
| 692
|
# Test calling non-special method inherited from native type
class mytuple(tuple):
pass
t = mytuple((1, 2, 3))
print(t)
print(t == (1, 2, 3))
print((1, 2, 3) == t)
print(t < (1, 2, 3), t < (1, 2, 4))
print((1, 2, 3) <= t, (1, 2, 4) < t)
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/basics/subclass_native_cmp.py
|
Python
|
apache-2.0
| 244
|
# test containment operator on subclass of a native type
class mylist(list):
pass
class mydict(dict):
pass
class mybytes(bytes):
pass
l = mylist([1, 2, 3])
print(0 in l)
print(1 in l)
d = mydict({1:1, 2:2})
print(0 in l)
print(1 in l)
b = mybytes(b'1234')
print(0 in b)
print(b'1' in b)
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/basics/subclass_native_containment.py
|
Python
|
apache-2.0
| 305
|
# test subclassing a native type and overriding __init__
# overriding list.__init__()
class L(list):
def __init__(self, a, b):
super().__init__([a, b])
print(L(2, 3))
# inherits implicitly from object
class A:
def __init__(self):
print("A.__init__")
super().__init__()
A()
# inherits explicitly from object
class B(object):
def __init__(self):
print("B.__init__")
super().__init__()
B()
# multiple inheritance with object explicitly mentioned
class C:
pass
class D(C, object):
def __init__(self):
print('D.__init__')
super().__init__()
def reinit(self):
print('D.foo')
super().__init__()
a = D()
a.__init__()
a.reinit()
# call __init__() after object is already init'd
class L(list):
def reinit(self):
super().__init__(range(2))
a = L(range(5))
print(a)
a.reinit()
print(a)
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/basics/subclass_native_init.py
|
Python
|
apache-2.0
| 887
|
# test subclassing a native type which can be iterated over
class mymap(map):
pass
m = mymap(lambda x: x + 10, range(4))
print(list(m))
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/basics/subclass_native_iter.py
|
Python
|
apache-2.0
| 142
|