99_builtin_func.py 33 KB

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