99_builtin_func.py 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956
  1. # test super:
  2. class TestSuperBase():
  3. def __init__(self):
  4. self.base_attr = 1
  5. def base_method(self):
  6. return self.base_attr
  7. def error(self):
  8. raise Exception('未能拦截错误')
  9. class TestSuperChild1(TestSuperBase):
  10. def __init__(self):
  11. super(TestSuperChild1, self).__init__()
  12. def child_method(self):
  13. return super(TestSuperChild1, self).base_method()
  14. def error_handling(self):
  15. try:
  16. super(TestSuperChild1, self).error()
  17. except:
  18. pass
  19. class TestSuperChild2(TestSuperBase):
  20. pass
  21. test_base = TestSuperBase()
  22. # 测试属性
  23. assert test_base.base_attr == 1
  24. # 测试方法
  25. assert test_base.base_method() == 1
  26. test_child1 = TestSuperChild1()
  27. # 测试继承的属性
  28. assert test_child1.base_attr == 1
  29. # 测试继承的方法
  30. assert test_child1.base_method() == 1
  31. # 测试子类添加的方法
  32. assert test_child1.child_method() == 1
  33. # 测试子类的错误拦截
  34. test_child1.error_handling()
  35. test_child2 = TestSuperChild2()
  36. # 测试继承的属性
  37. assert test_child2.base_attr == 1
  38. # 测试继承的方法
  39. assert test_child2.base_method() == 1
  40. class TestSuperNoBaseMethod(TestSuperBase):
  41. def __init__(self):
  42. super(TestSuperNoBaseMethod, self).append(1)
  43. try:
  44. t = TestSuperNoParent()
  45. print('未能拦截错误')
  46. exit(1)
  47. except:
  48. pass
  49. try:
  50. t = TestSuperNoBaseMethod()
  51. print('未能拦截错误')
  52. exit(1)
  53. except:
  54. pass
  55. class B():
  56. pass
  57. class C():
  58. def method(self):
  59. super(C, self).method()
  60. class D():
  61. def method(self):
  62. super(B, self).method()
  63. try:
  64. c = C()
  65. c.method()
  66. print('未能拦截错误')
  67. exit(1)
  68. except:
  69. pass
  70. try:
  71. d = D()
  72. d.method()
  73. print('未能拦截错误')
  74. exit(1)
  75. except:
  76. pass
  77. class A():
  78. def __init__(self):
  79. self.a = 1
  80. @staticmethod
  81. def static_method(txt):
  82. return txt
  83. # @classmethod
  84. # def class_method(cls, txt):
  85. # return cls.__name__ + txt
  86. assert A.static_method(123) == 123
  87. # assert A.class_method(123) == 'A123'
  88. # 无法测试 -----------------------------------------------
  89. # 248: 192: _vm->bind_builtin_func<1>("__import__", [](VM* vm, ArgsView args) {
  90. # 67: 193: const Str& name = CAST(Str&, args[0]);
  91. # 67: 194: auto dot = name.sv().find_last_of(".");
  92. # 67: 195: if(dot != std::string_view::npos){
  93. # #####: 196: auto ext = name.sv().substr(dot);
  94. # #####: 197: if(ext == ".so" || ext == ".dll" || ext == ".dylib"){
  95. # #####: 198: dylib_entry_t entry = load_dylib(name.c_str());
  96. # #####: 199: if(!entry){
  97. # #####: 200: vm->_error("ImportError", "cannot load dynamic library: " + name.escape());
  98. # #####: 201: }
  99. # #####: 202: vm->_c.s_view.push(ArgsView(vm->s_data.end(), vm->s_data.end()));
  100. # #####: 203: const char* name = entry(vm, PK_VERSION);
  101. # #####: 204: vm->_c.s_view.pop();
  102. # #####: 205: if(name == nullptr){
  103. # #####: 206: vm->_error("ImportError", "module initialization failed: " + Str(name).escape());
  104. # #####: 207: }
  105. # #####: 208: return vm->_modules[name];
  106. # #####: 209: }
  107. # #####: 210: }
  108. # 67: 211: return vm->py_import(name);
  109. # 67: 212: });
  110. # test hash:
  111. # 测试整数类型的输入
  112. assert hash(0) == 0
  113. assert hash(123) == 123
  114. assert hash(-456) == -456
  115. # 测试字符串类型的输入
  116. assert type(hash("hello")) is int
  117. # 测试浮点数类型的输入
  118. assert type(hash(3.14)) is int
  119. assert type(hash(-2.71828)) is int
  120. # 测试边界情况
  121. assert type(hash(None)) is int
  122. assert hash(True) == 1
  123. assert hash(False) == 0
  124. # 测试元组
  125. assert type(hash((4, 5, 6, (1234,1122), 2.3983, 'abcd'))) is int
  126. # 测试自定义类和对象的输入
  127. class A():
  128. pass
  129. a = A()
  130. assert type(hash(A)) is int
  131. assert type(hash(a)) is int
  132. # 测试函数的输入
  133. def f():
  134. pass
  135. assert type(hash(a)) is int
  136. # 测试不可哈希对象
  137. try:
  138. hash({1:1})
  139. print('未能拦截错误')
  140. exit(1)
  141. except:
  142. pass
  143. try:
  144. hash([1])
  145. print('未能拦截错误')
  146. exit(1)
  147. except:
  148. pass
  149. # -----------------------------------------------
  150. # 114: 259: _vm->bind_builtin_func<1>("chr", [](VM* vm, ArgsView args) {
  151. # #####: 260: i64 i = CAST(i64, args[0]);
  152. # #####: 261: if (i < 0 || i > 128) vm->ValueError("chr() arg not in range(128)");
  153. # #####: 262: return VAR(std::string(1, (char)i));
  154. # #####: 263: });
  155. # test chr
  156. l = []
  157. for i in range(128):
  158. l.append(f'{i} {chr(i)}')
  159. assert l == ['0 \x00', '1 \x01', '2 \x02', '3 \x03', '4 \x04', '5 \x05', '6 \x06', '7 \x07', '8 \x08', '9 \t', '10 \n', '11 \x0b', '12 \x0c', '13 \r', '14 \x0e', '15 \x0f', '16 \x10', '17 \x11', '18 \x12', '19 \x13', '20 \x14', '21 \x15', '22 \x16', '23 \x17', '24 \x18', '25 \x19', '26 \x1a', '27 \x1b', '28 \x1c', '29 \x1d', '30 \x1e', '31 \x1f', '32 ', '33 !', '34 "', '35 #', '36 $', '37 %', '38 &', "39 '", '40 (', '41 )', '42 *', '43 +', '44 ,', '45 -', '46 .', '47 /', '48 0', '49 1', '50 2', '51 3', '52 4', '53 5', '54 6', '55 7', '56 8', '57 9', '58 :', '59 ;', '60 <', '61 =', '62 >', '63 ?', '64 @', '65 A', '66 B', '67 C', '68 D', '69 E', '70 F', '71 G', '72 H', '73 I', '74 J', '75 K', '76 L', '77 M', '78 N', '79 O', '80 P', '81 Q', '82 R', '83 S', '84 T', '85 U', '86 V', '87 W', '88 X', '89 Y', '90 Z', '91 [', '92 \\', '93 ]', '94 ^', '95 _', '96 `', '97 a', '98 b', '99 c', '100 d', '101 e', '102 f', '103 g', '104 h', '105 i', '106 j', '107 k', '108 l', '109 m', '110 n', '111 o', '112 p', '113 q', '114 r', '115 s', '116 t', '117 u', '118 v', '119 w', '120 x', '121 y', '122 z', '123 {', '124 |', '125 }', '126 ~', '127 \x7f']
  160. assert type(bin(1234)) is str
  161. # 无法测试, 不能覆盖-----------------------------------------------
  162. # 136: 285: _vm->bind_builtin_func<1>("dir", [](VM* vm, ArgsView args) {
  163. # 10: 286: std::set<StrName> names;
  164. # 10: 287: if(!is_tagged(args[0]) && args[0]->is_attr_valid()){
  165. # #####: 288: std::vector<StrName> keys = args[0]->attr().keys();
  166. # #####: 289: names.insert(keys.begin(), keys.end());
  167. # #####: 290: }
  168. # 10: 291: const NameDict& t_attr = vm->_t(args[0])->attr();
  169. # 10: 292: std::vector<StrName> keys = t_attr.keys();
  170. # 10: 293: names.insert(keys.begin(), keys.end());
  171. # 10: 294: List ret;
  172. # 305: 295: for (StrName name : names) ret.push_back(VAR(name.sv()));
  173. # 10: 296: return VAR(std::move(ret));
  174. # 10: 297: });
  175. # test dir:
  176. # test __repr__:
  177. class A():
  178. def __init__(self):
  179. self.attr = 0
  180. repr(A())
  181. # 未完全测试准确性-----------------------------------------------
  182. # 33600: 318: _vm->bind_constructor<-1>("range", [](VM* vm, ArgsView args) {
  183. # 16742: 319: args._begin += 1; // skip cls
  184. # 16742: 320: Range r;
  185. # 16742: 321: switch (args.size()) {
  186. # 8735: 322: case 1: r.stop = CAST(i64, args[0]); break;
  187. # 3867: 323: case 2: r.start = CAST(i64, args[0]); r.stop = CAST(i64, args[1]); break;
  188. # 4140: 324: case 3: r.start = CAST(i64, args[0]); r.stop = CAST(i64, args[1]); r.step = CAST(i64, args[2]); break;
  189. # #####: 325: default: vm->TypeError("expected 1-3 arguments, got " + std::to_string(args.size()));
  190. # #####: 326: }
  191. # 33484: 327: return VAR(r);
  192. # 16742: 328: });
  193. # -: 329:
  194. # test range:
  195. try:
  196. range(1,2,3,4)
  197. print('未能拦截错误, 在测试 range')
  198. exit(1)
  199. except:
  200. pass
  201. # /************ int ************/
  202. try:
  203. int('asad')
  204. print('未能拦截错误, 在测试 int')
  205. exit(1)
  206. except:
  207. pass
  208. try:
  209. int(123, 16)
  210. print('未能拦截错误, 在测试 int')
  211. exit(1)
  212. except:
  213. pass
  214. # 未完全测试准确性-----------------------------------------------
  215. # 116: 392: _vm->bind_method<0>("int", "bit_length", [](VM* vm, ArgsView args) {
  216. # #####: 393: i64 x = _CAST(i64, args[0]);
  217. # #####: 394: if(x < 0) x = -x;
  218. # -: 395: int bits = 0;
  219. # #####: 396: while(x){ x >>= 1; bits++; }
  220. # #####: 397: return VAR(bits);
  221. # -: 398: });
  222. # test int.bit_length:
  223. assert type(int.bit_length(100)) is int
  224. # 未完全测试准确性-----------------------------------------------
  225. # 116: 400: _vm->bind__floordiv__(_vm->tp_int, [](VM* vm, PyObject* lhs_, PyObject* rhs_) {
  226. # #####: 401: i64 rhs = CAST(i64, rhs_);
  227. # #####: 402: return VAR(_CAST(i64, lhs_) / rhs);
  228. # -: 403: });
  229. # test int.__floordiv__:
  230. assert type(10//11) is int
  231. # 未完全测试准确性-----------------------------------------------
  232. # 116: 405: _vm->bind__mod__(_vm->tp_int, [](VM* vm, PyObject* lhs_, PyObject* rhs_) {
  233. # #####: 406: i64 rhs = CAST(i64, rhs_);
  234. # #####: 407: return VAR(_CAST(i64, lhs_) % rhs);
  235. # test int.__mod__:
  236. assert type(11%2) is int
  237. try:
  238. float('asad')
  239. print('未能拦截错误, 在测试 float')
  240. exit(1)
  241. except:
  242. pass
  243. try:
  244. float([])
  245. print('未能拦截错误, 在测试 float')
  246. exit(1)
  247. except:
  248. pass
  249. # /************ str ************/
  250. # test str.__rmul__:
  251. assert type(12 * '12') is str
  252. # 未完全测试准确性-----------------------------------------------
  253. # 116: 554: _vm->bind_method<1>("str", "index", [](VM* vm, ArgsView args) {
  254. # #####: 555: const Str& self = _CAST(Str&, args[0]);
  255. # #####: 556: const Str& sub = CAST(Str&, args[1]);
  256. # #####: 557: int index = self.index(sub);
  257. # #####: 558: if(index == -1) vm->ValueError("substring not found");
  258. # #####: 559: return VAR(index);
  259. # #####: 560: });
  260. # test str.index:
  261. assert type('25363546'.index('63')) is int
  262. try:
  263. '25363546'.index('err')
  264. print('未能拦截错误, 在测试 str.index')
  265. exit(1)
  266. except:
  267. pass
  268. # 未完全测试准确性-----------------------------------------------
  269. # 116: 562: _vm->bind_method<1>("str", "find", [](VM* vm, ArgsView args) {
  270. # #####: 563: const Str& self = _CAST(Str&, args[0]);
  271. # #####: 564: const Str& sub = CAST(Str&, args[1]);
  272. # #####: 565: return VAR(self.index(sub));
  273. # -: 566: });
  274. # test str.find:
  275. assert type('25363546'.find('63')) is int
  276. assert type('25363546'.find('err')) is int
  277. # /************ list ************/
  278. # 未完全测试准确性-----------------------------------------------
  279. # 174: 615: _vm->bind_constructor<-1>("list", [](VM* vm, ArgsView args) {
  280. # 29: 616: if(args.size() == 1+0) return VAR(List());
  281. # 29: 617: if(args.size() == 1+1){
  282. # 29: 618: return vm->py_list(args[1]);
  283. # -: 619: }
  284. # #####: 620: vm->TypeError("list() takes 0 or 1 arguments");
  285. # #####: 621: return vm->None;
  286. # 29: 622: });
  287. # test list:
  288. try:
  289. list(1,2)
  290. print('未能拦截错误, 在测试 list')
  291. exit(1)
  292. except:
  293. pass
  294. # 未完全测试准确性----------------------------------------------
  295. # 116: 648: _vm->bind_method<1>("list", "index", [](VM* vm, ArgsView args) {
  296. # #####: 649: List& self = _CAST(List&, args[0]);
  297. # #####: 650: PyObject* obj = args[1];
  298. # #####: 651: for(int i=0; i<self.size(); i++){
  299. # #####: 652: if(vm->py_eq(self[i], obj)) return VAR(i);
  300. # -: 653: }
  301. # #####: 654: vm->ValueError(_CAST(Str&, vm->py_repr(obj)) + " is not in list");
  302. # #####: 655: return vm->None;
  303. # #####: 656: });
  304. # test list.index:
  305. assert type([1,2,3,4,5].index(4)) is int
  306. try:
  307. [1,2,3,4,5].index(6)
  308. print('未能拦截错误, 在测试 list.index')
  309. exit(1)
  310. except:
  311. pass
  312. # 未完全测试准确性----------------------------------------------
  313. # 118: 658: _vm->bind_method<1>("list", "remove", [](VM* vm, ArgsView args) {
  314. # 1: 659: List& self = _CAST(List&, args[0]);
  315. # 1: 660: PyObject* obj = args[1];
  316. # 2: 661: for(int i=0; i<self.size(); i++){
  317. # 2: 662: if(vm->py_eq(self[i], obj)){
  318. # 1: 663: self.erase(i);
  319. # 1: 664: return vm->None;
  320. # -: 665: }
  321. # -: 666: }
  322. # #####: 667: vm->ValueError(_CAST(Str&, vm->py_repr(obj)) + " is not in list");
  323. # #####: 668: return vm->None;
  324. # 1: 669: });
  325. # test list.remove:
  326. try:
  327. [1,2,3,4,5].remove(6)
  328. print('未能拦截错误, 在测试 list.remove')
  329. exit(1)
  330. except:
  331. pass
  332. # 未完全测试准确性----------------------------------------------
  333. # 2536: 671: _vm->bind_method<-1>("list", "pop", [](VM* vm, ArgsView args) {
  334. # 1210: 672: List& self = _CAST(List&, args[0]);
  335. # 1210: 673: if(args.size() == 1+0){
  336. # 1208: 674: if(self.empty()) vm->IndexError("pop from empty list");
  337. # 1208: 675: return self.popx_back();
  338. # -: 676: }
  339. # 2: 677: if(args.size() == 1+1){
  340. # 2: 678: int index = CAST(int, args[1]);
  341. # 2: 679: index = vm->normalized_index(index, self.size());
  342. # 2: 680: PyObject* ret = self[index];
  343. # 2: 681: self.erase(index);
  344. # -: 682: return ret;
  345. # -: 683: }
  346. # #####: 684: vm->TypeError("pop() takes at most 1 argument");
  347. # #####: 685: return vm->None;
  348. # 1210: 686: });
  349. # test list.pop:
  350. try:
  351. [1,2,3,4,5].pop(1,2,3,4)
  352. print('未能拦截错误, 在测试 list.pop')
  353. exit(1)
  354. except:
  355. pass
  356. # 未完全测试准确性-----------------------------------------------
  357. # test list.__rmul__:
  358. assert type(12 * [12]) is list
  359. # /************ tuple ************/
  360. # 未完全测试准确性-----------------------------------------------
  361. # 180: 783: _vm->bind_constructor<-1>("tuple", [](VM* vm, ArgsView args) {
  362. # 32: 784: if(args.size() == 1+0) return VAR(Tuple(0));
  363. # 32: 785: if(args.size() == 1+1){
  364. # 32: 786: List list = CAST(List, vm->py_list(args[1]));
  365. # 32: 787: return VAR(Tuple(std::move(list)));
  366. # 32: 788: }
  367. # #####: 789: vm->TypeError("tuple() takes at most 1 argument");
  368. # #####: 790: return vm->None;
  369. # 32: 791: });
  370. # -: 792:
  371. # test tuple:
  372. try:
  373. tuple(1,2)
  374. print('未能拦截错误, 在测试 tuple')
  375. exit(1)
  376. except:
  377. pass
  378. # 未完全测试准确性-----------------------------------------------
  379. # 118: 793: _vm->bind__contains__(_vm->tp_tuple, [](VM* vm, PyObject* obj, PyObject* item) {
  380. # 1: 794: Tuple& self = _CAST(Tuple&, obj);
  381. # 3: 795: for(PyObject* i: self) if(vm->py_eq(i, item)) return vm->True;
  382. # #####: 796: return vm->False;
  383. # 1: 797: });
  384. # test tuple.__contains__:
  385. assert (1,2,3).__contains__(5) == False
  386. # 未完全测试准确性-----------------------------------------------
  387. # 116: 799: _vm->bind_method<1>("tuple", "count", [](VM* vm, ArgsView args) {
  388. # #####: 800: Tuple& self = _CAST(Tuple&, args[0]);
  389. # -: 801: int count = 0;
  390. # #####: 802: for(PyObject* i: self) if(vm->py_eq(i, args[1])) count++;
  391. # #####: 803: return VAR(count);
  392. # -: 804: });
  393. # test tuple.count:
  394. assert (1,2,2,3,3,3).count(3) == 3
  395. assert (1,2,2,3,3,3).count(0) == 0
  396. # /************ bool ************/
  397. # -----------------------------------------------
  398. # 116: 842: _vm->bind__repr__(_vm->tp_bool, [](VM* vm, PyObject* self) {
  399. # #####: 843: bool val = _CAST(bool, self);
  400. # #####: 844: return VAR(val ? "True" : "False");
  401. # -: 845: });
  402. # test bool.__repr__:
  403. assert repr(True) == 'True'
  404. assert repr(False) == 'False'
  405. # 未完全测试准确性-----------------------------------------------
  406. # 116: 882: _vm->bind__and__(_vm->tp_bool, [](VM* vm, PyObject* lhs, PyObject* rhs) {
  407. # #####: 883: return VAR(_CAST(bool, lhs) && CAST(bool, rhs));
  408. # -: 884: });
  409. # test bool.__and__:
  410. assert True & True == 1
  411. # 未完全测试准确性-----------------------------------------------
  412. # 116: 885: _vm->bind__or__(_vm->tp_bool, [](VM* vm, PyObject* lhs, PyObject* rhs) {
  413. # #####: 886: return VAR(_CAST(bool, lhs) || CAST(bool, rhs));
  414. # -: 887: });
  415. # test bool.__or__:
  416. assert True | True == 1
  417. # 未完全测试准确性-----------------------------------------------
  418. # 116: 888: _vm->bind__xor__(_vm->tp_bool, [](VM* vm, PyObject* lhs, PyObject* rhs) {
  419. # #####: 889: return VAR(_CAST(bool, lhs) != CAST(bool, rhs));
  420. # -: 890: });
  421. # test bool.__xor__:
  422. assert (True ^ True) == 0
  423. # 未完全测试准确性-----------------------------------------------
  424. # 120: 891: _vm->bind__eq__(_vm->tp_bool, [](VM* vm, PyObject* lhs, PyObject* rhs) {
  425. # 2: 892: if(is_non_tagged_type(rhs, vm->tp_bool)) return VAR(lhs == rhs);
  426. # #####: 893: if(is_int(rhs)) return VAR(_CAST(bool, lhs) == (bool)CAST(i64, rhs));
  427. # #####: 894: return vm->NotImplemented;
  428. # 2: 895: });
  429. # test bool.__eq__:
  430. assert (True == True) == 1
  431. # /************ bytes ************/
  432. # 未完全测试准确性-----------------------------------------------
  433. # 116: 922: _vm->bind__hash__(_vm->tp_bytes, [](VM* vm, PyObject* obj) {
  434. # #####: 923: const Bytes& self = _CAST(Bytes&, obj);
  435. # #####: 924: std::string_view view(self.data(), self.size());
  436. # #####: 925: return (i64)std::hash<std::string_view>()(view);
  437. # #####: 926: });
  438. # test bytes.__hash__:
  439. assert type(hash(bytes([0x41, 0x42, 0x43]))) is int
  440. # 未完全测试准确性-----------------------------------------------
  441. # test bytes.__repr__:
  442. assert type(repr(bytes([0x41, 0x42, 0x43]))) is str
  443. # /************ slice ************/
  444. # 未完全测试准确性-----------------------------------------------
  445. # 116: 953: _vm->bind_constructor<4>("slice", [](VM* vm, ArgsView args) {
  446. # #####: 954: return VAR(Slice(args[1], args[2], args[3]));
  447. # -: 955: });
  448. # test slice:
  449. assert type(slice(0.1, 0.2, 0.3)) is slice
  450. # 未完全测试准确性-----------------------------------------------
  451. # 116: 1529: bind_property(_t(tp_slice), "start", [](VM* vm, ArgsView args){
  452. # #####: 1530: return CAST(Slice&, args[0]).start;
  453. # -: 1531: });
  454. # 116: 1532: bind_property(_t(tp_slice), "stop", [](VM* vm, ArgsView args){
  455. # #####: 1533: return CAST(Slice&, args[0]).stop;
  456. # -: 1534: });
  457. # 116: 1535: bind_property(_t(tp_slice), "step", [](VM* vm, ArgsView args){
  458. # #####: 1536: return CAST(Slice&, args[0]).step;
  459. # -: 1537: });
  460. s = slice(1, 2, 3)
  461. assert type(s) is slice
  462. assert s.start == 1
  463. assert s.stop == 2
  464. assert s.step == 3
  465. assert slice.__dict__['start'].__signature__ == 'start'
  466. # 未完全测试准确性-----------------------------------------------
  467. # test slice.__repr__
  468. assert type(repr(slice(1,1,1))) is str
  469. # /************ mappingproxy ************/
  470. # 未完全测试准确性-----------------------------------------------
  471. # 116: 968: _vm->bind_method<0>("mappingproxy", "keys", [](VM* vm, ArgsView args) {
  472. # #####: 969: MappingProxy& self = _CAST(MappingProxy&, args[0]);
  473. # #####: 970: List keys;
  474. # #####: 971: for(StrName name : self.attr().keys()) keys.push_back(VAR(name.sv()));
  475. # #####: 972: return VAR(std::move(keys));
  476. # #####: 973: });
  477. # test mappingproxy.keys:
  478. class A():
  479. def __init__(self):
  480. self.a = 10
  481. def method(self):
  482. pass
  483. my_mappingproxy = A().__dict__
  484. assert type(my_mappingproxy.keys()) is list
  485. # 未完全测试准确性-----------------------------------------------
  486. # 116: 975: _vm->bind_method<0>("mappingproxy", "values", [](VM* vm, ArgsView args) {
  487. # #####: 976: MappingProxy& self = _CAST(MappingProxy&, args[0]);
  488. # #####: 977: List values;
  489. # #####: 978: for(auto& item : self.attr().items()) values.push_back(item.second);
  490. # #####: 979: return VAR(std::move(values));
  491. # #####: 980: });
  492. # test mappingproxy.values:
  493. class A():
  494. def __init__(self):
  495. self.a = 10
  496. def method(self):
  497. pass
  498. my_mappingproxy = A().__dict__
  499. assert type(my_mappingproxy.values()) is list
  500. # 未完全测试准确性-----------------------------------------------
  501. # 116: 992: _vm->bind__len__(_vm->tp_mappingproxy, [](VM* vm, PyObject* obj) {
  502. # #####: 993: return (i64)_CAST(MappingProxy&, obj).attr().size();
  503. # -: 994: });
  504. # test mappingproxy.__len__:
  505. class A():
  506. def __init__(self):
  507. self.a = 10
  508. def method(self):
  509. pass
  510. my_mappingproxy = A().__dict__
  511. assert type(len(my_mappingproxy)) is int
  512. # 未完全测试准确性-----------------------------------------------
  513. # 116: 996: _vm->bind__hash__(_vm->tp_mappingproxy, [](VM* vm, PyObject* obj) {
  514. # #####: 997: vm->TypeError("unhashable type: 'mappingproxy'");
  515. # #####: 998: return (i64)0;
  516. # #####: 999: });
  517. # test mappingproxy.__hash__:
  518. class A():
  519. def __init__(self):
  520. self.a = 10
  521. def method(self):
  522. pass
  523. my_mappingproxy = A().__dict__
  524. try:
  525. hash(my_mappingproxy)
  526. print('未能拦截错误, 在测试 mappingproxy.__hash__')
  527. exit(1)
  528. except TypeError:
  529. pass
  530. a = hash(object()) # object is hashable
  531. a = hash(A()) # A is hashable
  532. class B:
  533. def __eq__(self, o): return True
  534. try:
  535. hash(B())
  536. print('未能拦截错误, 在测试 B.__hash__')
  537. exit(1)
  538. except TypeError:
  539. pass
  540. # 未完全测试准确性-----------------------------------------------
  541. # test mappingproxy.__repr__:
  542. class A():
  543. def __init__(self):
  544. self.a = 10
  545. def method(self):
  546. pass
  547. my_mappingproxy = A().__dict__
  548. assert type(repr(my_mappingproxy)) is str
  549. # /************ dict ************/
  550. # 未完全测试准确性-----------------------------------------------
  551. # 202: 1033: _vm->bind_method<-1>("dict", "__init__", [](VM* vm, ArgsView args){
  552. # 43: 1034: if(args.size() == 1+0) return vm->None;
  553. # 42: 1035: if(args.size() == 1+1){
  554. # 42: 1036: auto _lock = vm->heap.gc_scope_lock();
  555. # 42: 1037: Dict& self = _CAST(Dict&, args[0]);
  556. # 42: 1038: List& list = CAST(List&, args[1]);
  557. # 165: 1039: for(PyObject* item : list){
  558. # 123: 1040: Tuple& t = CAST(Tuple&, item);
  559. # 123: 1041: if(t.size() != 2){
  560. # #####: 1042: vm->ValueError("dict() takes an iterable of tuples (key, value)");
  561. # #####: 1043: return vm->None;
  562. # -: 1044: }
  563. # 123: 1045: self.set(t[0], t[1]);
  564. # 246: 1046: }
  565. # 42: 1047: return vm->None;
  566. # 42: 1048: }
  567. # #####: 1049: vm->TypeError("dict() takes at most 1 argument");
  568. # #####: 1050: return vm->None;
  569. # 43: 1051: });
  570. # test dict:
  571. assert type(dict([(1,2)])) is dict
  572. try:
  573. dict([(1, 2, 3)])
  574. print('未能拦截错误, 在测试 dict')
  575. exit(1)
  576. except:
  577. pass
  578. try:
  579. dict([(1, 2)], 1)
  580. print('未能拦截错误, 在测试 dict')
  581. exit(1)
  582. except:
  583. pass
  584. # 未完全测试准确性-----------------------------------------------
  585. # 116: 1057: _vm->bind__hash__(_vm->tp_dict, [](VM* vm, PyObject* obj) {
  586. # #####: 1058: vm->TypeError("unhashable type: 'dict'");
  587. # #####: 1059: return (i64)0;
  588. # #####: 1060: });
  589. # test dict.__hash__
  590. try:
  591. hash(dict([(1,2)]))
  592. print('未能拦截错误, 在测试 dict.__hash__')
  593. exit(1)
  594. except:
  595. pass
  596. # 未完全测试准确性-----------------------------------------------
  597. # 116: 1093: _vm->bind__iter__(_vm->tp_dict, [](VM* vm, PyObject* obj) {
  598. # #####: 1094: const Dict& self = _CAST(Dict&, obj);
  599. # #####: 1095: return vm->py_iter(VAR(self.keys()));
  600. # #####: 1096: });
  601. # test dict.__iter__
  602. for k in {1:2, 2:3, 3:4}:
  603. assert k in [1,2,3]
  604. # 未完全测试准确性-----------------------------------------------
  605. # 166: 1098: _vm->bind_method<-1>("dict", "get", [](VM* vm, ArgsView args) {
  606. # 25: 1099: Dict& self = _CAST(Dict&, args[0]);
  607. # 25: 1100: if(args.size() == 1+1){
  608. # #####: 1101: PyObject* ret = self.try_get(args[1]);
  609. # #####: 1102: if(ret != nullptr) return ret;
  610. # #####: 1103: return vm->None;
  611. # 25: 1104: }else if(args.size() == 1+2){
  612. # 25: 1105: PyObject* ret = self.try_get(args[1]);
  613. # 25: 1106: if(ret != nullptr) return ret;
  614. # 19: 1107: return args[2];
  615. # -: 1108: }
  616. # #####: 1109: vm->TypeError("get() takes at most 2 arguments");
  617. # #####: 1110: return vm->None;
  618. # 25: 1111: });
  619. # test dict.get
  620. assert {1:2, 3:4}.get(1) == 2
  621. assert {1:2, 3:4}.get(2) is None
  622. assert {1:2, 3:4}.get(20, 100) == 100
  623. try:
  624. {1:2, 3:4}.get(1,1, 1)
  625. print('未能拦截错误, 在测试 dict.get')
  626. exit(1)
  627. except:
  628. pass
  629. # 未完全测试准确性-----------------------------------------------
  630. # test dict.__repr__
  631. assert type(repr({1:2, 3:4})) is str
  632. # /************ property ************/
  633. class A():
  634. def __init__(self):
  635. self._name = '123'
  636. @property
  637. def value(self):
  638. return 2
  639. def get_name(self):
  640. '''
  641. doc string 1
  642. '''
  643. return self._name
  644. def set_name(self, val):
  645. '''
  646. doc string 2
  647. '''
  648. self._name = val
  649. assert A().value == 2
  650. assert A.__dict__['value'].__signature__ == ''
  651. A.name = property(A.get_name, A.set_name, "name: str")
  652. assert A.__dict__['name'].__signature__ == 'name: str'
  653. try:
  654. property(A.get_name, A.set_name, 1)
  655. print('未能拦截错误, 在测试 property')
  656. exit(1)
  657. except:
  658. pass
  659. class Vector2:
  660. def __init__(self) -> None:
  661. self._x = 0
  662. @property
  663. def x(self):
  664. return self._x
  665. @x.setter
  666. def x(self, val):
  667. self._x = val
  668. v = Vector2()
  669. assert v.x == 0
  670. v.x = 10
  671. assert v.x == 10
  672. # /************ module timeit ************/
  673. import timeit
  674. def aaa():
  675. for i in range(10):
  676. for j in range(10):
  677. pass
  678. assert type(timeit.timeit(aaa, 2)) is float
  679. # 未完全测试准确性-----------------------------------------------
  680. # 116: 1218: _vm->bind_property(_vm->_t(_vm->tp_function), "__doc__", [](VM* vm, ArgsView args) {
  681. # #####: 1219: Function& func = _CAST(Function&, args[0]);
  682. # #####: 1220: return VAR(func.decl->docstring);
  683. # -: 1221: });
  684. # function.__doc__
  685. def aaa():
  686. '12345'
  687. pass
  688. assert type(aaa.__doc__) is str
  689. # 未完全测试准确性-----------------------------------------------
  690. # 116: 1229: _vm->bind_property(_vm->_t(_vm->tp_function), "__signature__", [](VM* vm, ArgsView args) {
  691. # #####: 1230: Function& func = _CAST(Function&, args[0]);
  692. # #####: 1231: return VAR(func.decl->signature);
  693. # -: 1232: });
  694. # function.__signature__
  695. def aaa():
  696. pass
  697. assert type(aaa.__signature__) is str
  698. # /************ module time ************/
  699. import time
  700. # 未完全测试准确性-----------------------------------------------
  701. # 116: 1267: vm->bind_func<1>(mod, "sleep", [](VM* vm, ArgsView args) {
  702. # #####: 1268: f64 seconds = CAST_F(args[0]);
  703. # #####: 1269: auto begin = std::chrono::system_clock::now();
  704. # #####: 1270: while(true){
  705. # #####: 1271: auto now = std::chrono::system_clock::now();
  706. # #####: 1272: f64 elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(now - begin).count() / 1000.0;
  707. # #####: 1273: if(elapsed >= seconds) break;
  708. # #####: 1274: }
  709. # #####: 1275: return vm->None;
  710. # #####: 1276: });
  711. # test time.time
  712. assert type(time.time()) is float
  713. local_t = time.localtime()
  714. assert type(local_t.tm_year) is int
  715. assert type(local_t.tm_mon) is int
  716. assert type(local_t.tm_mday) is int
  717. assert type(local_t.tm_hour) is int
  718. assert type(local_t.tm_min) is int
  719. assert type(local_t.tm_sec) is int
  720. assert type(local_t.tm_wday) is int
  721. assert type(local_t.tm_yday) is int
  722. assert type(local_t.tm_isdst) is int
  723. # 未完全测试准确性-----------------------------------------------
  724. # 116: 1267: vm->bind_func<1>(mod, "sleep", [](VM* vm, ArgsView args) {
  725. # #####: 1268: f64 seconds = CAST_F(args[0]);
  726. # #####: 1269: auto begin = std::chrono::system_clock::now();
  727. # #####: 1270: while(true){
  728. # #####: 1271: auto now = std::chrono::system_clock::now();
  729. # #####: 1272: f64 elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(now - begin).count() / 1000.0;
  730. # #####: 1273: if(elapsed >= seconds) break;
  731. # #####: 1274: }
  732. # #####: 1275: return vm->None;
  733. # #####: 1276: });
  734. # test time.sleep
  735. time.sleep(0.1)
  736. # 未完全测试准确性-----------------------------------------------
  737. # 116: 1278: vm->bind_func<0>(mod, "localtime", [](VM* vm, ArgsView args) {
  738. # #####: 1279: auto now = std::chrono::system_clock::now();
  739. # #####: 1280: std::time_t t = std::chrono::system_clock::to_time_t(now);
  740. # #####: 1281: std::tm* tm = std::localtime(&t);
  741. # #####: 1282: Dict d(vm);
  742. # #####: 1283: d.set(VAR("tm_year"), VAR(tm->tm_year + 1900));
  743. # #####: 1284: d.set(VAR("tm_mon"), VAR(tm->tm_mon + 1));
  744. # #####: 1285: d.set(VAR("tm_mday"), VAR(tm->tm_mday));
  745. # #####: 1286: d.set(VAR("tm_hour"), VAR(tm->tm_hour));
  746. # #####: 1287: d.set(VAR("tm_min"), VAR(tm->tm_min));
  747. # #####: 1288: d.set(VAR("tm_sec"), VAR(tm->tm_sec + 1));
  748. # #####: 1289: d.set(VAR("tm_wday"), VAR((tm->tm_wday + 6) % 7));
  749. # #####: 1290: d.set(VAR("tm_yday"), VAR(tm->tm_yday + 1));
  750. # #####: 1291: d.set(VAR("tm_isdst"), VAR(tm->tm_isdst));
  751. # #####: 1292: return VAR(std::move(d));
  752. # #####: 1293: });
  753. # 58: 1294:}
  754. # test time.localtime
  755. assert type(time.localtime()) is time.struct_time
  756. # test min/max
  757. assert min(1, 2) == 1
  758. assert min(1, 2, 3) == 1
  759. assert min([1, 2]) == 1
  760. assert min([1, 2], key=lambda x: -x) == 2
  761. assert max(1, 2) == 2
  762. assert max(1, 2, 3) == 3
  763. assert max([1, 2]) == 2
  764. assert max([1, 2, 3], key=lambda x: -x) == 1
  765. assert min([
  766. (1, 2),
  767. (1, 3),
  768. (1, 4),
  769. ]) == (1, 2)
  770. assert min(1, 2) == 1
  771. assert max(1, 2) == 2
  772. # test callable
  773. assert callable(lambda: 1) is True # function
  774. assert callable(1) is False # int
  775. assert callable(object) is True # type
  776. assert callable(object()) is False
  777. assert callable([].append) is True # bound method
  778. assert callable([].__getitem__) is True # bound method
  779. class A:
  780. def __init__(self):
  781. pass
  782. def __call__(self):
  783. pass
  784. assert callable(A) is True # type
  785. assert callable(A()) is True # instance with __call__
  786. assert callable(A.__call__) is True # bound method
  787. assert callable(A.__init__) is True # bound method
  788. assert callable(print) is True # builtin function
  789. assert callable(isinstance) is True # builtin function
  790. assert id(0) is None
  791. assert id(2**62) is not None
  792. # test issubclass
  793. assert issubclass(int, int) is True
  794. assert issubclass(int, object) is True
  795. assert issubclass(object, int) is False
  796. assert issubclass(object, object) is True
  797. assert issubclass(int, type) is False
  798. assert issubclass(type, type) is True
  799. assert issubclass(float, int) is False