99_builtin_func.py 43 KB

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