99_builtin_func.py 33 KB

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