开源 企业版 高校版 私有云 模力方舟 AI 队友
代码拉取完成,页面将自动刷新
捐赠
捐赠前请先登录
扫描微信二维码支付
取消
支付完成
支付提示
将跳转至支付宝完成支付
确定
取消
1 Star 2 Fork 1

APIJSON/UnitAuto

加入 Gitee
与超过 1400万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
已有帐号? 立即登录
文件
master
分支 (11)
标签 (14)
master
dependabot/maven/UnitAuto-SpringBoot-SDK/com.alibaba-fastjson-1.2.83
dependabot/maven/UnitAuto-Java-Demo/mysql-mysql-connector-java-8.0.28
dependabot/maven/UnitAuto-Jar/com.alibaba-fastjson-1.2.83
dependabot/maven/UnitAuto-Java/com.alibaba-fastjson-1.2.83
dependabot/maven/UnitAuto-Java-Demo/com.alibaba-fastjson-1.2.83
dependabot/maven/UnitAuto-Java-Demo/mysql-mysql-connector-java-8.0.16
dependabot/maven/UnitAuto-Java-SpringBoot/mysql-mysql-connector-java-8.0.16
dependabot/maven/Demo/UnitAuto-Java-SpringBoot/mysql-mysql-connector-java-8.0.16
dependabot/maven/UnitAutoBoot/mysql-mysql-connector-java-8.0.16
dependabot/maven/UnitAuto-Backend/UnitAutoBoot/mysql-mysql-connector-java-8.0.16
3.0.0
2.9.5
2.9.0
2.8.1
2.7.3
2.7.2
2.6.4
2.6.3
2.6.0
2.5.0
2.4.0
2.0.0
1.0.3
1.0.0
master
分支 (11)
标签 (14)
master
dependabot/maven/UnitAuto-SpringBoot-SDK/com.alibaba-fastjson-1.2.83
dependabot/maven/UnitAuto-Java-Demo/mysql-mysql-connector-java-8.0.28
dependabot/maven/UnitAuto-Jar/com.alibaba-fastjson-1.2.83
dependabot/maven/UnitAuto-Java/com.alibaba-fastjson-1.2.83
dependabot/maven/UnitAuto-Java-Demo/com.alibaba-fastjson-1.2.83
dependabot/maven/UnitAuto-Java-Demo/mysql-mysql-connector-java-8.0.16
dependabot/maven/UnitAuto-Java-SpringBoot/mysql-mysql-connector-java-8.0.16
dependabot/maven/Demo/UnitAuto-Java-SpringBoot/mysql-mysql-connector-java-8.0.16
dependabot/maven/UnitAutoBoot/mysql-mysql-connector-java-8.0.16
dependabot/maven/UnitAuto-Backend/UnitAutoBoot/mysql-mysql-connector-java-8.0.16
3.0.0
2.9.5
2.9.0
2.8.1
2.7.3
2.7.2
2.6.4
2.6.3
2.6.0
2.5.0
2.4.0
2.0.0
1.0.3
1.0.0
克隆/下载
克隆/下载
提示
下载代码请复制以下命令到终端执行
为确保你提交的代码身份被 Gitee 正确识别,请执行以下命令完成配置
初次使用 SSH 协议进行代码克隆、推送等操作时,需按下述提示完成 SSH 配置
1 生成 RSA 密钥
2 获取 RSA 公钥内容,并配置到 SSH公钥
在 Gitee 上使用 SVN,请访问 使用指南
使用 HTTPS 协议时,命令行会出现如下账号密码验证步骤。基于安全考虑,Gitee 建议 配置并使用私人令牌 替代登录密码进行克隆、推送等操作
Username for 'https://gitee.com': userName
Password for 'https://userName@gitee.com': # 私人令牌
master
分支 (11)
标签 (14)
master
dependabot/maven/UnitAuto-SpringBoot-SDK/com.alibaba-fastjson-1.2.83
dependabot/maven/UnitAuto-Java-Demo/mysql-mysql-connector-java-8.0.28
dependabot/maven/UnitAuto-Jar/com.alibaba-fastjson-1.2.83
dependabot/maven/UnitAuto-Java/com.alibaba-fastjson-1.2.83
dependabot/maven/UnitAuto-Java-Demo/com.alibaba-fastjson-1.2.83
dependabot/maven/UnitAuto-Java-Demo/mysql-mysql-connector-java-8.0.16
dependabot/maven/UnitAuto-Java-SpringBoot/mysql-mysql-connector-java-8.0.16
dependabot/maven/Demo/UnitAuto-Java-SpringBoot/mysql-mysql-connector-java-8.0.16
dependabot/maven/UnitAutoBoot/mysql-mysql-connector-java-8.0.16
dependabot/maven/UnitAuto-Backend/UnitAutoBoot/mysql-mysql-connector-java-8.0.16
3.0.0
2.9.5
2.9.0
2.8.1
2.7.3
2.7.2
2.6.4
2.6.3
2.6.0
2.5.0
2.4.0
2.0.0
1.0.3
1.0.0
methodutil.py 37.49 KB
一键复制 编辑 原始数据 按行查看 历史
TommyLemon 提交于 2023年08月08日 18:15 +08:00 . 更新 Go 版 和 Python 版源码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148
# encoding=utf-8
# MIT License
#
# Copyright (c) 2023 TommyLemon
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
import asyncio
import builtins
import json
import os
import re
import time
import inspect
import types
import typing
from typing import Type
null = None
false = False
true = True
KEY_OK = 'ok'
KEY_CODE = 'code'
KEY_MSG = 'msg'
KEY_THROW = 'throw'
KEY_TRACE = 'trace'
CODE_SUCCESS = 200
CODE_SERVER_ERROR = 500
MSG_SUCCESS = 'success'
LANGUAGE = 'Python'
KEY_LANGUAGE = "language"
KEY_REUSE = "reuse"
KEY_UI = "ui"
KEY_TIME = "time"
KEY_TIMEOUT = "timeout"
KEY_PACKAGE = "package"
KEY_THIS = "this"
KEY_CLASS = "class"
KEY_CONSTRUCTOR = "constructor"
KEY_KEY = "key"
KEY_TYPE = "type"
KEY_AT_TYPE = "@type"
KEY_VALUE = "value"
KEY_WARN = "warn"
KEY_STATIC = "static"
KEY_ASYNC = "async"
KEY_NAME = "name"
KEY_METHOD = "method"
KEY_MOCK = "mock"
KEY_QUERY = "query"
KEY_DEPTH = "depth"
KEY_RETURN = "return"
KEY_TIME_DETAIL = "time:start|duration|end"
KEY_CLASS_ARGS = "classArgs"
KEY_METHOD_ARGS = "methodArgs"
KEY_ARGS = "args"
KEY_CALLBACK = "callback"
KEY_GLOBAL = "global"
KEY_CALL_LIST = "call()[]"
KEY_CALL_MAP = "call(){}"
KEY_PACKAGE_TOTAL = "packageTotal"
KEY_CLASS_TOTAL = "classTotal"
KEY_METHOD_TOTAL = "methodTotal"
KEY_PACKAGE_LIST = "packageList"
KEY_CLASS_LIST = "classList"
KEY_METHOD_LIST = "methodList"
MILLIS_TIME = 1000000
PATTERN_ALPHABET = re.compile('^[A-Za-z]+$')
PATTERN_UPPER_ALPHABET = re.compile('^[A-Z]+$')
PATTERN_LOWER_ALPHABET = re.compile('^[a-z]+$')
PATTERN_NUMBER = re.compile('^[0-9]+$')
PATTERN_NAME = re.compile('^[A-Za-z0-9_]+$')
class Config:
DEFAULT_MODULE_PATH: str = ''
config = Config()
PRIMITIVE_CLASS_MAP = {
None: any,
'None': any,
'any': any,
'bool': bool,
'False': bool,
'True': bool,
'int': int,
'float': float,
'str': str
}
CLASS_MAP = dict(PRIMITIVE_CLASS_MAP, **{
'object': object,
'list': list,
'tuple': tuple,
'range': range,
'slice': slice,
'set': set,
'reversed': reversed,
'dict': dict,
'map': map,
'bytes': bytes,
'bytearray': bytearray,
'frozenset': frozenset,
'enumerate': enumerate,
'filter': filter,
'complex': complex,
'Exception': Exception,
'BaseException': BaseException,
'OSError': OSError,
'IOError': IOError,
'BlockingIOError': BlockingIOError,
'EnvironmentError': EnvironmentError,
'ConnectionError': ConnectionError,
'BrokenPipeError': BrokenPipeError,
'BufferError': BufferError,
'EOFError': EOFError,
'SyntaxError': SyntaxError,
'FileExistsError': FileExistsError,
'FileNotFoundError': FileNotFoundError,
'Warning': Warning,
'BytesWarning': BytesWarning,
'ChildProcessError': ChildProcessError,
'property': property,
'classmethod': classmethod,
'staticmethod': staticmethod,
'super': super,
'type': type,
'zip': zip,
})
class InterfaceProxy:
pass
INSTANCE_MAP = {}
def get_instance(
clazz, value: any = null, constructor: callable = null, class_args: list = null,
reuse: bool = false, module=null, import_fun: callable = null
):
reuse = reuse or false
key = str(clazz) + ('' if is_none(constructor) else '.' + str(constructor))\
+ '(' + str(class_args) + ')' if reuse else null
instance = INSTANCE_MAP[key] if reuse else null
if is_none(instance):
cal = size(class_args)
ca_keys = [null] * cal
ca_types = [null] * cal
ca_values = [null] * cal
c_kwargs = {}
init_args(class_args, ca_keys, ca_types, ca_values, c_kwargs, import_fun=import_fun)
if constructor is None:
instance = clazz(*ca_values, **c_kwargs)
else:
try:
instance = constructor(*ca_values, **c_kwargs)
except Exception as e:
print(e)
try:
instance = clazz.constructor(*ca_values, **c_kwargs) # @staticmethod in class
except Exception as e2:
raise Exception(
str(module) + ' does not have such a function, and ' + str(clazz)
+ ' does not have a @staticmethod called ' + str(constructor)
+ '! ' + str(e) + '; ' + str(e2)
)
if reuse and not_none(instance):
INSTANCE_MAP[key] = instance
return instance
def on_complete(data: any, method: callable, proxy: InterfaceProxy, *extras: any):
pass
def on_callback(data: any, method: callable, proxy: InterfaceProxy, *extras: any):
pass
class Listener:
complete: callable = on_complete
callback: callable = on_callback
getinstance: callable = get_instance
listener = Listener()
def list_method(req, import_fun: callable = null) -> dict:
start_time = cur_time_in_millis()
try:
if is_str(req):
req = parse_json(req)
mock = req.get(KEY_MOCK)
assert mock in [null, true, false], KEY_MOCK + ' must be in [true, false]!'
query = req.get(KEY_QUERY)
assert query in [null, 0, 1, 2], KEY_QUERY + ' must be in [0, 1, 2]! 0-Data, 1-Total count, 2-Both above'
depth = req.get(KEY_DEPTH)
assert is_int(depth, false), KEY_DEPTH + ' must be int!'
package = req.get(KEY_PACKAGE)
assert is_str(package), KEY_PACKAGE + ' must be str!'
clazz = req.get(KEY_CLASS)
assert is_str(clazz), KEY_CLASS + ' must be str!'
method = req.get(KEY_METHOD)
assert is_str(method), KEY_METHOD + ' must be str!'
types = req.get('types')
assert is_list(types), 'types must be list!'
is_all_pkg = is_empty(package)
is_all_cls = is_empty(clazz)
is_all_mtd = is_empty(method)
fl = split(clazz, '$')
module_list = []
import_fun = import_fun or __import__
depth = depth or 0
d = 0
for root, dirs, files in os.walk(package.replace('.', '/')):
d += 1
if depth > 0 and d > depth:
break
# for name in dirs:
# m = import_fun(('' if is_empty(root) else root.replace('/', '.') + '.') + name.replace('/', '.'), fromlist=['__init__'])
# if not_none(m) and not module_list.__contains__(m):
# module_list.append(m)
for name in files:
if size(name) <= 3 or not name.endswith('.py'):
continue
name = name[:-3]
p = os.path.join(root, name).replace('/', '.')
m = import_fun(p, fromlist=name)
if is_none(m) or module_list.__contains__(m) or m in module_list:
continue
module_list.append(m)
if is_empty(module_list):
try:
mn = package if is_empty(fl) else package + '.' + fl[0]
root_module = import_fun(mn, fromlist=['__init__'] if is_empty(fl) else fl[0])
module_list.append(root_module)
mdl_dict = root_module.__dict__
vs = mdl_dict.values()
for v in vs:
if type(v).__name__ == 'module' and str(v).endswith("/__init__.py'>"): # if is_instance(v, module):
module_list.append(v)
pass
except Exception as e:
print(e)
pkg_list = []
for module_item in module_list:
cl = []
pkg = module_item.__name__
pkg_str = str(module_item)
is_file = pkg_str.endswith(".py'>") and not pkg_str.endswith("/__init__.py'>")
file_name = null
if is_file:
ns = split(pkg, '.') # 不存在这个函数 ind = last_index(pkg, '.')
file_name = ns[-1]
pkg = pkg[:-1-len(ns[-1])]
# module_item = import_fun(pkg)
# if module_item not in cl and not cl.__contains__(module_item):
cl.append(module_item)
if pkg.endswith('.__init__'):
pkg = pkg[:-len('.__init__')]
if is_empty(pkg):
continue
mdl_list = dir(module_item)
l = size(mdl_list)
cls_list = []
if l > 1 and not is_all_cls:
try:
cls = module_item
i = -1
for n in fl:
i += 1
if i <= 0:
continue
cls = getattr(cls, n)
cl = [cls]
except Exception as e:
print(e)
else:
for mdl in mdl_list:
pn = str(mdl)
if is_empty(pn) or pn.startswith('_') or pn.endswith('_'):
continue
try:
cls = getattr(module_item, pn)
cm = cls.__module__ if hasattr(cls, '__module__') else null
if is_empty(cm) or not cm.startswith(pkg):
continue
ct = type(cls).__name__
s = str(cls)
if ct == 'function':
if is_file:
continue
mtd = parse_method(cls, import_fun=import_fun) if is_all_mtd or cls.__name__ == method else null
if is_empty(mtd):
continue
cls_list.append({
KEY_CLASS: file_name,
KEY_METHOD_LIST: [mtd]
})
if ct == 'class' or ct == 'type':
if cls not in cl and not cl.__contains__(cls):
cl.append(cls)
elif ct == 'module':
if is_file or (s.endswith(".py'>") and not s.endswith("/__init__.py'>")):
if cls not in cl and not cl.__contains__(cls):
cl.append(cls)
# elif not (cls in module_list):
# module_list.append(cls)
except Exception as e:
print(e)
for cls in cl:
cn = cls.__name__
cs = str(cls).strip() # 一样 cs = cls.__str__()
ind = index(cs, "'")
if ind >= 0:
cs = cs[ind + 1:]
ind = index(cs, "'")
if ind >= 0:
cs = cs[:ind]
if not cs.startswith(pkg + '.'):
continue
cs = cs[len(pkg + '.'):]
if is_empty(cs):
continue
if true:
ml = []
if callable(cls) and type(cls).__name__ == 'function':
if is_all_mtd or cn == method:
ml = [cls]
else:
continue
elif not is_all_mtd:
try:
func = getattr(cls, method)
if callable(func) and type(func).__name__ == 'function':
ml = [func]
except Exception as e:
print(e)
else:
ns = dir(cls)
if not_empty(ns):
for n in ns:
if is_empty(n) or n.startswith('_') or n.endswith('_'):
continue
try:
func = getattr(cls, n)
if callable(func):
ft = type(func).__name__
if ft == 'function':
ml.append(func)
# elif ft in ('type', 'class') and str(func) == ("<class '" + cn + "." + func.__name__ + "'>"):
# cl.append(func)
except Exception as e:
print(e)
# cls.__class__.methods
mtd_list = []
for mtd in ml:
m = parse_method(mtd, import_fun=import_fun)
if not_empty(m):
mtd_list.append(m)
# 不存在这个函数 ind = cn.lastindex('.')
# <module 'unitauto.test.testutil' from 'unitauto/test/testutil.py'>
# if cs.startswith("class <'"):
# cs = cs[len("class <'"):]
# if cs.endswith("'>"):
# cs = cs[:-len("'>")]
if is_empty(mtd_list):
continue
cls_list.append({
# KEY_CLASS: cn if ind < 0 else cn[ind+1:],
KEY_CLASS: cs.replace('.', '$'),
KEY_METHOD_LIST: mtd_list
})
if is_empty(cls_list):
continue
pkg_list.append({
KEY_PACKAGE: pkg,
KEY_CLASS_LIST: cls_list
})
time_detail = get_time_detail(start_time)
return {
KEY_LANGUAGE: LANGUAGE,
KEY_OK: true,
KEY_CODE: CODE_SUCCESS,
KEY_MSG: MSG_SUCCESS,
KEY_PACKAGE_LIST: pkg_list,
KEY_TIME_DETAIL: time_detail
}
except Exception as e:
return {
KEY_LANGUAGE: LANGUAGE,
KEY_OK: false,
KEY_CODE: CODE_SERVER_ERROR,
KEY_MSG: str(e),
KEY_TIME_DETAIL: get_time_detail(start_time),
KEY_THROW: e.__class__.__name__,
# KEY_TRACE: e.__traceback__.__str__
}
def get_type_str_by_str(s: str, keep_prefix: bool = false, import_fun: callable = null) -> str:
start = s.index("'") if is_contain(s, "'") else -1
if start >= 0:
s = s[start + 1:]
end = s.index("'") if is_contain(s, "'") else -1
if end >= 0:
s = s[:end]
s = s.strip()
if s in (null, '', '_empty', 'inspect._empty', 'NoneType', 'POSITIONAL_OR_KEYWORD'):
return null
dmp = null if keep_prefix else config.DEFAULT_MODULE_PATH
if not_empty(dmp) and s.startswith(dmp):
s = s[len(dmp) + 1:]
# if s.startswith('__init__.'):
# return s[len('__init__.'):]
s = s.replace('.__init__.', '$')
if '$' not in s and '.' in s:
ks = split(s, '.')
# util.Test.Test2 会误判为 util.Test$Test2,实际应该为 util$Test.Test2 s = '.'.join(ks[:-1]) + '$' + ks[-1]
ns = ks[0]
ks = ks[1:]
is_inner_cls = false
for k in ks:
if (not is_inner_cls) and not is_module_path(ns + '.' + k, import_fun): # is_big_name(k)
is_inner_cls = true
ns += ('$' if is_inner_cls else '.') + k
return ns
return s
def is_module_path(path: str, import_fun: callable = null) -> bool:
try:
import_fun = import_fun or __import__
m = import_fun(path)
return not_none(m)
except Exception as e:
print(e)
return false
def get_type_str(return_annotation, instance: any = null, keep_prefix: bool = false, import_fun: callable = null) -> str:
rt = get_type_str_by_str(str(return_annotation), keep_prefix=keep_prefix, import_fun=import_fun)
if is_empty(rt):
rt = get_type_str_by_str(str(type(instance)), keep_prefix=keep_prefix, import_fun=import_fun)
return rt
def parse_method(func, import_fun: callable = null) -> dict:
signature = null if func is None else inspect.signature(func)
if signature is None:
return {}
return_annotation = signature.return_annotation
rt = get_type_str(return_annotation, keep_prefix=true, import_fun=import_fun)
types = []
for param in signature.parameters.values():
a = null if param is None else param.annotation
n = null
if a is not None:
try:
n = a.__name__
except Exception as e:
n = str(a)
types.append('any' if is_empty(n) or n in ('_empty', 'POSITIONAL_OR_KEYWORD') else n)
names = [param.name for param in signature.parameters.values()]
static = is_empty(names) or names[0] != 'self'
name = func.__name__
return {
KEY_STATIC: static,
'returnType': rt,
'genericReturnType': rt,
KEY_METHOD: name,
KEY_NAME: name,
'parameterTypeList': types if static else types[1:],
'genericParameterTypeList': types if static else types[1:],
'parameterNameList': names if static else names[1:],
'parameterDefaultValueList': null
}
def wrap_result(
instance, func, method_args, ma_types, ma_values, result, start_time,
json_dumps: callable = null, json_loads: callable = null, import_fun: callable = null
):
time_detail = get_time_detail(start_time)
signature = inspect.signature(func)
return_annotation = null if signature is None else signature.return_annotation
rt = get_type_str(return_annotation, result, import_fun=import_fun)
mal = size(method_args)
mas = [null] * mal
json_dumps = json_dumps or json.dumps
if mal > 0: # bug 要及时发现 and size(ma_values) == mal:
i = -1
for v in ma_values:
i += 1
if callable(v):
mas[i] = method_args[i]
continue
t = ma_types[i]
try:
json_dumps(v)
except Exception as e:
print(e)
v = str(v)
mas[i] = {
KEY_TYPE: t.__name__ if t is not None else type(v),
KEY_VALUE: v
}
if is_none(instance):
if result is None and is_empty(rt):
return {
KEY_LANGUAGE: LANGUAGE,
KEY_OK: true,
KEY_CODE: CODE_SUCCESS,
KEY_MSG: MSG_SUCCESS,
KEY_METHOD_ARGS: mas,
KEY_TIME_DETAIL: time_detail
}
return {
KEY_LANGUAGE: LANGUAGE,
KEY_OK: true,
KEY_CODE: CODE_SUCCESS,
KEY_MSG: MSG_SUCCESS,
KEY_TYPE: rt,
KEY_RETURN: result,
KEY_METHOD_ARGS: mas,
KEY_TIME_DETAIL: time_detail
}
cls = type(instance)
this = {
KEY_TYPE: cls.__name__,
}
json_loads = json_loads or json.loads
try:
json_dumps(instance)
this[KEY_VALUE] = instance
except Exception as e:
print(e)
try:
this[KEY_VALUE] = json_loads(json_dumps(instance, cls=cls))
except Exception as e2:
print(e2)
try:
this[KEY_VALUE] = json_loads(instance.encode(null))
except Exception as e3:
print(e3) # FIXME instance.__dict__ , dir(instance)
this[KEY_VALUE] = str(instance)
this[KEY_WARN] = str(e)
if result is None and is_empty(rt):
return {
KEY_LANGUAGE: LANGUAGE,
KEY_OK: true,
KEY_CODE: CODE_SUCCESS,
KEY_MSG: MSG_SUCCESS,
KEY_METHOD_ARGS: mas,
KEY_THIS: this,
KEY_TIME_DETAIL: time_detail
}
return {
KEY_LANGUAGE: LANGUAGE,
KEY_OK: true,
KEY_CODE: CODE_SUCCESS,
KEY_MSG: MSG_SUCCESS,
KEY_TYPE: rt,
KEY_RETURN: result,
KEY_METHOD_ARGS: mas,
KEY_THIS: this,
KEY_TIME_DETAIL: time_detail
}
def invoke_method(
req: any, callback: callable = null, getinstance: callable = null,
json_dumps: callable = null, json_loads: callable = null, import_fun: callable = null
) -> dict:
start_time = time.time_ns()
is_wait = false
try:
getinstance = getinstance or get_instance
json_dumps = json_dumps or to_json_str
json_loads = json_loads or parse_json
import_fun = import_fun or __import__
assert is_none(callback) or callable(callback)
if is_str(req):
req = json_loads(req)
reuse = req.get(KEY_REUSE)
assert is_bool(reuse), (KEY_REUSE + ' must be bool!')
static = req.get(KEY_STATIC)
assert is_bool(static), (KEY_STATIC + ' must be bool!')
is_async = req.get(KEY_ASYNC)
assert is_bool(is_async), (KEY_ASYNC + ' must be bool!')
package = req.get(KEY_PACKAGE)
assert is_str(package), (KEY_PACKAGE + ' must be str!')
clazz = req.get(KEY_CLASS)
assert is_str(clazz), (KEY_CLASS + ' must be str!')
method = req.get(KEY_METHOD)
assert is_str(method), (KEY_METHOD + ' must be str!')
assert not_empty(method), (KEY_CLASS + ' method be empty!')
class_args = req.get(KEY_CLASS_ARGS)
assert is_list(class_args), (KEY_CLASS_ARGS + ' must be list!')
args = req.get(KEY_ARGS)
assert is_list(args), (KEY_ARGS + ' must be list!')
method_args = req.get(KEY_METHOD_ARGS)
assert is_list(method_args), (KEY_METHOD_ARGS + ' must be list!')
assert args is None or method_args is None, (KEY_ARGS + ', ' + KEY_METHOD_ARGS + ' cannot both be not null!')
constructor = req.get(KEY_CONSTRUCTOR)
assert is_str(constructor), (KEY_CONSTRUCTOR + ' must be str!')
this = req.get(KEY_THIS)
assert is_dict(this), (KEY_THIS + ' must be dict!')
instance = None
if this is not None:
assert not static, KEY_STATIC + ' cannot appear together with ' + KEY_THIS + '!'
assert class_args is None, KEY_THIS + ' cannot appear together with ' + KEY_CLASS_ARGS + '!'
assert constructor is None, KEY_THIS + ' cannot appear together with ' + KEY_CONSTRUCTOR + '!'
this_keys = [null]
this_types = [null]
this_values = [null]
this_kwargs = {}
init_args([this], this_keys, this_types, this_values, this_kwargs, import_fun=import_fun)
instance = this_values[0]
if class_args is not None:
assert not static, KEY_CLASS_ARGS + ' cannot appear together with ' + KEY_STATIC + '!'
assert this is None, KEY_CLASS_ARGS + ' cannot appear together with ' + KEY_THIS + '!'
method_args = method_args or args
mal = size(method_args)
ma_keys = [null] * mal
ma_types = [null] * mal
ma_values = [null] * mal
m_kwargs = {}
final_result = {}
def final_callback(*args, **kwargs):
if not_none(callback): # callable(callback):
callback(wrap_result(
final_result.get(KEY_THIS), func, method_args, ma_types, ma_values,
final_result.get(KEY_VALUE), start_time, import_fun=import_fun
))
is_wait = init_args(method_args, ma_keys, ma_types, ma_values, m_kwargs, true, final_callback, import_fun=import_fun)
fl = split(clazz, '$')
l = size(fl)
mn = package if l <= 0 else package + '.' + fl[0]
module = import_fun(mn, fromlist=['__init__'] if l <= 0 else fl[0])
cls: any = null
if l > 1:
i = -1
m = module
for n in fl:
i += 1
if i <= 0:
continue
# if i > 1:
# n = 'Test$InnerTest' # 'Test.InnerTest'
# # 'Test' object has no attribute 'InnerTest' # m = m()
m = getattr(m, n) # FIXME Test.InnerTest raise Exception: type object 'Test' has no attribute 'InnerTest'
cls = m
# 'testutil' object has no attribute 'Test.InnerTest' cls = getattr(module, '.'.join(fl[1:]))
# 'testutil' object has no attribute 'Test.InnerTest' cls = getattr(module, '$'.join(fl[1:]))
if cls is None:
func = getattr(module, method)
elif static:
func = getattr(cls, method)
else:
if instance is None:
constructor_func = None if is_empty(constructor) else getattr(module, constructor)
instance = getinstance(
cls, null, constructor_func, class_args, reuse=reuse, module=module, import_fun=import_fun
)
func = getattr(instance, method)
final_result[KEY_THIS] = instance
ksl = size(m_kwargs)
start_time = cur_time_in_millis()
result = func(*ma_values[:mal - ksl], **m_kwargs) # asyncio.run 只允许调 async 函数 is_async != false
# 自动识别 async 关键词
is_async = is_async or (is_async is None and is_instance(result, (types.CoroutineType, types.AsyncGeneratorType)))
if is_async:
result = asyncio.run(result)
final_result[KEY_VALUE] = result
res = wrap_result(
instance, func, method_args, ma_types, ma_values, result, start_time,
json_dumps=json_dumps, json_loads=json_loads, import_fun=import_fun
)
except Exception as e:
res = {
KEY_LANGUAGE: LANGUAGE,
KEY_OK: false,
KEY_CODE: CODE_SERVER_ERROR,
KEY_MSG: str(e),
KEY_TIME_DETAIL: get_time_detail(start_time),
KEY_THROW: e.__class__.__name__,
# KEY_TRACE: e.__traceback__.__str__()
}
if (not is_wait) and callable(callback):
callback(res)
return res
def init_args(
method_args: list, ma_keys: list, ma_types: list, ma_values: list,
ma_kwargs: dict, keep_kwargs_in_types_and_values: bool = false,
callback: callable = null, import_fun: callable = null
):
is_wait = false
mal = size(method_args)
if mal > 0:
i = -1
for arg in method_args:
i += 1
value = null
is_fun = false
if is_str(arg) and (arg.__contains__(':') or arg.__contains__('=')):
ind = index(arg, ':')
eq_ind = index(arg, '=')
key = (arg[:eq_ind] if ind < 0 else arg[ind+1:eq_ind]) if eq_ind >= 0 else null
typ = arg[:ind] if ind >= 0 else null
# ma_types.append(arg[:ind] if ind >= 0 else 'str')
value = arg[eq_ind+1:] if eq_ind >= 0 else (arg[ind+1:] if ind >= 0 else arg)
# ma_values.append(arg[ind + 1:] if ind >= 0 else arg)
else:
id = is_dict(arg)
key = arg.get(KEY_KEY) if id else null
typ = arg.get(KEY_TYPE) if id else null
# ma_types.append(arg.get(KEY_TYPE) if id else type(arg))
value = arg.get(KEY_VALUE) if id else arg
# ma_values.append(arg.get(KEY_VALUE) if id else arg)
start = index(typ, '(')
end = last_index(typ, ')')
if start >= 0 and end > start: # 命名函数 或 lambda 匿名函数
assert is_dict(value, true), '{"type": "def(arg0,arg1...)", "value": value} 中 value 类型错误,' \
'必须为 dict!且格式必须为 {"type": returnType, "return": returnValue, "callback": bool}'
cb = value.get(KEY_CALLBACK)
assert is_bool(cb, false), '{"type": "def(arg0,arg1...)", "value": {"callback": bool}} 中' \
' value/callback 类型错误,必须为 true 或 false !'
is_fun = true
is_wait = is_wait or cb
fun = typ[:start] if start > 0 else null
# assert is_none(fun) or is_name(fun), '{"type": "fun(arg0,arg1...)"} 必须是函数名,或者关键词 def '
assert fun == 'def', '{"type": "fun(arg0,arg1...)"} 必须是函数名,或者关键词 def '
aks = split(typ[start+1:end])
akl = size(aks)
fa_types = [null] * akl
fa_keys = [null] * akl
for j in range(akl):
ak = aks[j]
ak_ind = index(ak, ':')
fa_types[j] = null if ak_ind < 0 else ak[:ak_ind]
fa_keys[j] = ak if ak_ind < 0 else ak[ak_ind+1:]
rtn_type = value.get(KEY_TYPE)
rtn_val = value.get(KEY_RETURN)
raw_val: dict = value
def cb_fun(*args, **kwargs):
mas: list = []
if not_empty(args):
for arg in args:
mas.append({
KEY_TYPE: type(arg).__name__,
KEY_VALUE: arg
})
if not_empty(kwargs):
for k in kwargs:
v = kwargs[k]
mas.append({
KEY_KEY: k,
KEY_TYPE: type(v).__name__,
KEY_VALUE: v
})
call_list: list = raw_val.get(KEY_CALL_LIST) or []
call_list.append({
KEY_TIME: cur_time_in_millis(),
KEY_METHOD_ARGS: mas
})
raw_val[KEY_CALL_LIST] = call_list
if cb:
callback(*args, **kwargs)
rv = rtn_val
if is_str(rv, true):
try:
fn = '__unitauto_return_' + str(i) + '__'
to_eval = 'def ' + fn + '('
k = 0
first = true
for ak in fa_keys:
if ak in kwargs:
arg = kwargs.get(ak)
else:
arg = args[k]
k += 1
to_eval += ('' if first else ', ') + ak + '=' + str(arg)
first = false
# to_eval += ak + ' = ' + str(arg) + ';'
# exec(ak + ' = ' + str(arg))
to_eval += '):\n return ' + rv
exec(to_eval)
# to_eval += rv
nrv = eval(fn + '()') # eval(rv) # eval(to_eval) # exec(to_eval)
return cast(nrv, get_class(rtn_type, nrv))
except Exception as e:
print(e)
return cast(rv, get_class(rtn_type, rv))
value = cb_fun # eval('lambda ' + ', '.join(fa_keys) + ': ' + str(rtn_val))
clazz = type(value) if is_fun else get_class(typ, value, import_fun)
value = cast(value, clazz) if not is_fun else value
ma_keys[i] = key
if is_none(key):
if is_empty(ma_kwargs):
ma_types[i] = clazz
ma_values[i] = value
continue
raise Exception('所有已经有 key 的参数,必须后面也跟着有 key,对应调用 fun(key=value, key2=value2...) !')
assert key not in ma_kwargs, '调函数传参,所有 key 不允许重名!必须有唯一的不同名称!'
ma_kwargs[key] = value
if keep_kwargs_in_types_and_values:
ma_types[i] = clazz
ma_values[i] = value
else:
del ma_types[-1]
del ma_values[-1]
return is_wait
def cast(value, clazz, json_dumps: callable = null, json_loads: callable = null):
if value is not None and not is_instance(value, clazz):
json_dumps = json_dumps or json.dumps
json_loads = json_loads or json.loads
s = ''
try:
s = value if is_str(value) else json_dumps(value)
if PRIMITIVE_CLASS_MAP.__contains__(clazz.__name__):
value = eval(clazz.__name__ + '(' + s + ')')
else:
value = json_loads(s, cls=clazz) # FIXME 目前仅支持继承 JSONDecoder 且重写了 decode 方法的类
except Exception as e:
print(e)
if is_str(value):
value = json_loads(value)
if not is_instance(value, clazz):
if is_list(value):
value = clazz(*value)
elif is_dict(value):
value = clazz(**value) # FIXME 目前仅支持继承 __init__ 传完整参数且顺序一致的类
else:
pass
return value
def get_class(typ: str, value: any = None, import_fun: callable = null) -> Type:
fl = split(typ, '$')
if is_empty(fl):
return type(value)
import_fun = import_fun or __import__
path = typ
clazz = CLASS_MAP.get(path)
if clazz is None:
fl = split(path, '$')
pkg = fl[0]
pl = split(pkg, '.')
end = size(pl) - 1
cn = null if end < 0 else pl[end]
# pkg = pkg[:-len(cn)]
l = size(fl)
mn = fl[0] # pkg if is_empty(fl) else pkg + '.' + cn
module = import_fun(mn, fromlist=cn)
if l <= 1:
clazz = getattr(module, cn)
else:
j = -1
for n in fl:
j += 1
if j <= 0:
continue
clazz = getattr(module, n)
CLASS_MAP[path] = clazz
return clazz
def split(s: str, seperator: str = ',') -> list:
if s is None:
return null
if is_contain(s, seperator):
return s.split(seperator)
return [s]
def is_contain(s: str, seperator: str = ',') -> bool:
return false if is_empty(s) else seperator in s # s.__contains__(seperator)
def is_bool(obj, strict: bool = false) -> bool:
return (not strict) if obj is None else is_instance(obj, bool)
def is_int(obj, strict: bool = false) -> bool:
return (not strict) if obj is None else is_instance(obj, int)
def is_float(obj, strict: bool = false) -> bool:
return (not strict) if obj is None else is_instance(obj, float)
def is_str(obj, strict: bool = false) -> bool:
return (not strict) if obj is None else is_instance(obj, str)
def is_list(obj, strict: bool = false) -> bool:
return (not strict) if obj is None else is_instance(obj, list)
def is_dict(obj, strict: bool = false) -> bool:
return (not strict) if obj is None else is_instance(obj, dict)
def not_none(obj):
return not is_none(obj)
def is_none(obj):
return obj is None
def not_empty(obj) -> bool:
return not is_empty(obj)
def is_empty(obj) -> bool:
if obj is None:
return true
if is_int(obj) or is_float(obj):
return obj <= 0
return size(obj) <= 0
def is_instance(obj, typ):
if typ in [null, any, typing.Any]: # fix isinstance() arg 2 must be a type or tuple of types
return true
return isinstance(obj, typ)
def is_name(s: str) -> bool:
if is_empty(s) or PATTERN_NUMBER.match(s[:1]):
return false
return not_none(PATTERN_NAME.match(s))
def is_big_name(s: str) -> bool:
if is_empty(s) or not PATTERN_UPPER_ALPHABET.match(s[:1]):
return false
return not_none(PATTERN_NAME.match(s))
def size(obj) -> int:
if obj is None:
return 0
if is_bool(obj) or is_int(obj) or is_float(obj):
raise Exception('obj cannot be any one of [bool, int, float]!')
return len(obj)
def index(s: str, sub: str) -> int:
try:
return s.index(sub)
except Exception:
return -1
def last_index(s: str, sub: str) -> int:
ws = split(s, sub)
if size(ws) <= 1:
return -1
return size(s) - size(ws[-1]) - 1
def cur_time_in_millis() -> int:
return round(time.time_ns()/MILLIS_TIME)
def get_time_detail(start_time: int, end_time: int = 0):
if end_time is None or end_time <= 0:
end_time = cur_time_in_millis()
duration = end_time - start_time
return str(round(start_time)) + '|' + str(round(duration)) + '|' + str(round(end_time))
def parse_json(s: str):
return json.loads(s)
def to_json_str(obj, indent: int = 2) -> str:
return json.dumps(obj, ensure_ascii=false, indent=indent)
Loading...
举报
举报成功
我们将于2个工作日内通过站内信反馈结果给你!
请认真填写举报原因,尽可能描述详细。
请选择举报类型
取消
发送
误判申诉

此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。

如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。

取消
提交

简介

机器学习单元测试平台,零代码、全方位、自动化 测试 方法/函数 的正确性和可用性。本仓库为副本,请给原仓库右上角点亮 ⭐️ Star
取消

发行版

暂无发行版

贡献者

全部

近期动态

不能加载更多了
编辑仓库简介
简介内容
主页
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
JavaScript
1
https://gitee.com/APIJSON/UnitAuto.git
git@gitee.com:APIJSON/UnitAuto.git
APIJSON
UnitAuto
UnitAuto
master
点此查找更多帮助

搜索帮助

仓库举报
回到顶部
登录提示
该操作需登录 Gitee 帐号,请先登录后再操作。
立即登录
没有帐号,去注册

AltStyle によって変換されたページ (->オリジナル) /