99_builtin_func.py 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970
  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. # 116: 721: _vm->bind_method<1>("list", "__rmul__", [](VM* vm, ArgsView args) {
  380. # #####: 722: const List& self = _CAST(List&, args[0]);
  381. # #####: 723: if(!is_int(args[1])) return vm->NotImplemented;
  382. # #####: 724: int n = _CAST(int, args[1]);
  383. # #####: 725: List result;
  384. # #####: 726: result.reserve(self.size() * n);
  385. # #####: 727: for(int i = 0; i < n; i++) result.extend(self);
  386. # #####: 728: return VAR(std::move(result));
  387. # #####: 729: });
  388. # test list.__rmul__:
  389. assert type(12 * [12]) is list
  390. # /************ tuple ************/
  391. # 未完全测试准确性-----------------------------------------------
  392. # 180: 783: _vm->bind_constructor<-1>("tuple", [](VM* vm, ArgsView args) {
  393. # 32: 784: if(args.size() == 1+0) return VAR(Tuple(0));
  394. # 32: 785: if(args.size() == 1+1){
  395. # 32: 786: List list = CAST(List, vm->py_list(args[1]));
  396. # 32: 787: return VAR(Tuple(std::move(list)));
  397. # 32: 788: }
  398. # #####: 789: vm->TypeError("tuple() takes at most 1 argument");
  399. # #####: 790: return vm->None;
  400. # 32: 791: });
  401. # -: 792:
  402. # test tuple:
  403. try:
  404. tuple(1,2)
  405. print('未能拦截错误, 在测试 tuple')
  406. exit(1)
  407. except:
  408. pass
  409. # 未完全测试准确性-----------------------------------------------
  410. # 118: 793: _vm->bind__contains__(_vm->tp_tuple, [](VM* vm, PyObject* obj, PyObject* item) {
  411. # 1: 794: Tuple& self = _CAST(Tuple&, obj);
  412. # 3: 795: for(PyObject* i: self) if(vm->py_equals(i, item)) return vm->True;
  413. # #####: 796: return vm->False;
  414. # 1: 797: });
  415. # test tuple.__contains__:
  416. assert (1,2,3).__contains__(5) == False
  417. # 未完全测试准确性-----------------------------------------------
  418. # 116: 799: _vm->bind_method<1>("tuple", "count", [](VM* vm, ArgsView args) {
  419. # #####: 800: Tuple& self = _CAST(Tuple&, args[0]);
  420. # -: 801: int count = 0;
  421. # #####: 802: for(PyObject* i: self) if(vm->py_equals(i, args[1])) count++;
  422. # #####: 803: return VAR(count);
  423. # -: 804: });
  424. # test tuple.count:
  425. assert (1,2,2,3,3,3).count(3) == 3
  426. assert (1,2,2,3,3,3).count(0) == 0
  427. # /************ bool ************/
  428. # -----------------------------------------------
  429. # 116: 842: _vm->bind__repr__(_vm->tp_bool, [](VM* vm, PyObject* self) {
  430. # #####: 843: bool val = _CAST(bool, self);
  431. # #####: 844: return VAR(val ? "True" : "False");
  432. # -: 845: });
  433. # test bool.__repr__:
  434. assert repr(True) == 'True'
  435. assert repr(False) == 'False'
  436. # 未完全测试准确性-----------------------------------------------
  437. # 116: 882: _vm->bind__and__(_vm->tp_bool, [](VM* vm, PyObject* lhs, PyObject* rhs) {
  438. # #####: 883: return VAR(_CAST(bool, lhs) && CAST(bool, rhs));
  439. # -: 884: });
  440. # test bool.__and__:
  441. assert True & True == 1
  442. # 未完全测试准确性-----------------------------------------------
  443. # 116: 885: _vm->bind__or__(_vm->tp_bool, [](VM* vm, PyObject* lhs, PyObject* rhs) {
  444. # #####: 886: return VAR(_CAST(bool, lhs) || CAST(bool, rhs));
  445. # -: 887: });
  446. # test bool.__or__:
  447. assert True | True == 1
  448. # 未完全测试准确性-----------------------------------------------
  449. # 116: 888: _vm->bind__xor__(_vm->tp_bool, [](VM* vm, PyObject* lhs, PyObject* rhs) {
  450. # #####: 889: return VAR(_CAST(bool, lhs) != CAST(bool, rhs));
  451. # -: 890: });
  452. # test bool.__xor__:
  453. assert (True ^ True) == 0
  454. # 未完全测试准确性-----------------------------------------------
  455. # 120: 891: _vm->bind__eq__(_vm->tp_bool, [](VM* vm, PyObject* lhs, PyObject* rhs) {
  456. # 2: 892: if(is_non_tagged_type(rhs, vm->tp_bool)) return VAR(lhs == rhs);
  457. # #####: 893: if(is_int(rhs)) return VAR(_CAST(bool, lhs) == (bool)CAST(i64, rhs));
  458. # #####: 894: return vm->NotImplemented;
  459. # 2: 895: });
  460. # test bool.__eq__:
  461. assert (True == True) == 1
  462. # /************ bytes ************/
  463. # 未完全测试准确性-----------------------------------------------
  464. # 116: 922: _vm->bind__hash__(_vm->tp_bytes, [](VM* vm, PyObject* obj) {
  465. # #####: 923: const Bytes& self = _CAST(Bytes&, obj);
  466. # #####: 924: std::string_view view(self.data(), self.size());
  467. # #####: 925: return (i64)std::hash<std::string_view>()(view);
  468. # #####: 926: });
  469. # test bytes.__hash__:
  470. assert type(hash(bytes([0x41, 0x42, 0x43]))) is int
  471. # 未完全测试准确性-----------------------------------------------
  472. # test bytes.__repr__:
  473. assert type(repr(bytes([0x41, 0x42, 0x43]))) is str
  474. # /************ slice ************/
  475. # 未完全测试准确性-----------------------------------------------
  476. # 116: 953: _vm->bind_constructor<4>("slice", [](VM* vm, ArgsView args) {
  477. # #####: 954: return VAR(Slice(args[1], args[2], args[3]));
  478. # -: 955: });
  479. # test slice:
  480. assert type(slice(0.1, 0.2, 0.3)) is slice
  481. # 未完全测试准确性-----------------------------------------------
  482. # 116: 1529: bind_property(_t(tp_slice), "start", [](VM* vm, ArgsView args){
  483. # #####: 1530: return CAST(Slice&, args[0]).start;
  484. # -: 1531: });
  485. # 116: 1532: bind_property(_t(tp_slice), "stop", [](VM* vm, ArgsView args){
  486. # #####: 1533: return CAST(Slice&, args[0]).stop;
  487. # -: 1534: });
  488. # 116: 1535: bind_property(_t(tp_slice), "step", [](VM* vm, ArgsView args){
  489. # #####: 1536: return CAST(Slice&, args[0]).step;
  490. # -: 1537: });
  491. s = slice(1, 2, 3)
  492. assert type(s) is slice
  493. assert s.start == 1
  494. assert s.stop == 2
  495. assert s.step == 3
  496. assert slice.__dict__['start'].__signature__ == 'start'
  497. # 未完全测试准确性-----------------------------------------------
  498. # test slice.__repr__
  499. assert type(repr(slice(1,1,1))) is str
  500. # /************ mappingproxy ************/
  501. # 未完全测试准确性-----------------------------------------------
  502. # 116: 968: _vm->bind_method<0>("mappingproxy", "keys", [](VM* vm, ArgsView args) {
  503. # #####: 969: MappingProxy& self = _CAST(MappingProxy&, args[0]);
  504. # #####: 970: List keys;
  505. # #####: 971: for(StrName name : self.attr().keys()) keys.push_back(VAR(name.sv()));
  506. # #####: 972: return VAR(std::move(keys));
  507. # #####: 973: });
  508. # test mappingproxy.keys:
  509. class A():
  510. def __init__(self):
  511. self.a = 10
  512. def method(self):
  513. pass
  514. my_mappingproxy = A().__dict__
  515. assert type(my_mappingproxy.keys()) is list
  516. # 未完全测试准确性-----------------------------------------------
  517. # 116: 975: _vm->bind_method<0>("mappingproxy", "values", [](VM* vm, ArgsView args) {
  518. # #####: 976: MappingProxy& self = _CAST(MappingProxy&, args[0]);
  519. # #####: 977: List values;
  520. # #####: 978: for(auto& item : self.attr().items()) values.push_back(item.second);
  521. # #####: 979: return VAR(std::move(values));
  522. # #####: 980: });
  523. # test mappingproxy.values:
  524. class A():
  525. def __init__(self):
  526. self.a = 10
  527. def method(self):
  528. pass
  529. my_mappingproxy = A().__dict__
  530. assert type(my_mappingproxy.values()) is list
  531. # 未完全测试准确性-----------------------------------------------
  532. # 116: 992: _vm->bind__len__(_vm->tp_mappingproxy, [](VM* vm, PyObject* obj) {
  533. # #####: 993: return (i64)_CAST(MappingProxy&, obj).attr().size();
  534. # -: 994: });
  535. # test mappingproxy.__len__:
  536. class A():
  537. def __init__(self):
  538. self.a = 10
  539. def method(self):
  540. pass
  541. my_mappingproxy = A().__dict__
  542. assert type(len(my_mappingproxy)) is int
  543. # 未完全测试准确性-----------------------------------------------
  544. # 116: 996: _vm->bind__hash__(_vm->tp_mappingproxy, [](VM* vm, PyObject* obj) {
  545. # #####: 997: vm->TypeError("unhashable type: 'mappingproxy'");
  546. # #####: 998: return (i64)0;
  547. # #####: 999: });
  548. # test mappingproxy.__hash__:
  549. class A():
  550. def __init__(self):
  551. self.a = 10
  552. def method(self):
  553. pass
  554. my_mappingproxy = A().__dict__
  555. try:
  556. hash(my_mappingproxy)
  557. print('未能拦截错误, 在测试 mappingproxy.__hash__')
  558. exit(1)
  559. except TypeError:
  560. pass
  561. a = hash(object()) # object is hashable
  562. a = hash(A()) # A is hashable
  563. class B:
  564. def __eq__(self, o): return True
  565. try:
  566. hash(B())
  567. print('未能拦截错误, 在测试 B.__hash__')
  568. exit(1)
  569. except TypeError:
  570. pass
  571. # 未完全测试准确性-----------------------------------------------
  572. # test mappingproxy.__repr__:
  573. class A():
  574. def __init__(self):
  575. self.a = 10
  576. def method(self):
  577. pass
  578. my_mappingproxy = A().__dict__
  579. assert type(repr(my_mappingproxy)) is str
  580. # /************ dict ************/
  581. # 未完全测试准确性-----------------------------------------------
  582. # 202: 1033: _vm->bind_method<-1>("dict", "__init__", [](VM* vm, ArgsView args){
  583. # 43: 1034: if(args.size() == 1+0) return vm->None;
  584. # 42: 1035: if(args.size() == 1+1){
  585. # 42: 1036: auto _lock = vm->heap.gc_scope_lock();
  586. # 42: 1037: Dict& self = _CAST(Dict&, args[0]);
  587. # 42: 1038: List& list = CAST(List&, args[1]);
  588. # 165: 1039: for(PyObject* item : list){
  589. # 123: 1040: Tuple& t = CAST(Tuple&, item);
  590. # 123: 1041: if(t.size() != 2){
  591. # #####: 1042: vm->ValueError("dict() takes an iterable of tuples (key, value)");
  592. # #####: 1043: return vm->None;
  593. # -: 1044: }
  594. # 123: 1045: self.set(t[0], t[1]);
  595. # 246: 1046: }
  596. # 42: 1047: return vm->None;
  597. # 42: 1048: }
  598. # #####: 1049: vm->TypeError("dict() takes at most 1 argument");
  599. # #####: 1050: return vm->None;
  600. # 43: 1051: });
  601. # test dict:
  602. assert type(dict([(1,2)])) is dict
  603. try:
  604. dict([(1, 2, 3)])
  605. print('未能拦截错误, 在测试 dict')
  606. exit(1)
  607. except:
  608. pass
  609. try:
  610. dict([(1, 2)], 1)
  611. print('未能拦截错误, 在测试 dict')
  612. exit(1)
  613. except:
  614. pass
  615. # 未完全测试准确性-----------------------------------------------
  616. # 116: 1057: _vm->bind__hash__(_vm->tp_dict, [](VM* vm, PyObject* obj) {
  617. # #####: 1058: vm->TypeError("unhashable type: 'dict'");
  618. # #####: 1059: return (i64)0;
  619. # #####: 1060: });
  620. # test dict.__hash__
  621. try:
  622. hash(dict([(1,2)]))
  623. print('未能拦截错误, 在测试 dict.__hash__')
  624. exit(1)
  625. except:
  626. pass
  627. # 未完全测试准确性-----------------------------------------------
  628. # 116: 1093: _vm->bind__iter__(_vm->tp_dict, [](VM* vm, PyObject* obj) {
  629. # #####: 1094: const Dict& self = _CAST(Dict&, obj);
  630. # #####: 1095: return vm->py_iter(VAR(self.keys()));
  631. # #####: 1096: });
  632. # test dict.__iter__
  633. for k in {1:2, 2:3, 3:4}:
  634. assert k in [1,2,3]
  635. # 未完全测试准确性-----------------------------------------------
  636. # 166: 1098: _vm->bind_method<-1>("dict", "get", [](VM* vm, ArgsView args) {
  637. # 25: 1099: Dict& self = _CAST(Dict&, args[0]);
  638. # 25: 1100: if(args.size() == 1+1){
  639. # #####: 1101: PyObject* ret = self.try_get(args[1]);
  640. # #####: 1102: if(ret != nullptr) return ret;
  641. # #####: 1103: return vm->None;
  642. # 25: 1104: }else if(args.size() == 1+2){
  643. # 25: 1105: PyObject* ret = self.try_get(args[1]);
  644. # 25: 1106: if(ret != nullptr) return ret;
  645. # 19: 1107: return args[2];
  646. # -: 1108: }
  647. # #####: 1109: vm->TypeError("get() takes at most 2 arguments");
  648. # #####: 1110: return vm->None;
  649. # 25: 1111: });
  650. # test dict.get
  651. assert {1:2, 3:4}.get(1) == 2
  652. assert {1:2, 3:4}.get(2) is None
  653. assert {1:2, 3:4}.get(20, 100) == 100
  654. try:
  655. {1:2, 3:4}.get(1,1, 1)
  656. print('未能拦截错误, 在测试 dict.get')
  657. exit(1)
  658. except:
  659. pass
  660. # 未完全测试准确性-----------------------------------------------
  661. # test dict.__repr__
  662. assert type(repr({1:2, 3:4})) is str
  663. # /************ property ************/
  664. class A():
  665. def __init__(self):
  666. self._name = '123'
  667. @property
  668. def value(self):
  669. return 2
  670. def get_name(self):
  671. '''
  672. doc string 1
  673. '''
  674. return self._name
  675. def set_name(self, val):
  676. '''
  677. doc string 2
  678. '''
  679. self._name = val
  680. assert A().value == 2
  681. assert A.__dict__['value'].__signature__ == ''
  682. A.name = property(A.get_name, A.set_name, "name: str")
  683. assert A.__dict__['name'].__signature__ == 'name: str'
  684. try:
  685. property(A.get_name, A.set_name, 1)
  686. print('未能拦截错误, 在测试 property')
  687. exit(1)
  688. except:
  689. pass
  690. # /************ module timeit ************/
  691. import timeit
  692. def aaa():
  693. for i in range(100):
  694. for j in range(100):
  695. pass
  696. assert type(timeit.timeit(aaa, 2)) is float
  697. # 未完全测试准确性-----------------------------------------------
  698. # 116: 1218: _vm->bind_property(_vm->_t(_vm->tp_function), "__doc__", [](VM* vm, ArgsView args) {
  699. # #####: 1219: Function& func = _CAST(Function&, args[0]);
  700. # #####: 1220: return VAR(func.decl->docstring);
  701. # -: 1221: });
  702. # function.__doc__
  703. def aaa():
  704. '12345'
  705. pass
  706. assert type(aaa.__doc__) is str
  707. # 未完全测试准确性-----------------------------------------------
  708. # 116: 1229: _vm->bind_property(_vm->_t(_vm->tp_function), "__signature__", [](VM* vm, ArgsView args) {
  709. # #####: 1230: Function& func = _CAST(Function&, args[0]);
  710. # #####: 1231: return VAR(func.decl->signature);
  711. # -: 1232: });
  712. # function.__signature__
  713. def aaa():
  714. pass
  715. assert type(aaa.__signature__) is str
  716. # /************ module time ************/
  717. import time
  718. # 未完全测试准确性-----------------------------------------------
  719. # 116: 1267: vm->bind_func<1>(mod, "sleep", [](VM* vm, ArgsView args) {
  720. # #####: 1268: f64 seconds = CAST_F(args[0]);
  721. # #####: 1269: auto begin = std::chrono::system_clock::now();
  722. # #####: 1270: while(true){
  723. # #####: 1271: auto now = std::chrono::system_clock::now();
  724. # #####: 1272: f64 elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(now - begin).count() / 1000.0;
  725. # #####: 1273: if(elapsed >= seconds) break;
  726. # #####: 1274: }
  727. # #####: 1275: return vm->None;
  728. # #####: 1276: });
  729. # test time.time
  730. assert type(time.time()) is float
  731. local_t = time.localtime()
  732. assert type(local_t.tm_year) is int
  733. assert type(local_t.tm_mon) is int
  734. assert type(local_t.tm_mday) is int
  735. assert type(local_t.tm_hour) is int
  736. assert type(local_t.tm_min) is int
  737. assert type(local_t.tm_sec) is int
  738. assert type(local_t.tm_wday) is int
  739. assert type(local_t.tm_yday) is int
  740. assert type(local_t.tm_isdst) is int
  741. # 未完全测试准确性-----------------------------------------------
  742. # 116: 1267: vm->bind_func<1>(mod, "sleep", [](VM* vm, ArgsView args) {
  743. # #####: 1268: f64 seconds = CAST_F(args[0]);
  744. # #####: 1269: auto begin = std::chrono::system_clock::now();
  745. # #####: 1270: while(true){
  746. # #####: 1271: auto now = std::chrono::system_clock::now();
  747. # #####: 1272: f64 elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(now - begin).count() / 1000.0;
  748. # #####: 1273: if(elapsed >= seconds) break;
  749. # #####: 1274: }
  750. # #####: 1275: return vm->None;
  751. # #####: 1276: });
  752. # test time.sleep
  753. time.sleep(0.1)
  754. # 未完全测试准确性-----------------------------------------------
  755. # 116: 1278: vm->bind_func<0>(mod, "localtime", [](VM* vm, ArgsView args) {
  756. # #####: 1279: auto now = std::chrono::system_clock::now();
  757. # #####: 1280: std::time_t t = std::chrono::system_clock::to_time_t(now);
  758. # #####: 1281: std::tm* tm = std::localtime(&t);
  759. # #####: 1282: Dict d(vm);
  760. # #####: 1283: d.set(VAR("tm_year"), VAR(tm->tm_year + 1900));
  761. # #####: 1284: d.set(VAR("tm_mon"), VAR(tm->tm_mon + 1));
  762. # #####: 1285: d.set(VAR("tm_mday"), VAR(tm->tm_mday));
  763. # #####: 1286: d.set(VAR("tm_hour"), VAR(tm->tm_hour));
  764. # #####: 1287: d.set(VAR("tm_min"), VAR(tm->tm_min));
  765. # #####: 1288: d.set(VAR("tm_sec"), VAR(tm->tm_sec + 1));
  766. # #####: 1289: d.set(VAR("tm_wday"), VAR((tm->tm_wday + 6) % 7));
  767. # #####: 1290: d.set(VAR("tm_yday"), VAR(tm->tm_yday + 1));
  768. # #####: 1291: d.set(VAR("tm_isdst"), VAR(tm->tm_isdst));
  769. # #####: 1292: return VAR(std::move(d));
  770. # #####: 1293: });
  771. # 58: 1294:}
  772. # test time.localtime
  773. assert type(time.localtime()) is time.struct_time
  774. # /************ module dis ************/
  775. import dis
  776. # 116: 1487: vm->bind_func<1>(mod, "dis", [](VM* vm, ArgsView args) {
  777. # #####: 1488: CodeObject_ code = get_code(vm, args[0]);
  778. # #####: 1489: vm->_stdout(vm, vm->disassemble(code));
  779. # #####: 1490: return vm->None;
  780. # #####: 1491: });
  781. # test dis.dis
  782. def aaa():
  783. pass
  784. assert dis.dis(aaa) is None
  785. # test min/max
  786. assert min(1, 2) == 1
  787. assert min(1, 2, 3) == 1
  788. assert min([1, 2]) == 1
  789. assert min([1, 2], key=lambda x: -x) == 2
  790. assert max(1, 2) == 2
  791. assert max(1, 2, 3) == 3
  792. assert max([1, 2]) == 2
  793. assert max([1, 2], key=lambda x: -x) == 1
  794. assert min([
  795. (1, 2),
  796. (1, 3),
  797. (1, 4),
  798. ]) == (1, 2)
  799. # test callable
  800. assert callable(lambda: 1) is True # function
  801. assert callable(1) is False # int
  802. assert callable(object) is True # type
  803. assert callable(object()) is False
  804. assert callable([].append) is True # bound method
  805. assert callable([].__getitem__) is True # bound method
  806. class A:
  807. def __init__(self):
  808. pass
  809. def __call__(self):
  810. pass
  811. assert callable(A) is True # type
  812. assert callable(A()) is True # instance with __call__
  813. assert callable(A.__call__) is True # bound method
  814. assert callable(A.__init__) is True # bound method
  815. assert callable(print) is True # builtin function
  816. assert callable(isinstance) is True # builtin function
  817. assert id(0) is None
  818. assert id(2**62) is not None