@rowstile/cli-linux-x64 0.1.0-alpha.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (565) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +5 -0
  3. package/package.json +26 -0
  4. package/python/bin/python3.13 +0 -0
  5. package/python/bin/python3.13-config +122 -0
  6. package/python/lib/libpython3.13.so.1.0 +0 -0
  7. package/python/lib/libpython3.so +0 -0
  8. package/python/lib/python3.13/LICENSE.txt +277 -0
  9. package/python/lib/python3.13/__future__.py +147 -0
  10. package/python/lib/python3.13/__hello__.py +16 -0
  11. package/python/lib/python3.13/_aix_support.py +108 -0
  12. package/python/lib/python3.13/_android_support.py +192 -0
  13. package/python/lib/python3.13/_apple_support.py +66 -0
  14. package/python/lib/python3.13/_collections_abc.py +1187 -0
  15. package/python/lib/python3.13/_colorize.py +119 -0
  16. package/python/lib/python3.13/_compat_pickle.py +251 -0
  17. package/python/lib/python3.13/_compression.py +162 -0
  18. package/python/lib/python3.13/_ios_support.py +71 -0
  19. package/python/lib/python3.13/_markupbase.py +396 -0
  20. package/python/lib/python3.13/_opcode_metadata.py +343 -0
  21. package/python/lib/python3.13/_osx_support.py +579 -0
  22. package/python/lib/python3.13/_py_abc.py +147 -0
  23. package/python/lib/python3.13/_pydatetime.py +2640 -0
  24. package/python/lib/python3.13/_pydecimal.py +6356 -0
  25. package/python/lib/python3.13/_pyio.py +2714 -0
  26. package/python/lib/python3.13/_pylong.py +363 -0
  27. package/python/lib/python3.13/_pyrepl/__init__.py +19 -0
  28. package/python/lib/python3.13/_pyrepl/__main__.py +10 -0
  29. package/python/lib/python3.13/_pyrepl/_minimal_curses.py +68 -0
  30. package/python/lib/python3.13/_pyrepl/_threading_handler.py +74 -0
  31. package/python/lib/python3.13/_pyrepl/base_eventqueue.py +110 -0
  32. package/python/lib/python3.13/_pyrepl/commands.py +492 -0
  33. package/python/lib/python3.13/_pyrepl/completing_reader.py +295 -0
  34. package/python/lib/python3.13/_pyrepl/console.py +229 -0
  35. package/python/lib/python3.13/_pyrepl/curses.py +33 -0
  36. package/python/lib/python3.13/_pyrepl/fancy_termios.py +82 -0
  37. package/python/lib/python3.13/_pyrepl/historical_reader.py +419 -0
  38. package/python/lib/python3.13/_pyrepl/input.py +114 -0
  39. package/python/lib/python3.13/_pyrepl/keymap.py +213 -0
  40. package/python/lib/python3.13/_pyrepl/main.py +59 -0
  41. package/python/lib/python3.13/_pyrepl/mypy.ini +29 -0
  42. package/python/lib/python3.13/_pyrepl/pager.py +175 -0
  43. package/python/lib/python3.13/_pyrepl/reader.py +764 -0
  44. package/python/lib/python3.13/_pyrepl/readline.py +599 -0
  45. package/python/lib/python3.13/_pyrepl/simple_interact.py +180 -0
  46. package/python/lib/python3.13/_pyrepl/trace.py +21 -0
  47. package/python/lib/python3.13/_pyrepl/types.py +10 -0
  48. package/python/lib/python3.13/_pyrepl/unix_console.py +852 -0
  49. package/python/lib/python3.13/_pyrepl/unix_eventqueue.py +76 -0
  50. package/python/lib/python3.13/_pyrepl/utils.py +83 -0
  51. package/python/lib/python3.13/_pyrepl/windows_console.py +687 -0
  52. package/python/lib/python3.13/_pyrepl/windows_eventqueue.py +42 -0
  53. package/python/lib/python3.13/_sitebuiltins.py +91 -0
  54. package/python/lib/python3.13/_strptime.py +800 -0
  55. package/python/lib/python3.13/_sysconfigdata__linux_x86_64-linux-gnu.py +1079 -0
  56. package/python/lib/python3.13/_threading_local.py +120 -0
  57. package/python/lib/python3.13/_weakrefset.py +205 -0
  58. package/python/lib/python3.13/abc.py +188 -0
  59. package/python/lib/python3.13/antigravity.py +17 -0
  60. package/python/lib/python3.13/argparse.py +2690 -0
  61. package/python/lib/python3.13/ast.py +1865 -0
  62. package/python/lib/python3.13/asyncio/__init__.py +47 -0
  63. package/python/lib/python3.13/asyncio/__main__.py +211 -0
  64. package/python/lib/python3.13/asyncio/base_events.py +2086 -0
  65. package/python/lib/python3.13/asyncio/base_futures.py +67 -0
  66. package/python/lib/python3.13/asyncio/base_subprocess.py +312 -0
  67. package/python/lib/python3.13/asyncio/base_tasks.py +94 -0
  68. package/python/lib/python3.13/asyncio/constants.py +41 -0
  69. package/python/lib/python3.13/asyncio/coroutines.py +109 -0
  70. package/python/lib/python3.13/asyncio/events.py +885 -0
  71. package/python/lib/python3.13/asyncio/exceptions.py +62 -0
  72. package/python/lib/python3.13/asyncio/format_helpers.py +84 -0
  73. package/python/lib/python3.13/asyncio/futures.py +425 -0
  74. package/python/lib/python3.13/asyncio/locks.py +617 -0
  75. package/python/lib/python3.13/asyncio/log.py +7 -0
  76. package/python/lib/python3.13/asyncio/mixins.py +21 -0
  77. package/python/lib/python3.13/asyncio/proactor_events.py +891 -0
  78. package/python/lib/python3.13/asyncio/protocols.py +216 -0
  79. package/python/lib/python3.13/asyncio/queues.py +309 -0
  80. package/python/lib/python3.13/asyncio/runners.py +217 -0
  81. package/python/lib/python3.13/asyncio/selector_events.py +1328 -0
  82. package/python/lib/python3.13/asyncio/sslproto.py +929 -0
  83. package/python/lib/python3.13/asyncio/staggered.py +174 -0
  84. package/python/lib/python3.13/asyncio/streams.py +787 -0
  85. package/python/lib/python3.13/asyncio/subprocess.py +229 -0
  86. package/python/lib/python3.13/asyncio/taskgroups.py +278 -0
  87. package/python/lib/python3.13/asyncio/tasks.py +1121 -0
  88. package/python/lib/python3.13/asyncio/threads.py +26 -0
  89. package/python/lib/python3.13/asyncio/timeouts.py +185 -0
  90. package/python/lib/python3.13/asyncio/transports.py +337 -0
  91. package/python/lib/python3.13/asyncio/trsock.py +98 -0
  92. package/python/lib/python3.13/asyncio/unix_events.py +1550 -0
  93. package/python/lib/python3.13/asyncio/windows_events.py +906 -0
  94. package/python/lib/python3.13/asyncio/windows_utils.py +181 -0
  95. package/python/lib/python3.13/base64.py +628 -0
  96. package/python/lib/python3.13/bdb.py +973 -0
  97. package/python/lib/python3.13/bisect.py +118 -0
  98. package/python/lib/python3.13/bz2.py +352 -0
  99. package/python/lib/python3.13/cProfile.py +197 -0
  100. package/python/lib/python3.13/calendar.py +813 -0
  101. package/python/lib/python3.13/cmd.py +409 -0
  102. package/python/lib/python3.13/code.py +386 -0
  103. package/python/lib/python3.13/codecs.py +1132 -0
  104. package/python/lib/python3.13/codeop.py +155 -0
  105. package/python/lib/python3.13/collections/__init__.py +1603 -0
  106. package/python/lib/python3.13/colorsys.py +166 -0
  107. package/python/lib/python3.13/compileall.py +470 -0
  108. package/python/lib/python3.13/concurrent/__init__.py +1 -0
  109. package/python/lib/python3.13/concurrent/futures/__init__.py +54 -0
  110. package/python/lib/python3.13/concurrent/futures/_base.py +660 -0
  111. package/python/lib/python3.13/concurrent/futures/process.py +892 -0
  112. package/python/lib/python3.13/concurrent/futures/thread.py +240 -0
  113. package/python/lib/python3.13/configparser.py +1396 -0
  114. package/python/lib/python3.13/contextlib.py +814 -0
  115. package/python/lib/python3.13/contextvars.py +4 -0
  116. package/python/lib/python3.13/copy.py +306 -0
  117. package/python/lib/python3.13/copyreg.py +217 -0
  118. package/python/lib/python3.13/csv.py +527 -0
  119. package/python/lib/python3.13/ctypes/__init__.py +605 -0
  120. package/python/lib/python3.13/ctypes/_aix.py +327 -0
  121. package/python/lib/python3.13/ctypes/_endian.py +78 -0
  122. package/python/lib/python3.13/ctypes/macholib/README.ctypes +7 -0
  123. package/python/lib/python3.13/ctypes/macholib/__init__.py +9 -0
  124. package/python/lib/python3.13/ctypes/macholib/dyld.py +165 -0
  125. package/python/lib/python3.13/ctypes/macholib/dylib.py +42 -0
  126. package/python/lib/python3.13/ctypes/macholib/fetch_macholib +2 -0
  127. package/python/lib/python3.13/ctypes/macholib/fetch_macholib.bat +1 -0
  128. package/python/lib/python3.13/ctypes/macholib/framework.py +42 -0
  129. package/python/lib/python3.13/ctypes/util.py +387 -0
  130. package/python/lib/python3.13/ctypes/wintypes.py +202 -0
  131. package/python/lib/python3.13/curses/__init__.py +101 -0
  132. package/python/lib/python3.13/curses/ascii.py +99 -0
  133. package/python/lib/python3.13/curses/has_key.py +192 -0
  134. package/python/lib/python3.13/curses/panel.py +6 -0
  135. package/python/lib/python3.13/curses/textpad.py +236 -0
  136. package/python/lib/python3.13/dataclasses.py +1679 -0
  137. package/python/lib/python3.13/datetime.py +9 -0
  138. package/python/lib/python3.13/dbm/__init__.py +194 -0
  139. package/python/lib/python3.13/dbm/dumb.py +319 -0
  140. package/python/lib/python3.13/dbm/gnu.py +3 -0
  141. package/python/lib/python3.13/dbm/ndbm.py +3 -0
  142. package/python/lib/python3.13/dbm/sqlite3.py +144 -0
  143. package/python/lib/python3.13/decimal.py +109 -0
  144. package/python/lib/python3.13/difflib.py +2058 -0
  145. package/python/lib/python3.13/dis.py +1075 -0
  146. package/python/lib/python3.13/doctest.py +2919 -0
  147. package/python/lib/python3.13/email/__init__.py +61 -0
  148. package/python/lib/python3.13/email/_encoded_words.py +233 -0
  149. package/python/lib/python3.13/email/_header_value_parser.py +3153 -0
  150. package/python/lib/python3.13/email/_parseaddr.py +563 -0
  151. package/python/lib/python3.13/email/_policybase.py +382 -0
  152. package/python/lib/python3.13/email/architecture.rst +216 -0
  153. package/python/lib/python3.13/email/base64mime.py +115 -0
  154. package/python/lib/python3.13/email/charset.py +396 -0
  155. package/python/lib/python3.13/email/contentmanager.py +254 -0
  156. package/python/lib/python3.13/email/encoders.py +65 -0
  157. package/python/lib/python3.13/email/errors.py +117 -0
  158. package/python/lib/python3.13/email/feedparser.py +536 -0
  159. package/python/lib/python3.13/email/generator.py +530 -0
  160. package/python/lib/python3.13/email/header.py +582 -0
  161. package/python/lib/python3.13/email/headerregistry.py +618 -0
  162. package/python/lib/python3.13/email/iterators.py +68 -0
  163. package/python/lib/python3.13/email/message.py +1217 -0
  164. package/python/lib/python3.13/email/mime/__init__.py +0 -0
  165. package/python/lib/python3.13/email/mime/application.py +37 -0
  166. package/python/lib/python3.13/email/mime/audio.py +97 -0
  167. package/python/lib/python3.13/email/mime/base.py +29 -0
  168. package/python/lib/python3.13/email/mime/image.py +152 -0
  169. package/python/lib/python3.13/email/mime/message.py +33 -0
  170. package/python/lib/python3.13/email/mime/multipart.py +47 -0
  171. package/python/lib/python3.13/email/mime/nonmultipart.py +21 -0
  172. package/python/lib/python3.13/email/mime/text.py +40 -0
  173. package/python/lib/python3.13/email/parser.py +127 -0
  174. package/python/lib/python3.13/email/policy.py +232 -0
  175. package/python/lib/python3.13/email/quoprimime.py +300 -0
  176. package/python/lib/python3.13/email/utils.py +497 -0
  177. package/python/lib/python3.13/encodings/__init__.py +179 -0
  178. package/python/lib/python3.13/encodings/__pycache__/__init__.cpython-313.pyc +0 -0
  179. package/python/lib/python3.13/encodings/__pycache__/aliases.cpython-313.pyc +0 -0
  180. package/python/lib/python3.13/encodings/__pycache__/utf_8.cpython-313.pyc +0 -0
  181. package/python/lib/python3.13/encodings/aliases.py +560 -0
  182. package/python/lib/python3.13/encodings/ascii.py +50 -0
  183. package/python/lib/python3.13/encodings/base64_codec.py +55 -0
  184. package/python/lib/python3.13/encodings/big5.py +39 -0
  185. package/python/lib/python3.13/encodings/big5hkscs.py +39 -0
  186. package/python/lib/python3.13/encodings/bz2_codec.py +78 -0
  187. package/python/lib/python3.13/encodings/charmap.py +69 -0
  188. package/python/lib/python3.13/encodings/cp037.py +307 -0
  189. package/python/lib/python3.13/encodings/cp1006.py +307 -0
  190. package/python/lib/python3.13/encodings/cp1026.py +307 -0
  191. package/python/lib/python3.13/encodings/cp1125.py +698 -0
  192. package/python/lib/python3.13/encodings/cp1140.py +307 -0
  193. package/python/lib/python3.13/encodings/cp1250.py +307 -0
  194. package/python/lib/python3.13/encodings/cp1251.py +307 -0
  195. package/python/lib/python3.13/encodings/cp1252.py +307 -0
  196. package/python/lib/python3.13/encodings/cp1253.py +307 -0
  197. package/python/lib/python3.13/encodings/cp1254.py +307 -0
  198. package/python/lib/python3.13/encodings/cp1255.py +307 -0
  199. package/python/lib/python3.13/encodings/cp1256.py +307 -0
  200. package/python/lib/python3.13/encodings/cp1257.py +307 -0
  201. package/python/lib/python3.13/encodings/cp1258.py +307 -0
  202. package/python/lib/python3.13/encodings/cp273.py +307 -0
  203. package/python/lib/python3.13/encodings/cp424.py +307 -0
  204. package/python/lib/python3.13/encodings/cp437.py +698 -0
  205. package/python/lib/python3.13/encodings/cp500.py +307 -0
  206. package/python/lib/python3.13/encodings/cp720.py +309 -0
  207. package/python/lib/python3.13/encodings/cp737.py +698 -0
  208. package/python/lib/python3.13/encodings/cp775.py +697 -0
  209. package/python/lib/python3.13/encodings/cp850.py +698 -0
  210. package/python/lib/python3.13/encodings/cp852.py +698 -0
  211. package/python/lib/python3.13/encodings/cp855.py +698 -0
  212. package/python/lib/python3.13/encodings/cp856.py +307 -0
  213. package/python/lib/python3.13/encodings/cp857.py +694 -0
  214. package/python/lib/python3.13/encodings/cp858.py +698 -0
  215. package/python/lib/python3.13/encodings/cp860.py +698 -0
  216. package/python/lib/python3.13/encodings/cp861.py +698 -0
  217. package/python/lib/python3.13/encodings/cp862.py +698 -0
  218. package/python/lib/python3.13/encodings/cp863.py +698 -0
  219. package/python/lib/python3.13/encodings/cp864.py +690 -0
  220. package/python/lib/python3.13/encodings/cp865.py +698 -0
  221. package/python/lib/python3.13/encodings/cp866.py +698 -0
  222. package/python/lib/python3.13/encodings/cp869.py +689 -0
  223. package/python/lib/python3.13/encodings/cp874.py +307 -0
  224. package/python/lib/python3.13/encodings/cp875.py +307 -0
  225. package/python/lib/python3.13/encodings/cp932.py +39 -0
  226. package/python/lib/python3.13/encodings/cp949.py +39 -0
  227. package/python/lib/python3.13/encodings/cp950.py +39 -0
  228. package/python/lib/python3.13/encodings/euc_jis_2004.py +39 -0
  229. package/python/lib/python3.13/encodings/euc_jisx0213.py +39 -0
  230. package/python/lib/python3.13/encodings/euc_jp.py +39 -0
  231. package/python/lib/python3.13/encodings/euc_kr.py +39 -0
  232. package/python/lib/python3.13/encodings/gb18030.py +39 -0
  233. package/python/lib/python3.13/encodings/gb2312.py +39 -0
  234. package/python/lib/python3.13/encodings/gbk.py +39 -0
  235. package/python/lib/python3.13/encodings/hex_codec.py +55 -0
  236. package/python/lib/python3.13/encodings/hp_roman8.py +314 -0
  237. package/python/lib/python3.13/encodings/hz.py +39 -0
  238. package/python/lib/python3.13/encodings/idna.py +387 -0
  239. package/python/lib/python3.13/encodings/iso2022_jp.py +39 -0
  240. package/python/lib/python3.13/encodings/iso2022_jp_1.py +39 -0
  241. package/python/lib/python3.13/encodings/iso2022_jp_2.py +39 -0
  242. package/python/lib/python3.13/encodings/iso2022_jp_2004.py +39 -0
  243. package/python/lib/python3.13/encodings/iso2022_jp_3.py +39 -0
  244. package/python/lib/python3.13/encodings/iso2022_jp_ext.py +39 -0
  245. package/python/lib/python3.13/encodings/iso2022_kr.py +39 -0
  246. package/python/lib/python3.13/encodings/iso8859_1.py +307 -0
  247. package/python/lib/python3.13/encodings/iso8859_10.py +307 -0
  248. package/python/lib/python3.13/encodings/iso8859_11.py +307 -0
  249. package/python/lib/python3.13/encodings/iso8859_13.py +307 -0
  250. package/python/lib/python3.13/encodings/iso8859_14.py +307 -0
  251. package/python/lib/python3.13/encodings/iso8859_15.py +307 -0
  252. package/python/lib/python3.13/encodings/iso8859_16.py +307 -0
  253. package/python/lib/python3.13/encodings/iso8859_2.py +307 -0
  254. package/python/lib/python3.13/encodings/iso8859_3.py +307 -0
  255. package/python/lib/python3.13/encodings/iso8859_4.py +307 -0
  256. package/python/lib/python3.13/encodings/iso8859_5.py +307 -0
  257. package/python/lib/python3.13/encodings/iso8859_6.py +307 -0
  258. package/python/lib/python3.13/encodings/iso8859_7.py +307 -0
  259. package/python/lib/python3.13/encodings/iso8859_8.py +307 -0
  260. package/python/lib/python3.13/encodings/iso8859_9.py +307 -0
  261. package/python/lib/python3.13/encodings/johab.py +39 -0
  262. package/python/lib/python3.13/encodings/koi8_r.py +307 -0
  263. package/python/lib/python3.13/encodings/koi8_t.py +308 -0
  264. package/python/lib/python3.13/encodings/koi8_u.py +307 -0
  265. package/python/lib/python3.13/encodings/kz1048.py +307 -0
  266. package/python/lib/python3.13/encodings/latin_1.py +50 -0
  267. package/python/lib/python3.13/encodings/mac_arabic.py +698 -0
  268. package/python/lib/python3.13/encodings/mac_croatian.py +307 -0
  269. package/python/lib/python3.13/encodings/mac_cyrillic.py +307 -0
  270. package/python/lib/python3.13/encodings/mac_farsi.py +307 -0
  271. package/python/lib/python3.13/encodings/mac_greek.py +307 -0
  272. package/python/lib/python3.13/encodings/mac_iceland.py +307 -0
  273. package/python/lib/python3.13/encodings/mac_latin2.py +312 -0
  274. package/python/lib/python3.13/encodings/mac_roman.py +307 -0
  275. package/python/lib/python3.13/encodings/mac_romanian.py +307 -0
  276. package/python/lib/python3.13/encodings/mac_turkish.py +307 -0
  277. package/python/lib/python3.13/encodings/mbcs.py +47 -0
  278. package/python/lib/python3.13/encodings/oem.py +41 -0
  279. package/python/lib/python3.13/encodings/palmos.py +308 -0
  280. package/python/lib/python3.13/encodings/ptcp154.py +312 -0
  281. package/python/lib/python3.13/encodings/punycode.py +253 -0
  282. package/python/lib/python3.13/encodings/quopri_codec.py +56 -0
  283. package/python/lib/python3.13/encodings/raw_unicode_escape.py +46 -0
  284. package/python/lib/python3.13/encodings/rot_13.py +113 -0
  285. package/python/lib/python3.13/encodings/shift_jis.py +39 -0
  286. package/python/lib/python3.13/encodings/shift_jis_2004.py +39 -0
  287. package/python/lib/python3.13/encodings/shift_jisx0213.py +39 -0
  288. package/python/lib/python3.13/encodings/tis_620.py +307 -0
  289. package/python/lib/python3.13/encodings/undefined.py +49 -0
  290. package/python/lib/python3.13/encodings/unicode_escape.py +46 -0
  291. package/python/lib/python3.13/encodings/utf_16.py +155 -0
  292. package/python/lib/python3.13/encodings/utf_16_be.py +42 -0
  293. package/python/lib/python3.13/encodings/utf_16_le.py +42 -0
  294. package/python/lib/python3.13/encodings/utf_32.py +150 -0
  295. package/python/lib/python3.13/encodings/utf_32_be.py +37 -0
  296. package/python/lib/python3.13/encodings/utf_32_le.py +37 -0
  297. package/python/lib/python3.13/encodings/utf_7.py +38 -0
  298. package/python/lib/python3.13/encodings/utf_8.py +42 -0
  299. package/python/lib/python3.13/encodings/utf_8_sig.py +130 -0
  300. package/python/lib/python3.13/encodings/uu_codec.py +103 -0
  301. package/python/lib/python3.13/encodings/zlib_codec.py +77 -0
  302. package/python/lib/python3.13/enum.py +2183 -0
  303. package/python/lib/python3.13/filecmp.py +320 -0
  304. package/python/lib/python3.13/fileinput.py +442 -0
  305. package/python/lib/python3.13/fnmatch.py +192 -0
  306. package/python/lib/python3.13/fractions.py +1043 -0
  307. package/python/lib/python3.13/ftplib.py +975 -0
  308. package/python/lib/python3.13/functools.py +1036 -0
  309. package/python/lib/python3.13/genericpath.py +200 -0
  310. package/python/lib/python3.13/getopt.py +215 -0
  311. package/python/lib/python3.13/getpass.py +192 -0
  312. package/python/lib/python3.13/gettext.py +657 -0
  313. package/python/lib/python3.13/glob.py +572 -0
  314. package/python/lib/python3.13/graphlib.py +250 -0
  315. package/python/lib/python3.13/gzip.py +693 -0
  316. package/python/lib/python3.13/hashlib.py +255 -0
  317. package/python/lib/python3.13/heapq.py +603 -0
  318. package/python/lib/python3.13/hmac.py +220 -0
  319. package/python/lib/python3.13/html/__init__.py +132 -0
  320. package/python/lib/python3.13/html/entities.py +2513 -0
  321. package/python/lib/python3.13/html/parser.py +583 -0
  322. package/python/lib/python3.13/http/__init__.py +202 -0
  323. package/python/lib/python3.13/http/client.py +1598 -0
  324. package/python/lib/python3.13/http/cookiejar.py +2122 -0
  325. package/python/lib/python3.13/http/cookies.py +635 -0
  326. package/python/lib/python3.13/http/server.py +1355 -0
  327. package/python/lib/python3.13/imaplib.py +1769 -0
  328. package/python/lib/python3.13/importlib/__init__.py +136 -0
  329. package/python/lib/python3.13/importlib/_abc.py +39 -0
  330. package/python/lib/python3.13/importlib/_bootstrap.py +1559 -0
  331. package/python/lib/python3.13/importlib/_bootstrap_external.py +1826 -0
  332. package/python/lib/python3.13/importlib/abc.py +243 -0
  333. package/python/lib/python3.13/importlib/machinery.py +21 -0
  334. package/python/lib/python3.13/importlib/metadata/__init__.py +1093 -0
  335. package/python/lib/python3.13/importlib/metadata/_adapters.py +89 -0
  336. package/python/lib/python3.13/importlib/metadata/_collections.py +30 -0
  337. package/python/lib/python3.13/importlib/metadata/_functools.py +104 -0
  338. package/python/lib/python3.13/importlib/metadata/_itertools.py +73 -0
  339. package/python/lib/python3.13/importlib/metadata/_meta.py +67 -0
  340. package/python/lib/python3.13/importlib/metadata/_text.py +99 -0
  341. package/python/lib/python3.13/importlib/metadata/diagnose.py +21 -0
  342. package/python/lib/python3.13/importlib/readers.py +12 -0
  343. package/python/lib/python3.13/importlib/resources/__init__.py +43 -0
  344. package/python/lib/python3.13/importlib/resources/_adapters.py +168 -0
  345. package/python/lib/python3.13/importlib/resources/_common.py +211 -0
  346. package/python/lib/python3.13/importlib/resources/_functional.py +81 -0
  347. package/python/lib/python3.13/importlib/resources/_itertools.py +38 -0
  348. package/python/lib/python3.13/importlib/resources/abc.py +173 -0
  349. package/python/lib/python3.13/importlib/resources/readers.py +203 -0
  350. package/python/lib/python3.13/importlib/resources/simple.py +106 -0
  351. package/python/lib/python3.13/importlib/simple.py +14 -0
  352. package/python/lib/python3.13/importlib/util.py +274 -0
  353. package/python/lib/python3.13/inspect.py +3479 -0
  354. package/python/lib/python3.13/io.py +99 -0
  355. package/python/lib/python3.13/ipaddress.py +2440 -0
  356. package/python/lib/python3.13/json/__init__.py +365 -0
  357. package/python/lib/python3.13/json/decoder.py +364 -0
  358. package/python/lib/python3.13/json/encoder.py +446 -0
  359. package/python/lib/python3.13/json/scanner.py +73 -0
  360. package/python/lib/python3.13/json/tool.py +90 -0
  361. package/python/lib/python3.13/keyword.py +64 -0
  362. package/python/lib/python3.13/lib-dynload/.empty +0 -0
  363. package/python/lib/python3.13/lib-dynload/_dbm.cpython-313-x86_64-linux-gnu.so +0 -0
  364. package/python/lib/python3.13/linecache.py +236 -0
  365. package/python/lib/python3.13/locale.py +1987 -0
  366. package/python/lib/python3.13/logging/__init__.py +2330 -0
  367. package/python/lib/python3.13/logging/config.py +1080 -0
  368. package/python/lib/python3.13/logging/handlers.py +1629 -0
  369. package/python/lib/python3.13/lzma.py +364 -0
  370. package/python/lib/python3.13/mailbox.py +2219 -0
  371. package/python/lib/python3.13/mimetypes.py +679 -0
  372. package/python/lib/python3.13/modulefinder.py +671 -0
  373. package/python/lib/python3.13/multiprocessing/__init__.py +37 -0
  374. package/python/lib/python3.13/multiprocessing/connection.py +1216 -0
  375. package/python/lib/python3.13/multiprocessing/context.py +383 -0
  376. package/python/lib/python3.13/multiprocessing/dummy/__init__.py +126 -0
  377. package/python/lib/python3.13/multiprocessing/dummy/connection.py +75 -0
  378. package/python/lib/python3.13/multiprocessing/forkserver.py +373 -0
  379. package/python/lib/python3.13/multiprocessing/heap.py +337 -0
  380. package/python/lib/python3.13/multiprocessing/managers.py +1397 -0
  381. package/python/lib/python3.13/multiprocessing/pool.py +957 -0
  382. package/python/lib/python3.13/multiprocessing/popen_fork.py +97 -0
  383. package/python/lib/python3.13/multiprocessing/popen_forkserver.py +74 -0
  384. package/python/lib/python3.13/multiprocessing/popen_spawn_posix.py +76 -0
  385. package/python/lib/python3.13/multiprocessing/popen_spawn_win32.py +147 -0
  386. package/python/lib/python3.13/multiprocessing/process.py +436 -0
  387. package/python/lib/python3.13/multiprocessing/queues.py +399 -0
  388. package/python/lib/python3.13/multiprocessing/reduction.py +281 -0
  389. package/python/lib/python3.13/multiprocessing/resource_sharer.py +154 -0
  390. package/python/lib/python3.13/multiprocessing/resource_tracker.py +499 -0
  391. package/python/lib/python3.13/multiprocessing/shared_memory.py +544 -0
  392. package/python/lib/python3.13/multiprocessing/sharedctypes.py +240 -0
  393. package/python/lib/python3.13/multiprocessing/spawn.py +307 -0
  394. package/python/lib/python3.13/multiprocessing/synchronize.py +404 -0
  395. package/python/lib/python3.13/multiprocessing/util.py +562 -0
  396. package/python/lib/python3.13/netrc.py +199 -0
  397. package/python/lib/python3.13/ntpath.py +872 -0
  398. package/python/lib/python3.13/nturl2path.py +69 -0
  399. package/python/lib/python3.13/numbers.py +427 -0
  400. package/python/lib/python3.13/opcode.py +115 -0
  401. package/python/lib/python3.13/operator.py +467 -0
  402. package/python/lib/python3.13/optparse.py +1681 -0
  403. package/python/lib/python3.13/os.py +1184 -0
  404. package/python/lib/python3.13/pathlib/__init__.py +12 -0
  405. package/python/lib/python3.13/pathlib/_abc.py +930 -0
  406. package/python/lib/python3.13/pathlib/_local.py +861 -0
  407. package/python/lib/python3.13/pdb.py +2550 -0
  408. package/python/lib/python3.13/pickle.py +1860 -0
  409. package/python/lib/python3.13/pickletools.py +2904 -0
  410. package/python/lib/python3.13/pkgutil.py +529 -0
  411. package/python/lib/python3.13/platform.py +1454 -0
  412. package/python/lib/python3.13/plistlib.py +948 -0
  413. package/python/lib/python3.13/poplib.py +477 -0
  414. package/python/lib/python3.13/posixpath.py +578 -0
  415. package/python/lib/python3.13/pprint.py +658 -0
  416. package/python/lib/python3.13/profile.py +616 -0
  417. package/python/lib/python3.13/pstats.py +778 -0
  418. package/python/lib/python3.13/pty.py +211 -0
  419. package/python/lib/python3.13/py_compile.py +212 -0
  420. package/python/lib/python3.13/pyclbr.py +314 -0
  421. package/python/lib/python3.13/pydoc.py +2861 -0
  422. package/python/lib/python3.13/queue.py +383 -0
  423. package/python/lib/python3.13/quopri.py +237 -0
  424. package/python/lib/python3.13/random.py +1078 -0
  425. package/python/lib/python3.13/re/__init__.py +428 -0
  426. package/python/lib/python3.13/re/_casefix.py +106 -0
  427. package/python/lib/python3.13/re/_compiler.py +768 -0
  428. package/python/lib/python3.13/re/_constants.py +222 -0
  429. package/python/lib/python3.13/re/_parser.py +1081 -0
  430. package/python/lib/python3.13/reprlib.py +230 -0
  431. package/python/lib/python3.13/rlcompleter.py +222 -0
  432. package/python/lib/python3.13/runpy.py +326 -0
  433. package/python/lib/python3.13/sched.py +167 -0
  434. package/python/lib/python3.13/secrets.py +71 -0
  435. package/python/lib/python3.13/selectors.py +603 -0
  436. package/python/lib/python3.13/shelve.py +250 -0
  437. package/python/lib/python3.13/shlex.py +345 -0
  438. package/python/lib/python3.13/shutil.py +1569 -0
  439. package/python/lib/python3.13/signal.py +94 -0
  440. package/python/lib/python3.13/site.py +773 -0
  441. package/python/lib/python3.13/smtplib.py +1123 -0
  442. package/python/lib/python3.13/socket.py +988 -0
  443. package/python/lib/python3.13/socketserver.py +863 -0
  444. package/python/lib/python3.13/sqlite3/__init__.py +70 -0
  445. package/python/lib/python3.13/sqlite3/__main__.py +139 -0
  446. package/python/lib/python3.13/sqlite3/dbapi2.py +108 -0
  447. package/python/lib/python3.13/sqlite3/dump.py +118 -0
  448. package/python/lib/python3.13/sre_compile.py +7 -0
  449. package/python/lib/python3.13/sre_constants.py +7 -0
  450. package/python/lib/python3.13/sre_parse.py +7 -0
  451. package/python/lib/python3.13/ssl.py +1541 -0
  452. package/python/lib/python3.13/stat.py +212 -0
  453. package/python/lib/python3.13/statistics.py +1817 -0
  454. package/python/lib/python3.13/string.py +314 -0
  455. package/python/lib/python3.13/stringprep.py +272 -0
  456. package/python/lib/python3.13/struct.py +15 -0
  457. package/python/lib/python3.13/subprocess.py +2258 -0
  458. package/python/lib/python3.13/symtable.py +414 -0
  459. package/python/lib/python3.13/sysconfig/__init__.py +734 -0
  460. package/python/lib/python3.13/sysconfig/__main__.py +248 -0
  461. package/python/lib/python3.13/tabnanny.py +340 -0
  462. package/python/lib/python3.13/tarfile.py +3136 -0
  463. package/python/lib/python3.13/tempfile.py +958 -0
  464. package/python/lib/python3.13/textwrap.py +497 -0
  465. package/python/lib/python3.13/this.py +28 -0
  466. package/python/lib/python3.13/threading.py +1602 -0
  467. package/python/lib/python3.13/timeit.py +381 -0
  468. package/python/lib/python3.13/token.py +141 -0
  469. package/python/lib/python3.13/tokenize.py +592 -0
  470. package/python/lib/python3.13/tomllib/__init__.py +10 -0
  471. package/python/lib/python3.13/tomllib/_parser.py +703 -0
  472. package/python/lib/python3.13/tomllib/_re.py +107 -0
  473. package/python/lib/python3.13/tomllib/_types.py +10 -0
  474. package/python/lib/python3.13/tomllib/mypy.ini +15 -0
  475. package/python/lib/python3.13/trace.py +754 -0
  476. package/python/lib/python3.13/traceback.py +1639 -0
  477. package/python/lib/python3.13/tracemalloc.py +560 -0
  478. package/python/lib/python3.13/tty.py +73 -0
  479. package/python/lib/python3.13/types.py +346 -0
  480. package/python/lib/python3.13/typing.py +3846 -0
  481. package/python/lib/python3.13/unittest/__init__.py +80 -0
  482. package/python/lib/python3.13/unittest/__main__.py +18 -0
  483. package/python/lib/python3.13/unittest/_log.py +86 -0
  484. package/python/lib/python3.13/unittest/async_case.py +146 -0
  485. package/python/lib/python3.13/unittest/case.py +1478 -0
  486. package/python/lib/python3.13/unittest/loader.py +460 -0
  487. package/python/lib/python3.13/unittest/main.py +280 -0
  488. package/python/lib/python3.13/unittest/mock.py +3189 -0
  489. package/python/lib/python3.13/unittest/result.py +256 -0
  490. package/python/lib/python3.13/unittest/runner.py +292 -0
  491. package/python/lib/python3.13/unittest/signals.py +71 -0
  492. package/python/lib/python3.13/unittest/suite.py +379 -0
  493. package/python/lib/python3.13/unittest/util.py +170 -0
  494. package/python/lib/python3.13/urllib/__init__.py +0 -0
  495. package/python/lib/python3.13/urllib/error.py +74 -0
  496. package/python/lib/python3.13/urllib/parse.py +1264 -0
  497. package/python/lib/python3.13/urllib/request.py +2796 -0
  498. package/python/lib/python3.13/urllib/response.py +84 -0
  499. package/python/lib/python3.13/urllib/robotparser.py +363 -0
  500. package/python/lib/python3.13/uuid.py +784 -0
  501. package/python/lib/python3.13/warnings.py +735 -0
  502. package/python/lib/python3.13/wave.py +665 -0
  503. package/python/lib/python3.13/weakref.py +674 -0
  504. package/python/lib/python3.13/webbrowser.py +724 -0
  505. package/python/lib/python3.13/wsgiref/__init__.py +25 -0
  506. package/python/lib/python3.13/wsgiref/handlers.py +575 -0
  507. package/python/lib/python3.13/wsgiref/headers.py +192 -0
  508. package/python/lib/python3.13/wsgiref/simple_server.py +161 -0
  509. package/python/lib/python3.13/wsgiref/types.py +54 -0
  510. package/python/lib/python3.13/wsgiref/util.py +159 -0
  511. package/python/lib/python3.13/wsgiref/validate.py +438 -0
  512. package/python/lib/python3.13/xml/__init__.py +20 -0
  513. package/python/lib/python3.13/xml/dom/NodeFilter.py +27 -0
  514. package/python/lib/python3.13/xml/dom/__init__.py +140 -0
  515. package/python/lib/python3.13/xml/dom/domreg.py +99 -0
  516. package/python/lib/python3.13/xml/dom/expatbuilder.py +962 -0
  517. package/python/lib/python3.13/xml/dom/minicompat.py +109 -0
  518. package/python/lib/python3.13/xml/dom/minidom.py +2024 -0
  519. package/python/lib/python3.13/xml/dom/pulldom.py +336 -0
  520. package/python/lib/python3.13/xml/dom/xmlbuilder.py +389 -0
  521. package/python/lib/python3.13/xml/etree/ElementInclude.py +186 -0
  522. package/python/lib/python3.13/xml/etree/ElementPath.py +430 -0
  523. package/python/lib/python3.13/xml/etree/ElementTree.py +2116 -0
  524. package/python/lib/python3.13/xml/etree/__init__.py +33 -0
  525. package/python/lib/python3.13/xml/etree/cElementTree.py +3 -0
  526. package/python/lib/python3.13/xml/parsers/__init__.py +8 -0
  527. package/python/lib/python3.13/xml/parsers/expat.py +8 -0
  528. package/python/lib/python3.13/xml/sax/__init__.py +94 -0
  529. package/python/lib/python3.13/xml/sax/_exceptions.py +127 -0
  530. package/python/lib/python3.13/xml/sax/expatreader.py +454 -0
  531. package/python/lib/python3.13/xml/sax/handler.py +387 -0
  532. package/python/lib/python3.13/xml/sax/saxutils.py +369 -0
  533. package/python/lib/python3.13/xml/sax/xmlreader.py +378 -0
  534. package/python/lib/python3.13/xmlrpc/__init__.py +1 -0
  535. package/python/lib/python3.13/xmlrpc/client.py +1503 -0
  536. package/python/lib/python3.13/xmlrpc/server.py +1002 -0
  537. package/python/lib/python3.13/zipapp.py +229 -0
  538. package/python/lib/python3.13/zipfile/__init__.py +2391 -0
  539. package/python/lib/python3.13/zipfile/__main__.py +4 -0
  540. package/python/lib/python3.13/zipfile/_path/__init__.py +452 -0
  541. package/python/lib/python3.13/zipfile/_path/glob.py +113 -0
  542. package/python/lib/python3.13/zipimport.py +803 -0
  543. package/python/lib/python3.13/zoneinfo/__init__.py +34 -0
  544. package/python/lib/python3.13/zoneinfo/_common.py +172 -0
  545. package/python/lib/python3.13/zoneinfo/_tzpath.py +189 -0
  546. package/python/lib/python3.13/zoneinfo/_zoneinfo.py +779 -0
  547. package/python/licenses/LICENSE.bdb.txt +126 -0
  548. package/python/licenses/LICENSE.bzip2.txt +37 -0
  549. package/python/licenses/LICENSE.cpython.txt +771 -0
  550. package/python/licenses/LICENSE.expat.txt +21 -0
  551. package/python/licenses/LICENSE.libX11.txt +942 -0
  552. package/python/licenses/LICENSE.libXau.txt +21 -0
  553. package/python/licenses/LICENSE.libedit.txt +29 -0
  554. package/python/licenses/LICENSE.libffi.txt +21 -0
  555. package/python/licenses/LICENSE.liblzma.txt +13 -0
  556. package/python/licenses/LICENSE.libuuid.txt +27 -0
  557. package/python/licenses/LICENSE.libxcb.txt +30 -0
  558. package/python/licenses/LICENSE.mpdecimal.txt +24 -0
  559. package/python/licenses/LICENSE.ncurses.txt +29 -0
  560. package/python/licenses/LICENSE.openssl-1.1.txt +124 -0
  561. package/python/licenses/LICENSE.openssl-3.txt +177 -0
  562. package/python/licenses/LICENSE.sqlite.txt +23 -0
  563. package/python/licenses/LICENSE.tcl.txt +40 -0
  564. package/python/licenses/LICENSE.tix.txt +54 -0
  565. package/python/licenses/LICENSE.zlib.txt +21 -0
@@ -0,0 +1,3189 @@
1
+ # mock.py
2
+ # Test tools for mocking and patching.
3
+ # Maintained by Michael Foord
4
+ # Backport for other versions of Python available from
5
+ # https://pypi.org/project/mock
6
+
7
+ __all__ = (
8
+ 'Mock',
9
+ 'MagicMock',
10
+ 'patch',
11
+ 'sentinel',
12
+ 'DEFAULT',
13
+ 'ANY',
14
+ 'call',
15
+ 'create_autospec',
16
+ 'AsyncMock',
17
+ 'ThreadingMock',
18
+ 'FILTER_DIR',
19
+ 'NonCallableMock',
20
+ 'NonCallableMagicMock',
21
+ 'mock_open',
22
+ 'PropertyMock',
23
+ 'seal',
24
+ )
25
+
26
+
27
+ import asyncio
28
+ import contextlib
29
+ import io
30
+ import inspect
31
+ import pprint
32
+ import sys
33
+ import builtins
34
+ import pkgutil
35
+ from asyncio import iscoroutinefunction
36
+ import threading
37
+ from types import CodeType, ModuleType, MethodType
38
+ from unittest.util import safe_repr
39
+ from functools import wraps, partial
40
+ from threading import RLock
41
+
42
+
43
+ class InvalidSpecError(Exception):
44
+ """Indicates that an invalid value was used as a mock spec."""
45
+
46
+
47
+ _builtins = {name for name in dir(builtins) if not name.startswith('_')}
48
+
49
+ FILTER_DIR = True
50
+
51
+ # Workaround for issue #12370
52
+ # Without this, the __class__ properties wouldn't be set correctly
53
+ _safe_super = super
54
+
55
+ def _is_async_obj(obj):
56
+ if _is_instance_mock(obj) and not isinstance(obj, AsyncMock):
57
+ return False
58
+ if hasattr(obj, '__func__'):
59
+ obj = getattr(obj, '__func__')
60
+ return iscoroutinefunction(obj) or inspect.isawaitable(obj)
61
+
62
+
63
+ def _is_async_func(func):
64
+ if getattr(func, '__code__', None):
65
+ return iscoroutinefunction(func)
66
+ else:
67
+ return False
68
+
69
+
70
+ def _is_instance_mock(obj):
71
+ # can't use isinstance on Mock objects because they override __class__
72
+ # The base class for all mocks is NonCallableMock
73
+ return issubclass(type(obj), NonCallableMock)
74
+
75
+
76
+ def _is_exception(obj):
77
+ return (
78
+ isinstance(obj, BaseException) or
79
+ isinstance(obj, type) and issubclass(obj, BaseException)
80
+ )
81
+
82
+
83
+ def _extract_mock(obj):
84
+ # Autospecced functions will return a FunctionType with "mock" attribute
85
+ # which is the actual mock object that needs to be used.
86
+ if isinstance(obj, FunctionTypes) and hasattr(obj, 'mock'):
87
+ return obj.mock
88
+ else:
89
+ return obj
90
+
91
+
92
+ def _get_signature_object(func, as_instance, eat_self):
93
+ """
94
+ Given an arbitrary, possibly callable object, try to create a suitable
95
+ signature object.
96
+ Return a (reduced func, signature) tuple, or None.
97
+ """
98
+ if isinstance(func, type) and not as_instance:
99
+ # If it's a type and should be modelled as a type, use __init__.
100
+ func = func.__init__
101
+ # Skip the `self` argument in __init__
102
+ eat_self = True
103
+ elif isinstance(func, (classmethod, staticmethod)):
104
+ if isinstance(func, classmethod):
105
+ # Skip the `cls` argument of a class method
106
+ eat_self = True
107
+ # Use the original decorated method to extract the correct function signature
108
+ func = func.__func__
109
+ elif not isinstance(func, FunctionTypes):
110
+ # If we really want to model an instance of the passed type,
111
+ # __call__ should be looked up, not __init__.
112
+ try:
113
+ func = func.__call__
114
+ except AttributeError:
115
+ return None
116
+ if eat_self:
117
+ sig_func = partial(func, None)
118
+ else:
119
+ sig_func = func
120
+ try:
121
+ return func, inspect.signature(sig_func)
122
+ except ValueError:
123
+ # Certain callable types are not supported by inspect.signature()
124
+ return None
125
+
126
+
127
+ def _check_signature(func, mock, skipfirst, instance=False):
128
+ sig = _get_signature_object(func, instance, skipfirst)
129
+ if sig is None:
130
+ return
131
+ func, sig = sig
132
+ def checksig(self, /, *args, **kwargs):
133
+ sig.bind(*args, **kwargs)
134
+ _copy_func_details(func, checksig)
135
+ type(mock)._mock_check_sig = checksig
136
+ type(mock).__signature__ = sig
137
+
138
+
139
+ def _copy_func_details(func, funcopy):
140
+ # we explicitly don't copy func.__dict__ into this copy as it would
141
+ # expose original attributes that should be mocked
142
+ for attribute in (
143
+ '__name__', '__doc__', '__text_signature__',
144
+ '__module__', '__defaults__', '__kwdefaults__',
145
+ ):
146
+ try:
147
+ setattr(funcopy, attribute, getattr(func, attribute))
148
+ except AttributeError:
149
+ pass
150
+
151
+
152
+ def _callable(obj):
153
+ if isinstance(obj, type):
154
+ return True
155
+ if isinstance(obj, (staticmethod, classmethod, MethodType)):
156
+ return _callable(obj.__func__)
157
+ if getattr(obj, '__call__', None) is not None:
158
+ return True
159
+ return False
160
+
161
+
162
+ def _is_list(obj):
163
+ # checks for list or tuples
164
+ # XXXX badly named!
165
+ return type(obj) in (list, tuple)
166
+
167
+
168
+ def _instance_callable(obj):
169
+ """Given an object, return True if the object is callable.
170
+ For classes, return True if instances would be callable."""
171
+ if not isinstance(obj, type):
172
+ # already an instance
173
+ return getattr(obj, '__call__', None) is not None
174
+
175
+ # *could* be broken by a class overriding __mro__ or __dict__ via
176
+ # a metaclass
177
+ for base in (obj,) + obj.__mro__:
178
+ if base.__dict__.get('__call__') is not None:
179
+ return True
180
+ return False
181
+
182
+
183
+ def _set_signature(mock, original, instance=False):
184
+ # creates a function with signature (*args, **kwargs) that delegates to a
185
+ # mock. It still does signature checking by calling a lambda with the same
186
+ # signature as the original.
187
+
188
+ skipfirst = isinstance(original, type)
189
+ result = _get_signature_object(original, instance, skipfirst)
190
+ if result is None:
191
+ return mock
192
+ func, sig = result
193
+ def checksig(*args, **kwargs):
194
+ sig.bind(*args, **kwargs)
195
+ _copy_func_details(func, checksig)
196
+
197
+ name = original.__name__
198
+ if not name.isidentifier():
199
+ name = 'funcopy'
200
+ context = {'_checksig_': checksig, 'mock': mock}
201
+ src = """def %s(*args, **kwargs):
202
+ _checksig_(*args, **kwargs)
203
+ return mock(*args, **kwargs)""" % name
204
+ exec (src, context)
205
+ funcopy = context[name]
206
+ _setup_func(funcopy, mock, sig)
207
+ return funcopy
208
+
209
+ def _set_async_signature(mock, original, instance=False, is_async_mock=False):
210
+ # creates an async function with signature (*args, **kwargs) that delegates to a
211
+ # mock. It still does signature checking by calling a lambda with the same
212
+ # signature as the original.
213
+
214
+ skipfirst = isinstance(original, type)
215
+ func, sig = _get_signature_object(original, instance, skipfirst)
216
+ def checksig(*args, **kwargs):
217
+ sig.bind(*args, **kwargs)
218
+ _copy_func_details(func, checksig)
219
+
220
+ name = original.__name__
221
+ context = {'_checksig_': checksig, 'mock': mock}
222
+ src = """async def %s(*args, **kwargs):
223
+ _checksig_(*args, **kwargs)
224
+ return await mock(*args, **kwargs)""" % name
225
+ exec (src, context)
226
+ funcopy = context[name]
227
+ _setup_func(funcopy, mock, sig)
228
+ _setup_async_mock(funcopy)
229
+ return funcopy
230
+
231
+
232
+ def _setup_func(funcopy, mock, sig):
233
+ funcopy.mock = mock
234
+
235
+ def assert_called_with(*args, **kwargs):
236
+ return mock.assert_called_with(*args, **kwargs)
237
+ def assert_called(*args, **kwargs):
238
+ return mock.assert_called(*args, **kwargs)
239
+ def assert_not_called(*args, **kwargs):
240
+ return mock.assert_not_called(*args, **kwargs)
241
+ def assert_called_once(*args, **kwargs):
242
+ return mock.assert_called_once(*args, **kwargs)
243
+ def assert_called_once_with(*args, **kwargs):
244
+ return mock.assert_called_once_with(*args, **kwargs)
245
+ def assert_has_calls(*args, **kwargs):
246
+ return mock.assert_has_calls(*args, **kwargs)
247
+ def assert_any_call(*args, **kwargs):
248
+ return mock.assert_any_call(*args, **kwargs)
249
+ def reset_mock():
250
+ funcopy.method_calls = _CallList()
251
+ funcopy.mock_calls = _CallList()
252
+ mock.reset_mock()
253
+ ret = funcopy.return_value
254
+ if _is_instance_mock(ret) and not ret is mock:
255
+ ret.reset_mock()
256
+
257
+ funcopy.called = False
258
+ funcopy.call_count = 0
259
+ funcopy.call_args = None
260
+ funcopy.call_args_list = _CallList()
261
+ funcopy.method_calls = _CallList()
262
+ funcopy.mock_calls = _CallList()
263
+
264
+ funcopy.return_value = mock.return_value
265
+ funcopy.side_effect = mock.side_effect
266
+ funcopy._mock_children = mock._mock_children
267
+
268
+ funcopy.assert_called_with = assert_called_with
269
+ funcopy.assert_called_once_with = assert_called_once_with
270
+ funcopy.assert_has_calls = assert_has_calls
271
+ funcopy.assert_any_call = assert_any_call
272
+ funcopy.reset_mock = reset_mock
273
+ funcopy.assert_called = assert_called
274
+ funcopy.assert_not_called = assert_not_called
275
+ funcopy.assert_called_once = assert_called_once
276
+ funcopy.__signature__ = sig
277
+
278
+ mock._mock_delegate = funcopy
279
+
280
+
281
+ def _setup_async_mock(mock):
282
+ mock._is_coroutine = asyncio.coroutines._is_coroutine
283
+ mock.await_count = 0
284
+ mock.await_args = None
285
+ mock.await_args_list = _CallList()
286
+
287
+ # Mock is not configured yet so the attributes are set
288
+ # to a function and then the corresponding mock helper function
289
+ # is called when the helper is accessed similar to _setup_func.
290
+ def wrapper(attr, /, *args, **kwargs):
291
+ return getattr(mock.mock, attr)(*args, **kwargs)
292
+
293
+ for attribute in ('assert_awaited',
294
+ 'assert_awaited_once',
295
+ 'assert_awaited_with',
296
+ 'assert_awaited_once_with',
297
+ 'assert_any_await',
298
+ 'assert_has_awaits',
299
+ 'assert_not_awaited'):
300
+
301
+ # setattr(mock, attribute, wrapper) causes late binding
302
+ # hence attribute will always be the last value in the loop
303
+ # Use partial(wrapper, attribute) to ensure the attribute is bound
304
+ # correctly.
305
+ setattr(mock, attribute, partial(wrapper, attribute))
306
+
307
+
308
+ def _is_magic(name):
309
+ return '__%s__' % name[2:-2] == name
310
+
311
+
312
+ class _SentinelObject(object):
313
+ "A unique, named, sentinel object."
314
+ def __init__(self, name):
315
+ self.name = name
316
+
317
+ def __repr__(self):
318
+ return 'sentinel.%s' % self.name
319
+
320
+ def __reduce__(self):
321
+ return 'sentinel.%s' % self.name
322
+
323
+
324
+ class _Sentinel(object):
325
+ """Access attributes to return a named object, usable as a sentinel."""
326
+ def __init__(self):
327
+ self._sentinels = {}
328
+
329
+ def __getattr__(self, name):
330
+ if name == '__bases__':
331
+ # Without this help(unittest.mock) raises an exception
332
+ raise AttributeError
333
+ return self._sentinels.setdefault(name, _SentinelObject(name))
334
+
335
+ def __reduce__(self):
336
+ return 'sentinel'
337
+
338
+
339
+ sentinel = _Sentinel()
340
+
341
+ DEFAULT = sentinel.DEFAULT
342
+ _missing = sentinel.MISSING
343
+ _deleted = sentinel.DELETED
344
+
345
+
346
+ _allowed_names = {
347
+ 'return_value', '_mock_return_value', 'side_effect',
348
+ '_mock_side_effect', '_mock_parent', '_mock_new_parent',
349
+ '_mock_name', '_mock_new_name'
350
+ }
351
+
352
+
353
+ def _delegating_property(name):
354
+ _allowed_names.add(name)
355
+ _the_name = '_mock_' + name
356
+ def _get(self, name=name, _the_name=_the_name):
357
+ sig = self._mock_delegate
358
+ if sig is None:
359
+ return getattr(self, _the_name)
360
+ return getattr(sig, name)
361
+ def _set(self, value, name=name, _the_name=_the_name):
362
+ sig = self._mock_delegate
363
+ if sig is None:
364
+ self.__dict__[_the_name] = value
365
+ else:
366
+ setattr(sig, name, value)
367
+
368
+ return property(_get, _set)
369
+
370
+
371
+
372
+ class _CallList(list):
373
+
374
+ def __contains__(self, value):
375
+ if not isinstance(value, list):
376
+ return list.__contains__(self, value)
377
+ len_value = len(value)
378
+ len_self = len(self)
379
+ if len_value > len_self:
380
+ return False
381
+
382
+ for i in range(0, len_self - len_value + 1):
383
+ sub_list = self[i:i+len_value]
384
+ if sub_list == value:
385
+ return True
386
+ return False
387
+
388
+ def __repr__(self):
389
+ return pprint.pformat(list(self))
390
+
391
+
392
+ def _check_and_set_parent(parent, value, name, new_name):
393
+ value = _extract_mock(value)
394
+
395
+ if not _is_instance_mock(value):
396
+ return False
397
+ if ((value._mock_name or value._mock_new_name) or
398
+ (value._mock_parent is not None) or
399
+ (value._mock_new_parent is not None)):
400
+ return False
401
+
402
+ _parent = parent
403
+ while _parent is not None:
404
+ # setting a mock (value) as a child or return value of itself
405
+ # should not modify the mock
406
+ if _parent is value:
407
+ return False
408
+ _parent = _parent._mock_new_parent
409
+
410
+ if new_name:
411
+ value._mock_new_parent = parent
412
+ value._mock_new_name = new_name
413
+ if name:
414
+ value._mock_parent = parent
415
+ value._mock_name = name
416
+ return True
417
+
418
+ # Internal class to identify if we wrapped an iterator object or not.
419
+ class _MockIter(object):
420
+ def __init__(self, obj):
421
+ self.obj = iter(obj)
422
+ def __next__(self):
423
+ return next(self.obj)
424
+
425
+ class Base(object):
426
+ _mock_return_value = DEFAULT
427
+ _mock_side_effect = None
428
+ def __init__(self, /, *args, **kwargs):
429
+ pass
430
+
431
+
432
+
433
+ class NonCallableMock(Base):
434
+ """A non-callable version of `Mock`"""
435
+
436
+ # Store a mutex as a class attribute in order to protect concurrent access
437
+ # to mock attributes. Using a class attribute allows all NonCallableMock
438
+ # instances to share the mutex for simplicity.
439
+ #
440
+ # See https://github.com/python/cpython/issues/98624 for why this is
441
+ # necessary.
442
+ _lock = RLock()
443
+
444
+ def __new__(
445
+ cls, spec=None, wraps=None, name=None, spec_set=None,
446
+ parent=None, _spec_state=None, _new_name='', _new_parent=None,
447
+ _spec_as_instance=False, _eat_self=None, unsafe=False, **kwargs
448
+ ):
449
+ # every instance has its own class
450
+ # so we can create magic methods on the
451
+ # class without stomping on other mocks
452
+ bases = (cls,)
453
+ if not issubclass(cls, AsyncMockMixin):
454
+ # Check if spec is an async object or function
455
+ spec_arg = spec_set or spec
456
+ if spec_arg is not None and _is_async_obj(spec_arg):
457
+ bases = (AsyncMockMixin, cls)
458
+ new = type(cls.__name__, bases, {'__doc__': cls.__doc__})
459
+ instance = _safe_super(NonCallableMock, cls).__new__(new)
460
+ return instance
461
+
462
+
463
+ def __init__(
464
+ self, spec=None, wraps=None, name=None, spec_set=None,
465
+ parent=None, _spec_state=None, _new_name='', _new_parent=None,
466
+ _spec_as_instance=False, _eat_self=None, unsafe=False, **kwargs
467
+ ):
468
+ if _new_parent is None:
469
+ _new_parent = parent
470
+
471
+ __dict__ = self.__dict__
472
+ __dict__['_mock_parent'] = parent
473
+ __dict__['_mock_name'] = name
474
+ __dict__['_mock_new_name'] = _new_name
475
+ __dict__['_mock_new_parent'] = _new_parent
476
+ __dict__['_mock_sealed'] = False
477
+
478
+ if spec_set is not None:
479
+ spec = spec_set
480
+ spec_set = True
481
+ if _eat_self is None:
482
+ _eat_self = parent is not None
483
+
484
+ self._mock_add_spec(spec, spec_set, _spec_as_instance, _eat_self)
485
+
486
+ __dict__['_mock_children'] = {}
487
+ __dict__['_mock_wraps'] = wraps
488
+ __dict__['_mock_delegate'] = None
489
+
490
+ __dict__['_mock_called'] = False
491
+ __dict__['_mock_call_args'] = None
492
+ __dict__['_mock_call_count'] = 0
493
+ __dict__['_mock_call_args_list'] = _CallList()
494
+ __dict__['_mock_mock_calls'] = _CallList()
495
+
496
+ __dict__['method_calls'] = _CallList()
497
+ __dict__['_mock_unsafe'] = unsafe
498
+
499
+ if kwargs:
500
+ self.configure_mock(**kwargs)
501
+
502
+ _safe_super(NonCallableMock, self).__init__(
503
+ spec, wraps, name, spec_set, parent,
504
+ _spec_state
505
+ )
506
+
507
+
508
+ def attach_mock(self, mock, attribute):
509
+ """
510
+ Attach a mock as an attribute of this one, replacing its name and
511
+ parent. Calls to the attached mock will be recorded in the
512
+ `method_calls` and `mock_calls` attributes of this one."""
513
+ inner_mock = _extract_mock(mock)
514
+
515
+ inner_mock._mock_parent = None
516
+ inner_mock._mock_new_parent = None
517
+ inner_mock._mock_name = ''
518
+ inner_mock._mock_new_name = None
519
+
520
+ setattr(self, attribute, mock)
521
+
522
+
523
+ def mock_add_spec(self, spec, spec_set=False):
524
+ """Add a spec to a mock. `spec` can either be an object or a
525
+ list of strings. Only attributes on the `spec` can be fetched as
526
+ attributes from the mock.
527
+
528
+ If `spec_set` is True then only attributes on the spec can be set."""
529
+ self._mock_add_spec(spec, spec_set)
530
+
531
+
532
+ def _mock_add_spec(self, spec, spec_set, _spec_as_instance=False,
533
+ _eat_self=False):
534
+ if _is_instance_mock(spec):
535
+ raise InvalidSpecError(f'Cannot spec a Mock object. [object={spec!r}]')
536
+
537
+ _spec_class = None
538
+ _spec_signature = None
539
+ _spec_asyncs = []
540
+
541
+ if spec is not None and not _is_list(spec):
542
+ if isinstance(spec, type):
543
+ _spec_class = spec
544
+ else:
545
+ _spec_class = type(spec)
546
+ res = _get_signature_object(spec,
547
+ _spec_as_instance, _eat_self)
548
+ _spec_signature = res and res[1]
549
+
550
+ spec_list = dir(spec)
551
+
552
+ for attr in spec_list:
553
+ static_attr = inspect.getattr_static(spec, attr, None)
554
+ unwrapped_attr = static_attr
555
+ try:
556
+ unwrapped_attr = inspect.unwrap(unwrapped_attr)
557
+ except ValueError:
558
+ pass
559
+ if iscoroutinefunction(unwrapped_attr):
560
+ _spec_asyncs.append(attr)
561
+
562
+ spec = spec_list
563
+
564
+ __dict__ = self.__dict__
565
+ __dict__['_spec_class'] = _spec_class
566
+ __dict__['_spec_set'] = spec_set
567
+ __dict__['_spec_signature'] = _spec_signature
568
+ __dict__['_mock_methods'] = spec
569
+ __dict__['_spec_asyncs'] = _spec_asyncs
570
+
571
+ def __get_return_value(self):
572
+ ret = self._mock_return_value
573
+ if self._mock_delegate is not None:
574
+ ret = self._mock_delegate.return_value
575
+
576
+ if ret is DEFAULT and self._mock_wraps is None:
577
+ ret = self._get_child_mock(
578
+ _new_parent=self, _new_name='()'
579
+ )
580
+ self.return_value = ret
581
+ return ret
582
+
583
+
584
+ def __set_return_value(self, value):
585
+ if self._mock_delegate is not None:
586
+ self._mock_delegate.return_value = value
587
+ else:
588
+ self._mock_return_value = value
589
+ _check_and_set_parent(self, value, None, '()')
590
+
591
+ __return_value_doc = "The value to be returned when the mock is called."
592
+ return_value = property(__get_return_value, __set_return_value,
593
+ __return_value_doc)
594
+
595
+
596
+ @property
597
+ def __class__(self):
598
+ if self._spec_class is None:
599
+ return type(self)
600
+ return self._spec_class
601
+
602
+ called = _delegating_property('called')
603
+ call_count = _delegating_property('call_count')
604
+ call_args = _delegating_property('call_args')
605
+ call_args_list = _delegating_property('call_args_list')
606
+ mock_calls = _delegating_property('mock_calls')
607
+
608
+
609
+ def __get_side_effect(self):
610
+ delegated = self._mock_delegate
611
+ if delegated is None:
612
+ return self._mock_side_effect
613
+ sf = delegated.side_effect
614
+ if (sf is not None and not callable(sf)
615
+ and not isinstance(sf, _MockIter) and not _is_exception(sf)):
616
+ sf = _MockIter(sf)
617
+ delegated.side_effect = sf
618
+ return sf
619
+
620
+ def __set_side_effect(self, value):
621
+ value = _try_iter(value)
622
+ delegated = self._mock_delegate
623
+ if delegated is None:
624
+ self._mock_side_effect = value
625
+ else:
626
+ delegated.side_effect = value
627
+
628
+ side_effect = property(__get_side_effect, __set_side_effect)
629
+
630
+
631
+ def reset_mock(self, visited=None, *,
632
+ return_value: bool = False,
633
+ side_effect: bool = False):
634
+ "Restore the mock object to its initial state."
635
+ if visited is None:
636
+ visited = []
637
+ if id(self) in visited:
638
+ return
639
+ visited.append(id(self))
640
+
641
+ self.called = False
642
+ self.call_args = None
643
+ self.call_count = 0
644
+ self.mock_calls = _CallList()
645
+ self.call_args_list = _CallList()
646
+ self.method_calls = _CallList()
647
+
648
+ if return_value:
649
+ self._mock_return_value = DEFAULT
650
+ if side_effect:
651
+ self._mock_side_effect = None
652
+
653
+ for child in self._mock_children.values():
654
+ if isinstance(child, _SpecState) or child is _deleted:
655
+ continue
656
+ child.reset_mock(visited, return_value=return_value, side_effect=side_effect)
657
+
658
+ ret = self._mock_return_value
659
+ if _is_instance_mock(ret) and ret is not self:
660
+ ret.reset_mock(visited)
661
+
662
+
663
+ def configure_mock(self, /, **kwargs):
664
+ """Set attributes on the mock through keyword arguments.
665
+
666
+ Attributes plus return values and side effects can be set on child
667
+ mocks using standard dot notation and unpacking a dictionary in the
668
+ method call:
669
+
670
+ >>> attrs = {'method.return_value': 3, 'other.side_effect': KeyError}
671
+ >>> mock.configure_mock(**attrs)"""
672
+ for arg, val in sorted(kwargs.items(),
673
+ # we sort on the number of dots so that
674
+ # attributes are set before we set attributes on
675
+ # attributes
676
+ key=lambda entry: entry[0].count('.')):
677
+ args = arg.split('.')
678
+ final = args.pop()
679
+ obj = self
680
+ for entry in args:
681
+ obj = getattr(obj, entry)
682
+ setattr(obj, final, val)
683
+
684
+
685
+ def __getattr__(self, name):
686
+ if name in {'_mock_methods', '_mock_unsafe'}:
687
+ raise AttributeError(name)
688
+ elif self._mock_methods is not None:
689
+ if name not in self._mock_methods or name in _all_magics:
690
+ raise AttributeError("Mock object has no attribute %r" % name)
691
+ elif _is_magic(name):
692
+ raise AttributeError(name)
693
+ if not self._mock_unsafe and (not self._mock_methods or name not in self._mock_methods):
694
+ if name.startswith(('assert', 'assret', 'asert', 'aseert', 'assrt')) or name in _ATTRIB_DENY_LIST:
695
+ raise AttributeError(
696
+ f"{name!r} is not a valid assertion. Use a spec "
697
+ f"for the mock if {name!r} is meant to be an attribute.")
698
+
699
+ with NonCallableMock._lock:
700
+ result = self._mock_children.get(name)
701
+ if result is _deleted:
702
+ raise AttributeError(name)
703
+ elif result is None:
704
+ wraps = None
705
+ if self._mock_wraps is not None:
706
+ # XXXX should we get the attribute without triggering code
707
+ # execution?
708
+ wraps = getattr(self._mock_wraps, name)
709
+
710
+ result = self._get_child_mock(
711
+ parent=self, name=name, wraps=wraps, _new_name=name,
712
+ _new_parent=self
713
+ )
714
+ self._mock_children[name] = result
715
+
716
+ elif isinstance(result, _SpecState):
717
+ try:
718
+ result = create_autospec(
719
+ result.spec, result.spec_set, result.instance,
720
+ result.parent, result.name
721
+ )
722
+ except InvalidSpecError:
723
+ target_name = self.__dict__['_mock_name'] or self
724
+ raise InvalidSpecError(
725
+ f'Cannot autospec attr {name!r} from target '
726
+ f'{target_name!r} as it has already been mocked out. '
727
+ f'[target={self!r}, attr={result.spec!r}]')
728
+ self._mock_children[name] = result
729
+
730
+ return result
731
+
732
+
733
+ def _extract_mock_name(self):
734
+ _name_list = [self._mock_new_name]
735
+ _parent = self._mock_new_parent
736
+ last = self
737
+
738
+ dot = '.'
739
+ if _name_list == ['()']:
740
+ dot = ''
741
+
742
+ while _parent is not None:
743
+ last = _parent
744
+
745
+ _name_list.append(_parent._mock_new_name + dot)
746
+ dot = '.'
747
+ if _parent._mock_new_name == '()':
748
+ dot = ''
749
+
750
+ _parent = _parent._mock_new_parent
751
+
752
+ _name_list = list(reversed(_name_list))
753
+ _first = last._mock_name or 'mock'
754
+ if len(_name_list) > 1:
755
+ if _name_list[1] not in ('()', '().'):
756
+ _first += '.'
757
+ _name_list[0] = _first
758
+ return ''.join(_name_list)
759
+
760
+ def __repr__(self):
761
+ name = self._extract_mock_name()
762
+
763
+ name_string = ''
764
+ if name not in ('mock', 'mock.'):
765
+ name_string = ' name=%r' % name
766
+
767
+ spec_string = ''
768
+ if self._spec_class is not None:
769
+ spec_string = ' spec=%r'
770
+ if self._spec_set:
771
+ spec_string = ' spec_set=%r'
772
+ spec_string = spec_string % self._spec_class.__name__
773
+ return "<%s%s%s id='%s'>" % (
774
+ type(self).__name__,
775
+ name_string,
776
+ spec_string,
777
+ id(self)
778
+ )
779
+
780
+
781
+ def __dir__(self):
782
+ """Filter the output of `dir(mock)` to only useful members."""
783
+ if not FILTER_DIR:
784
+ return object.__dir__(self)
785
+
786
+ extras = self._mock_methods or []
787
+ from_type = dir(type(self))
788
+ from_dict = list(self.__dict__)
789
+ from_child_mocks = [
790
+ m_name for m_name, m_value in self._mock_children.items()
791
+ if m_value is not _deleted]
792
+
793
+ from_type = [e for e in from_type if not e.startswith('_')]
794
+ from_dict = [e for e in from_dict if not e.startswith('_') or
795
+ _is_magic(e)]
796
+ return sorted(set(extras + from_type + from_dict + from_child_mocks))
797
+
798
+
799
+ def __setattr__(self, name, value):
800
+ if name in _allowed_names:
801
+ # property setters go through here
802
+ return object.__setattr__(self, name, value)
803
+ elif (self._spec_set and self._mock_methods is not None and
804
+ name not in self._mock_methods and
805
+ name not in self.__dict__):
806
+ raise AttributeError("Mock object has no attribute '%s'" % name)
807
+ elif name in _unsupported_magics:
808
+ msg = 'Attempting to set unsupported magic method %r.' % name
809
+ raise AttributeError(msg)
810
+ elif name in _all_magics:
811
+ if self._mock_methods is not None and name not in self._mock_methods:
812
+ raise AttributeError("Mock object has no attribute '%s'" % name)
813
+
814
+ if not _is_instance_mock(value):
815
+ setattr(type(self), name, _get_method(name, value))
816
+ original = value
817
+ value = lambda *args, **kw: original(self, *args, **kw)
818
+ else:
819
+ # only set _new_name and not name so that mock_calls is tracked
820
+ # but not method calls
821
+ _check_and_set_parent(self, value, None, name)
822
+ setattr(type(self), name, value)
823
+ self._mock_children[name] = value
824
+ elif name == '__class__':
825
+ self._spec_class = value
826
+ return
827
+ else:
828
+ if _check_and_set_parent(self, value, name, name):
829
+ self._mock_children[name] = value
830
+
831
+ if self._mock_sealed and not hasattr(self, name):
832
+ mock_name = f'{self._extract_mock_name()}.{name}'
833
+ raise AttributeError(f'Cannot set {mock_name}')
834
+
835
+ if isinstance(value, PropertyMock):
836
+ self.__dict__[name] = value
837
+ return
838
+ return object.__setattr__(self, name, value)
839
+
840
+
841
+ def __delattr__(self, name):
842
+ if name in _all_magics and name in type(self).__dict__:
843
+ delattr(type(self), name)
844
+ if name not in self.__dict__:
845
+ # for magic methods that are still MagicProxy objects and
846
+ # not set on the instance itself
847
+ return
848
+
849
+ obj = self._mock_children.get(name, _missing)
850
+ if name in self.__dict__:
851
+ _safe_super(NonCallableMock, self).__delattr__(name)
852
+ elif obj is _deleted:
853
+ raise AttributeError(name)
854
+ if obj is not _missing:
855
+ del self._mock_children[name]
856
+ self._mock_children[name] = _deleted
857
+
858
+
859
+ def _format_mock_call_signature(self, args, kwargs):
860
+ name = self._mock_name or 'mock'
861
+ return _format_call_signature(name, args, kwargs)
862
+
863
+
864
+ def _format_mock_failure_message(self, args, kwargs, action='call'):
865
+ message = 'expected %s not found.\nExpected: %s\n Actual: %s'
866
+ expected_string = self._format_mock_call_signature(args, kwargs)
867
+ call_args = self.call_args
868
+ actual_string = self._format_mock_call_signature(*call_args)
869
+ return message % (action, expected_string, actual_string)
870
+
871
+
872
+ def _get_call_signature_from_name(self, name):
873
+ """
874
+ * If call objects are asserted against a method/function like obj.meth1
875
+ then there could be no name for the call object to lookup. Hence just
876
+ return the spec_signature of the method/function being asserted against.
877
+ * If the name is not empty then remove () and split by '.' to get
878
+ list of names to iterate through the children until a potential
879
+ match is found. A child mock is created only during attribute access
880
+ so if we get a _SpecState then no attributes of the spec were accessed
881
+ and can be safely exited.
882
+ """
883
+ if not name:
884
+ return self._spec_signature
885
+
886
+ sig = None
887
+ names = name.replace('()', '').split('.')
888
+ children = self._mock_children
889
+
890
+ for name in names:
891
+ child = children.get(name)
892
+ if child is None or isinstance(child, _SpecState):
893
+ break
894
+ else:
895
+ # If an autospecced object is attached using attach_mock the
896
+ # child would be a function with mock object as attribute from
897
+ # which signature has to be derived.
898
+ child = _extract_mock(child)
899
+ children = child._mock_children
900
+ sig = child._spec_signature
901
+
902
+ return sig
903
+
904
+
905
+ def _call_matcher(self, _call):
906
+ """
907
+ Given a call (or simply an (args, kwargs) tuple), return a
908
+ comparison key suitable for matching with other calls.
909
+ This is a best effort method which relies on the spec's signature,
910
+ if available, or falls back on the arguments themselves.
911
+ """
912
+
913
+ if isinstance(_call, tuple) and len(_call) > 2:
914
+ sig = self._get_call_signature_from_name(_call[0])
915
+ else:
916
+ sig = self._spec_signature
917
+
918
+ if sig is not None:
919
+ if len(_call) == 2:
920
+ name = ''
921
+ args, kwargs = _call
922
+ else:
923
+ name, args, kwargs = _call
924
+ try:
925
+ bound_call = sig.bind(*args, **kwargs)
926
+ return call(name, bound_call.args, bound_call.kwargs)
927
+ except TypeError as e:
928
+ return e.with_traceback(None)
929
+ else:
930
+ return _call
931
+
932
+ def assert_not_called(self):
933
+ """assert that the mock was never called.
934
+ """
935
+ if self.call_count != 0:
936
+ msg = ("Expected '%s' to not have been called. Called %s times.%s"
937
+ % (self._mock_name or 'mock',
938
+ self.call_count,
939
+ self._calls_repr()))
940
+ raise AssertionError(msg)
941
+
942
+ def assert_called(self):
943
+ """assert that the mock was called at least once
944
+ """
945
+ if self.call_count == 0:
946
+ msg = ("Expected '%s' to have been called." %
947
+ (self._mock_name or 'mock'))
948
+ raise AssertionError(msg)
949
+
950
+ def assert_called_once(self):
951
+ """assert that the mock was called only once.
952
+ """
953
+ if not self.call_count == 1:
954
+ msg = ("Expected '%s' to have been called once. Called %s times.%s"
955
+ % (self._mock_name or 'mock',
956
+ self.call_count,
957
+ self._calls_repr()))
958
+ raise AssertionError(msg)
959
+
960
+ def assert_called_with(self, /, *args, **kwargs):
961
+ """assert that the last call was made with the specified arguments.
962
+
963
+ Raises an AssertionError if the args and keyword args passed in are
964
+ different to the last call to the mock."""
965
+ if self.call_args is None:
966
+ expected = self._format_mock_call_signature(args, kwargs)
967
+ actual = 'not called.'
968
+ error_message = ('expected call not found.\nExpected: %s\n Actual: %s'
969
+ % (expected, actual))
970
+ raise AssertionError(error_message)
971
+
972
+ def _error_message():
973
+ msg = self._format_mock_failure_message(args, kwargs)
974
+ return msg
975
+ expected = self._call_matcher(_Call((args, kwargs), two=True))
976
+ actual = self._call_matcher(self.call_args)
977
+ if actual != expected:
978
+ cause = expected if isinstance(expected, Exception) else None
979
+ raise AssertionError(_error_message()) from cause
980
+
981
+
982
+ def assert_called_once_with(self, /, *args, **kwargs):
983
+ """assert that the mock was called exactly once and that that call was
984
+ with the specified arguments."""
985
+ if not self.call_count == 1:
986
+ msg = ("Expected '%s' to be called once. Called %s times.%s"
987
+ % (self._mock_name or 'mock',
988
+ self.call_count,
989
+ self._calls_repr()))
990
+ raise AssertionError(msg)
991
+ return self.assert_called_with(*args, **kwargs)
992
+
993
+
994
+ def assert_has_calls(self, calls, any_order=False):
995
+ """assert the mock has been called with the specified calls.
996
+ The `mock_calls` list is checked for the calls.
997
+
998
+ If `any_order` is False (the default) then the calls must be
999
+ sequential. There can be extra calls before or after the
1000
+ specified calls.
1001
+
1002
+ If `any_order` is True then the calls can be in any order, but
1003
+ they must all appear in `mock_calls`."""
1004
+ expected = [self._call_matcher(c) for c in calls]
1005
+ cause = next((e for e in expected if isinstance(e, Exception)), None)
1006
+ all_calls = _CallList(self._call_matcher(c) for c in self.mock_calls)
1007
+ if not any_order:
1008
+ if expected not in all_calls:
1009
+ if cause is None:
1010
+ problem = 'Calls not found.'
1011
+ else:
1012
+ problem = ('Error processing expected calls.\n'
1013
+ 'Errors: {}').format(
1014
+ [e if isinstance(e, Exception) else None
1015
+ for e in expected])
1016
+ raise AssertionError(
1017
+ f'{problem}\n'
1018
+ f'Expected: {_CallList(calls)}\n'
1019
+ f' Actual: {safe_repr(self.mock_calls)}'
1020
+ ) from cause
1021
+ return
1022
+
1023
+ all_calls = list(all_calls)
1024
+
1025
+ not_found = []
1026
+ for kall in expected:
1027
+ try:
1028
+ all_calls.remove(kall)
1029
+ except ValueError:
1030
+ not_found.append(kall)
1031
+ if not_found:
1032
+ raise AssertionError(
1033
+ '%r does not contain all of %r in its call list, '
1034
+ 'found %r instead' % (self._mock_name or 'mock',
1035
+ tuple(not_found), all_calls)
1036
+ ) from cause
1037
+
1038
+
1039
+ def assert_any_call(self, /, *args, **kwargs):
1040
+ """assert the mock has been called with the specified arguments.
1041
+
1042
+ The assert passes if the mock has *ever* been called, unlike
1043
+ `assert_called_with` and `assert_called_once_with` that only pass if
1044
+ the call is the most recent one."""
1045
+ expected = self._call_matcher(_Call((args, kwargs), two=True))
1046
+ cause = expected if isinstance(expected, Exception) else None
1047
+ actual = [self._call_matcher(c) for c in self.call_args_list]
1048
+ if cause or expected not in _AnyComparer(actual):
1049
+ expected_string = self._format_mock_call_signature(args, kwargs)
1050
+ raise AssertionError(
1051
+ '%s call not found' % expected_string
1052
+ ) from cause
1053
+
1054
+
1055
+ def _get_child_mock(self, /, **kw):
1056
+ """Create the child mocks for attributes and return value.
1057
+ By default child mocks will be the same type as the parent.
1058
+ Subclasses of Mock may want to override this to customize the way
1059
+ child mocks are made.
1060
+
1061
+ For non-callable mocks the callable variant will be used (rather than
1062
+ any custom subclass)."""
1063
+ if self._mock_sealed:
1064
+ attribute = f".{kw['name']}" if "name" in kw else "()"
1065
+ mock_name = self._extract_mock_name() + attribute
1066
+ raise AttributeError(mock_name)
1067
+
1068
+ _new_name = kw.get("_new_name")
1069
+ if _new_name in self.__dict__['_spec_asyncs']:
1070
+ return AsyncMock(**kw)
1071
+
1072
+ _type = type(self)
1073
+ if issubclass(_type, MagicMock) and _new_name in _async_method_magics:
1074
+ # Any asynchronous magic becomes an AsyncMock
1075
+ klass = AsyncMock
1076
+ elif issubclass(_type, AsyncMockMixin):
1077
+ if (_new_name in _all_sync_magics or
1078
+ self._mock_methods and _new_name in self._mock_methods):
1079
+ # Any synchronous method on AsyncMock becomes a MagicMock
1080
+ klass = MagicMock
1081
+ else:
1082
+ klass = AsyncMock
1083
+ elif not issubclass(_type, CallableMixin):
1084
+ if issubclass(_type, NonCallableMagicMock):
1085
+ klass = MagicMock
1086
+ elif issubclass(_type, NonCallableMock):
1087
+ klass = Mock
1088
+ else:
1089
+ klass = _type.__mro__[1]
1090
+ return klass(**kw)
1091
+
1092
+
1093
+ def _calls_repr(self):
1094
+ """Renders self.mock_calls as a string.
1095
+
1096
+ Example: "\nCalls: [call(1), call(2)]."
1097
+
1098
+ If self.mock_calls is empty, an empty string is returned. The
1099
+ output will be truncated if very long.
1100
+ """
1101
+ if not self.mock_calls:
1102
+ return ""
1103
+ return f"\nCalls: {safe_repr(self.mock_calls)}."
1104
+
1105
+
1106
+ # Denylist for forbidden attribute names in safe mode
1107
+ _ATTRIB_DENY_LIST = frozenset({
1108
+ name.removeprefix("assert_")
1109
+ for name in dir(NonCallableMock)
1110
+ if name.startswith("assert_")
1111
+ })
1112
+
1113
+
1114
+ class _AnyComparer(list):
1115
+ """A list which checks if it contains a call which may have an
1116
+ argument of ANY, flipping the components of item and self from
1117
+ their traditional locations so that ANY is guaranteed to be on
1118
+ the left."""
1119
+ def __contains__(self, item):
1120
+ for _call in self:
1121
+ assert len(item) == len(_call)
1122
+ if all([
1123
+ expected == actual
1124
+ for expected, actual in zip(item, _call)
1125
+ ]):
1126
+ return True
1127
+ return False
1128
+
1129
+
1130
+ def _try_iter(obj):
1131
+ if obj is None:
1132
+ return obj
1133
+ if _is_exception(obj):
1134
+ return obj
1135
+ if _callable(obj):
1136
+ return obj
1137
+ try:
1138
+ return iter(obj)
1139
+ except TypeError:
1140
+ # XXXX backwards compatibility
1141
+ # but this will blow up on first call - so maybe we should fail early?
1142
+ return obj
1143
+
1144
+
1145
+ class CallableMixin(Base):
1146
+
1147
+ def __init__(self, spec=None, side_effect=None, return_value=DEFAULT,
1148
+ wraps=None, name=None, spec_set=None, parent=None,
1149
+ _spec_state=None, _new_name='', _new_parent=None, **kwargs):
1150
+ self.__dict__['_mock_return_value'] = return_value
1151
+ _safe_super(CallableMixin, self).__init__(
1152
+ spec, wraps, name, spec_set, parent,
1153
+ _spec_state, _new_name, _new_parent, **kwargs
1154
+ )
1155
+
1156
+ self.side_effect = side_effect
1157
+
1158
+
1159
+ def _mock_check_sig(self, /, *args, **kwargs):
1160
+ # stub method that can be replaced with one with a specific signature
1161
+ pass
1162
+
1163
+
1164
+ def __call__(self, /, *args, **kwargs):
1165
+ # can't use self in-case a function / method we are mocking uses self
1166
+ # in the signature
1167
+ self._mock_check_sig(*args, **kwargs)
1168
+ self._increment_mock_call(*args, **kwargs)
1169
+ return self._mock_call(*args, **kwargs)
1170
+
1171
+
1172
+ def _mock_call(self, /, *args, **kwargs):
1173
+ return self._execute_mock_call(*args, **kwargs)
1174
+
1175
+ def _increment_mock_call(self, /, *args, **kwargs):
1176
+ self.called = True
1177
+
1178
+ # handle call_args
1179
+ # needs to be set here so assertions on call arguments pass before
1180
+ # execution in the case of awaited calls
1181
+ with NonCallableMock._lock:
1182
+ # Lock is used here so that call_args_list and call_count are
1183
+ # set atomically otherwise it is possible that by the time call_count
1184
+ # is set another thread may have appended to call_args_list.
1185
+ # The rest of this function relies on list.append being atomic and
1186
+ # skips locking.
1187
+ _call = _Call((args, kwargs), two=True)
1188
+ self.call_args = _call
1189
+ self.call_args_list.append(_call)
1190
+ self.call_count = len(self.call_args_list)
1191
+
1192
+ # initial stuff for method_calls:
1193
+ do_method_calls = self._mock_parent is not None
1194
+ method_call_name = self._mock_name
1195
+
1196
+ # initial stuff for mock_calls:
1197
+ mock_call_name = self._mock_new_name
1198
+ is_a_call = mock_call_name == '()'
1199
+ self.mock_calls.append(_Call(('', args, kwargs)))
1200
+
1201
+ # follow up the chain of mocks:
1202
+ _new_parent = self._mock_new_parent
1203
+ while _new_parent is not None:
1204
+
1205
+ # handle method_calls:
1206
+ if do_method_calls:
1207
+ _new_parent.method_calls.append(_Call((method_call_name, args, kwargs)))
1208
+ do_method_calls = _new_parent._mock_parent is not None
1209
+ if do_method_calls:
1210
+ method_call_name = _new_parent._mock_name + '.' + method_call_name
1211
+
1212
+ # handle mock_calls:
1213
+ this_mock_call = _Call((mock_call_name, args, kwargs))
1214
+ _new_parent.mock_calls.append(this_mock_call)
1215
+
1216
+ if _new_parent._mock_new_name:
1217
+ if is_a_call:
1218
+ dot = ''
1219
+ else:
1220
+ dot = '.'
1221
+ is_a_call = _new_parent._mock_new_name == '()'
1222
+ mock_call_name = _new_parent._mock_new_name + dot + mock_call_name
1223
+
1224
+ # follow the parental chain:
1225
+ _new_parent = _new_parent._mock_new_parent
1226
+
1227
+ def _execute_mock_call(self, /, *args, **kwargs):
1228
+ # separate from _increment_mock_call so that awaited functions are
1229
+ # executed separately from their call, also AsyncMock overrides this method
1230
+
1231
+ effect = self.side_effect
1232
+ if effect is not None:
1233
+ if _is_exception(effect):
1234
+ raise effect
1235
+ elif not _callable(effect):
1236
+ result = next(effect)
1237
+ if _is_exception(result):
1238
+ raise result
1239
+ else:
1240
+ result = effect(*args, **kwargs)
1241
+
1242
+ if result is not DEFAULT:
1243
+ return result
1244
+
1245
+ if self._mock_return_value is not DEFAULT:
1246
+ return self.return_value
1247
+
1248
+ if self._mock_delegate and self._mock_delegate.return_value is not DEFAULT:
1249
+ return self.return_value
1250
+
1251
+ if self._mock_wraps is not None:
1252
+ return self._mock_wraps(*args, **kwargs)
1253
+
1254
+ return self.return_value
1255
+
1256
+
1257
+
1258
+ class Mock(CallableMixin, NonCallableMock):
1259
+ """
1260
+ Create a new `Mock` object. `Mock` takes several optional arguments
1261
+ that specify the behaviour of the Mock object:
1262
+
1263
+ * `spec`: This can be either a list of strings or an existing object (a
1264
+ class or instance) that acts as the specification for the mock object. If
1265
+ you pass in an object then a list of strings is formed by calling dir on
1266
+ the object (excluding unsupported magic attributes and methods). Accessing
1267
+ any attribute not in this list will raise an `AttributeError`.
1268
+
1269
+ If `spec` is an object (rather than a list of strings) then
1270
+ `mock.__class__` returns the class of the spec object. This allows mocks
1271
+ to pass `isinstance` tests.
1272
+
1273
+ * `spec_set`: A stricter variant of `spec`. If used, attempting to *set*
1274
+ or get an attribute on the mock that isn't on the object passed as
1275
+ `spec_set` will raise an `AttributeError`.
1276
+
1277
+ * `side_effect`: A function to be called whenever the Mock is called. See
1278
+ the `side_effect` attribute. Useful for raising exceptions or
1279
+ dynamically changing return values. The function is called with the same
1280
+ arguments as the mock, and unless it returns `DEFAULT`, the return
1281
+ value of this function is used as the return value.
1282
+
1283
+ If `side_effect` is an iterable then each call to the mock will return
1284
+ the next value from the iterable. If any of the members of the iterable
1285
+ are exceptions they will be raised instead of returned.
1286
+
1287
+ * `return_value`: The value returned when the mock is called. By default
1288
+ this is a new Mock (created on first access). See the
1289
+ `return_value` attribute.
1290
+
1291
+ * `unsafe`: By default, accessing any attribute whose name starts with
1292
+ *assert*, *assret*, *asert*, *aseert*, or *assrt* raises an AttributeError.
1293
+ Additionally, an AttributeError is raised when accessing
1294
+ attributes that match the name of an assertion method without the prefix
1295
+ `assert_`, e.g. accessing `called_once` instead of `assert_called_once`.
1296
+ Passing `unsafe=True` will allow access to these attributes.
1297
+
1298
+ * `wraps`: Item for the mock object to wrap. If `wraps` is not None then
1299
+ calling the Mock will pass the call through to the wrapped object
1300
+ (returning the real result). Attribute access on the mock will return a
1301
+ Mock object that wraps the corresponding attribute of the wrapped object
1302
+ (so attempting to access an attribute that doesn't exist will raise an
1303
+ `AttributeError`).
1304
+
1305
+ If the mock has an explicit `return_value` set then calls are not passed
1306
+ to the wrapped object and the `return_value` is returned instead.
1307
+
1308
+ * `name`: If the mock has a name then it will be used in the repr of the
1309
+ mock. This can be useful for debugging. The name is propagated to child
1310
+ mocks.
1311
+
1312
+ Mocks can also be called with arbitrary keyword arguments. These will be
1313
+ used to set attributes on the mock after it is created.
1314
+ """
1315
+
1316
+
1317
+ # _check_spec_arg_typos takes kwargs from commands like patch and checks that
1318
+ # they don't contain common misspellings of arguments related to autospeccing.
1319
+ def _check_spec_arg_typos(kwargs_to_check):
1320
+ typos = ("autospect", "auto_spec", "set_spec")
1321
+ for typo in typos:
1322
+ if typo in kwargs_to_check:
1323
+ raise RuntimeError(
1324
+ f"{typo!r} might be a typo; use unsafe=True if this is intended"
1325
+ )
1326
+
1327
+
1328
+ class _patch(object):
1329
+
1330
+ attribute_name = None
1331
+ _active_patches = []
1332
+
1333
+ def __init__(
1334
+ self, getter, attribute, new, spec, create,
1335
+ spec_set, autospec, new_callable, kwargs, *, unsafe=False
1336
+ ):
1337
+ if new_callable is not None:
1338
+ if new is not DEFAULT:
1339
+ raise ValueError(
1340
+ "Cannot use 'new' and 'new_callable' together"
1341
+ )
1342
+ if autospec is not None:
1343
+ raise ValueError(
1344
+ "Cannot use 'autospec' and 'new_callable' together"
1345
+ )
1346
+ if not unsafe:
1347
+ _check_spec_arg_typos(kwargs)
1348
+ if _is_instance_mock(spec):
1349
+ raise InvalidSpecError(
1350
+ f'Cannot spec attr {attribute!r} as the spec '
1351
+ f'has already been mocked out. [spec={spec!r}]')
1352
+ if _is_instance_mock(spec_set):
1353
+ raise InvalidSpecError(
1354
+ f'Cannot spec attr {attribute!r} as the spec_set '
1355
+ f'target has already been mocked out. [spec_set={spec_set!r}]')
1356
+
1357
+ self.getter = getter
1358
+ self.attribute = attribute
1359
+ self.new = new
1360
+ self.new_callable = new_callable
1361
+ self.spec = spec
1362
+ self.create = create
1363
+ self.has_local = False
1364
+ self.spec_set = spec_set
1365
+ self.autospec = autospec
1366
+ self.kwargs = kwargs
1367
+ self.additional_patchers = []
1368
+ self.is_started = False
1369
+
1370
+
1371
+ def copy(self):
1372
+ patcher = _patch(
1373
+ self.getter, self.attribute, self.new, self.spec,
1374
+ self.create, self.spec_set,
1375
+ self.autospec, self.new_callable, self.kwargs
1376
+ )
1377
+ patcher.attribute_name = self.attribute_name
1378
+ patcher.additional_patchers = [
1379
+ p.copy() for p in self.additional_patchers
1380
+ ]
1381
+ return patcher
1382
+
1383
+
1384
+ def __call__(self, func):
1385
+ if isinstance(func, type):
1386
+ return self.decorate_class(func)
1387
+ if inspect.iscoroutinefunction(func):
1388
+ return self.decorate_async_callable(func)
1389
+ return self.decorate_callable(func)
1390
+
1391
+
1392
+ def decorate_class(self, klass):
1393
+ for attr in dir(klass):
1394
+ if not attr.startswith(patch.TEST_PREFIX):
1395
+ continue
1396
+
1397
+ attr_value = getattr(klass, attr)
1398
+ if not hasattr(attr_value, "__call__"):
1399
+ continue
1400
+
1401
+ patcher = self.copy()
1402
+ setattr(klass, attr, patcher(attr_value))
1403
+ return klass
1404
+
1405
+
1406
+ @contextlib.contextmanager
1407
+ def decoration_helper(self, patched, args, keywargs):
1408
+ extra_args = []
1409
+ with contextlib.ExitStack() as exit_stack:
1410
+ for patching in patched.patchings:
1411
+ arg = exit_stack.enter_context(patching)
1412
+ if patching.attribute_name is not None:
1413
+ keywargs.update(arg)
1414
+ elif patching.new is DEFAULT:
1415
+ extra_args.append(arg)
1416
+
1417
+ args += tuple(extra_args)
1418
+ yield (args, keywargs)
1419
+
1420
+
1421
+ def decorate_callable(self, func):
1422
+ # NB. Keep the method in sync with decorate_async_callable()
1423
+ if hasattr(func, 'patchings'):
1424
+ func.patchings.append(self)
1425
+ return func
1426
+
1427
+ @wraps(func)
1428
+ def patched(*args, **keywargs):
1429
+ with self.decoration_helper(patched,
1430
+ args,
1431
+ keywargs) as (newargs, newkeywargs):
1432
+ return func(*newargs, **newkeywargs)
1433
+
1434
+ patched.patchings = [self]
1435
+ return patched
1436
+
1437
+
1438
+ def decorate_async_callable(self, func):
1439
+ # NB. Keep the method in sync with decorate_callable()
1440
+ if hasattr(func, 'patchings'):
1441
+ func.patchings.append(self)
1442
+ return func
1443
+
1444
+ @wraps(func)
1445
+ async def patched(*args, **keywargs):
1446
+ with self.decoration_helper(patched,
1447
+ args,
1448
+ keywargs) as (newargs, newkeywargs):
1449
+ return await func(*newargs, **newkeywargs)
1450
+
1451
+ patched.patchings = [self]
1452
+ return patched
1453
+
1454
+
1455
+ def get_original(self):
1456
+ target = self.getter()
1457
+ name = self.attribute
1458
+
1459
+ original = DEFAULT
1460
+ local = False
1461
+
1462
+ try:
1463
+ original = target.__dict__[name]
1464
+ except (AttributeError, KeyError):
1465
+ original = getattr(target, name, DEFAULT)
1466
+ else:
1467
+ local = True
1468
+
1469
+ if name in _builtins and isinstance(target, ModuleType):
1470
+ self.create = True
1471
+
1472
+ if not self.create and original is DEFAULT:
1473
+ raise AttributeError(
1474
+ "%s does not have the attribute %r" % (target, name)
1475
+ )
1476
+ return original, local
1477
+
1478
+
1479
+ def __enter__(self):
1480
+ """Perform the patch."""
1481
+ if self.is_started:
1482
+ raise RuntimeError("Patch is already started")
1483
+
1484
+ new, spec, spec_set = self.new, self.spec, self.spec_set
1485
+ autospec, kwargs = self.autospec, self.kwargs
1486
+ new_callable = self.new_callable
1487
+ self.target = self.getter()
1488
+
1489
+ # normalise False to None
1490
+ if spec is False:
1491
+ spec = None
1492
+ if spec_set is False:
1493
+ spec_set = None
1494
+ if autospec is False:
1495
+ autospec = None
1496
+
1497
+ if spec is not None and autospec is not None:
1498
+ raise TypeError("Can't specify spec and autospec")
1499
+ if ((spec is not None or autospec is not None) and
1500
+ spec_set not in (True, None)):
1501
+ raise TypeError("Can't provide explicit spec_set *and* spec or autospec")
1502
+
1503
+ original, local = self.get_original()
1504
+
1505
+ if new is DEFAULT and autospec is None:
1506
+ inherit = False
1507
+ if spec is True:
1508
+ # set spec to the object we are replacing
1509
+ spec = original
1510
+ if spec_set is True:
1511
+ spec_set = original
1512
+ spec = None
1513
+ elif spec is not None:
1514
+ if spec_set is True:
1515
+ spec_set = spec
1516
+ spec = None
1517
+ elif spec_set is True:
1518
+ spec_set = original
1519
+
1520
+ if spec is not None or spec_set is not None:
1521
+ if original is DEFAULT:
1522
+ raise TypeError("Can't use 'spec' with create=True")
1523
+ if isinstance(original, type):
1524
+ # If we're patching out a class and there is a spec
1525
+ inherit = True
1526
+
1527
+ # Determine the Klass to use
1528
+ if new_callable is not None:
1529
+ Klass = new_callable
1530
+ elif spec is None and _is_async_obj(original):
1531
+ Klass = AsyncMock
1532
+ elif spec is not None or spec_set is not None:
1533
+ this_spec = spec
1534
+ if spec_set is not None:
1535
+ this_spec = spec_set
1536
+ if _is_list(this_spec):
1537
+ not_callable = '__call__' not in this_spec
1538
+ else:
1539
+ not_callable = not callable(this_spec)
1540
+ if _is_async_obj(this_spec):
1541
+ Klass = AsyncMock
1542
+ elif not_callable:
1543
+ Klass = NonCallableMagicMock
1544
+ else:
1545
+ Klass = MagicMock
1546
+ else:
1547
+ Klass = MagicMock
1548
+
1549
+ _kwargs = {}
1550
+ if spec is not None:
1551
+ _kwargs['spec'] = spec
1552
+ if spec_set is not None:
1553
+ _kwargs['spec_set'] = spec_set
1554
+
1555
+ # add a name to mocks
1556
+ if (isinstance(Klass, type) and
1557
+ issubclass(Klass, NonCallableMock) and self.attribute):
1558
+ _kwargs['name'] = self.attribute
1559
+
1560
+ _kwargs.update(kwargs)
1561
+ new = Klass(**_kwargs)
1562
+
1563
+ if inherit and _is_instance_mock(new):
1564
+ # we can only tell if the instance should be callable if the
1565
+ # spec is not a list
1566
+ this_spec = spec
1567
+ if spec_set is not None:
1568
+ this_spec = spec_set
1569
+ if (not _is_list(this_spec) and not
1570
+ _instance_callable(this_spec)):
1571
+ Klass = NonCallableMagicMock
1572
+
1573
+ _kwargs.pop('name')
1574
+ new.return_value = Klass(_new_parent=new, _new_name='()',
1575
+ **_kwargs)
1576
+ elif autospec is not None:
1577
+ # spec is ignored, new *must* be default, spec_set is treated
1578
+ # as a boolean. Should we check spec is not None and that spec_set
1579
+ # is a bool?
1580
+ if new is not DEFAULT:
1581
+ raise TypeError(
1582
+ "autospec creates the mock for you. Can't specify "
1583
+ "autospec and new."
1584
+ )
1585
+ if original is DEFAULT:
1586
+ raise TypeError("Can't use 'autospec' with create=True")
1587
+ spec_set = bool(spec_set)
1588
+ if autospec is True:
1589
+ autospec = original
1590
+
1591
+ if _is_instance_mock(self.target):
1592
+ raise InvalidSpecError(
1593
+ f'Cannot autospec attr {self.attribute!r} as the patch '
1594
+ f'target has already been mocked out. '
1595
+ f'[target={self.target!r}, attr={autospec!r}]')
1596
+ if _is_instance_mock(autospec):
1597
+ target_name = getattr(self.target, '__name__', self.target)
1598
+ raise InvalidSpecError(
1599
+ f'Cannot autospec attr {self.attribute!r} from target '
1600
+ f'{target_name!r} as it has already been mocked out. '
1601
+ f'[target={self.target!r}, attr={autospec!r}]')
1602
+
1603
+ new = create_autospec(autospec, spec_set=spec_set,
1604
+ _name=self.attribute, **kwargs)
1605
+ elif kwargs:
1606
+ # can't set keyword args when we aren't creating the mock
1607
+ # XXXX If new is a Mock we could call new.configure_mock(**kwargs)
1608
+ raise TypeError("Can't pass kwargs to a mock we aren't creating")
1609
+
1610
+ new_attr = new
1611
+
1612
+ self.temp_original = original
1613
+ self.is_local = local
1614
+ self._exit_stack = contextlib.ExitStack()
1615
+ self.is_started = True
1616
+ try:
1617
+ setattr(self.target, self.attribute, new_attr)
1618
+ if self.attribute_name is not None:
1619
+ extra_args = {}
1620
+ if self.new is DEFAULT:
1621
+ extra_args[self.attribute_name] = new
1622
+ for patching in self.additional_patchers:
1623
+ arg = self._exit_stack.enter_context(patching)
1624
+ if patching.new is DEFAULT:
1625
+ extra_args.update(arg)
1626
+ return extra_args
1627
+
1628
+ return new
1629
+ except:
1630
+ if not self.__exit__(*sys.exc_info()):
1631
+ raise
1632
+
1633
+ def __exit__(self, *exc_info):
1634
+ """Undo the patch."""
1635
+ if not self.is_started:
1636
+ return
1637
+
1638
+ if self.is_local and self.temp_original is not DEFAULT:
1639
+ setattr(self.target, self.attribute, self.temp_original)
1640
+ else:
1641
+ delattr(self.target, self.attribute)
1642
+ if not self.create and (not hasattr(self.target, self.attribute) or
1643
+ self.attribute in ('__doc__', '__module__',
1644
+ '__defaults__', '__annotations__',
1645
+ '__kwdefaults__')):
1646
+ # needed for proxy objects like django settings
1647
+ setattr(self.target, self.attribute, self.temp_original)
1648
+
1649
+ del self.temp_original
1650
+ del self.is_local
1651
+ del self.target
1652
+ exit_stack = self._exit_stack
1653
+ del self._exit_stack
1654
+ self.is_started = False
1655
+ return exit_stack.__exit__(*exc_info)
1656
+
1657
+
1658
+ def start(self):
1659
+ """Activate a patch, returning any created mock."""
1660
+ result = self.__enter__()
1661
+ self._active_patches.append(self)
1662
+ return result
1663
+
1664
+
1665
+ def stop(self):
1666
+ """Stop an active patch."""
1667
+ try:
1668
+ self._active_patches.remove(self)
1669
+ except ValueError:
1670
+ # If the patch hasn't been started this will fail
1671
+ return None
1672
+
1673
+ return self.__exit__(None, None, None)
1674
+
1675
+
1676
+
1677
+ def _get_target(target):
1678
+ try:
1679
+ target, attribute = target.rsplit('.', 1)
1680
+ except (TypeError, ValueError, AttributeError):
1681
+ raise TypeError(
1682
+ f"Need a valid target to patch. You supplied: {target!r}")
1683
+ return partial(pkgutil.resolve_name, target), attribute
1684
+
1685
+
1686
+ def _patch_object(
1687
+ target, attribute, new=DEFAULT, spec=None,
1688
+ create=False, spec_set=None, autospec=None,
1689
+ new_callable=None, *, unsafe=False, **kwargs
1690
+ ):
1691
+ """
1692
+ patch the named member (`attribute`) on an object (`target`) with a mock
1693
+ object.
1694
+
1695
+ `patch.object` can be used as a decorator, class decorator or a context
1696
+ manager. Arguments `new`, `spec`, `create`, `spec_set`,
1697
+ `autospec` and `new_callable` have the same meaning as for `patch`. Like
1698
+ `patch`, `patch.object` takes arbitrary keyword arguments for configuring
1699
+ the mock object it creates.
1700
+
1701
+ When used as a class decorator `patch.object` honours `patch.TEST_PREFIX`
1702
+ for choosing which methods to wrap.
1703
+ """
1704
+ if type(target) is str:
1705
+ raise TypeError(
1706
+ f"{target!r} must be the actual object to be patched, not a str"
1707
+ )
1708
+ getter = lambda: target
1709
+ return _patch(
1710
+ getter, attribute, new, spec, create,
1711
+ spec_set, autospec, new_callable, kwargs, unsafe=unsafe
1712
+ )
1713
+
1714
+
1715
+ def _patch_multiple(target, spec=None, create=False, spec_set=None,
1716
+ autospec=None, new_callable=None, **kwargs):
1717
+ """Perform multiple patches in a single call. It takes the object to be
1718
+ patched (either as an object or a string to fetch the object by importing)
1719
+ and keyword arguments for the patches::
1720
+
1721
+ with patch.multiple(settings, FIRST_PATCH='one', SECOND_PATCH='two'):
1722
+ ...
1723
+
1724
+ Use `DEFAULT` as the value if you want `patch.multiple` to create
1725
+ mocks for you. In this case the created mocks are passed into a decorated
1726
+ function by keyword, and a dictionary is returned when `patch.multiple` is
1727
+ used as a context manager.
1728
+
1729
+ `patch.multiple` can be used as a decorator, class decorator or a context
1730
+ manager. The arguments `spec`, `spec_set`, `create`,
1731
+ `autospec` and `new_callable` have the same meaning as for `patch`. These
1732
+ arguments will be applied to *all* patches done by `patch.multiple`.
1733
+
1734
+ When used as a class decorator `patch.multiple` honours `patch.TEST_PREFIX`
1735
+ for choosing which methods to wrap.
1736
+ """
1737
+ if type(target) is str:
1738
+ getter = partial(pkgutil.resolve_name, target)
1739
+ else:
1740
+ getter = lambda: target
1741
+
1742
+ if not kwargs:
1743
+ raise ValueError(
1744
+ 'Must supply at least one keyword argument with patch.multiple'
1745
+ )
1746
+ # need to wrap in a list for python 3, where items is a view
1747
+ items = list(kwargs.items())
1748
+ attribute, new = items[0]
1749
+ patcher = _patch(
1750
+ getter, attribute, new, spec, create, spec_set,
1751
+ autospec, new_callable, {}
1752
+ )
1753
+ patcher.attribute_name = attribute
1754
+ for attribute, new in items[1:]:
1755
+ this_patcher = _patch(
1756
+ getter, attribute, new, spec, create, spec_set,
1757
+ autospec, new_callable, {}
1758
+ )
1759
+ this_patcher.attribute_name = attribute
1760
+ patcher.additional_patchers.append(this_patcher)
1761
+ return patcher
1762
+
1763
+
1764
+ def patch(
1765
+ target, new=DEFAULT, spec=None, create=False,
1766
+ spec_set=None, autospec=None, new_callable=None, *, unsafe=False, **kwargs
1767
+ ):
1768
+ """
1769
+ `patch` acts as a function decorator, class decorator or a context
1770
+ manager. Inside the body of the function or with statement, the `target`
1771
+ is patched with a `new` object. When the function/with statement exits
1772
+ the patch is undone.
1773
+
1774
+ If `new` is omitted, then the target is replaced with an
1775
+ `AsyncMock if the patched object is an async function or a
1776
+ `MagicMock` otherwise. If `patch` is used as a decorator and `new` is
1777
+ omitted, the created mock is passed in as an extra argument to the
1778
+ decorated function. If `patch` is used as a context manager the created
1779
+ mock is returned by the context manager.
1780
+
1781
+ `target` should be a string in the form `'package.module.ClassName'`. The
1782
+ `target` is imported and the specified object replaced with the `new`
1783
+ object, so the `target` must be importable from the environment you are
1784
+ calling `patch` from. The target is imported when the decorated function
1785
+ is executed, not at decoration time.
1786
+
1787
+ The `spec` and `spec_set` keyword arguments are passed to the `MagicMock`
1788
+ if patch is creating one for you.
1789
+
1790
+ In addition you can pass `spec=True` or `spec_set=True`, which causes
1791
+ patch to pass in the object being mocked as the spec/spec_set object.
1792
+
1793
+ `new_callable` allows you to specify a different class, or callable object,
1794
+ that will be called to create the `new` object. By default `AsyncMock` is
1795
+ used for async functions and `MagicMock` for the rest.
1796
+
1797
+ A more powerful form of `spec` is `autospec`. If you set `autospec=True`
1798
+ then the mock will be created with a spec from the object being replaced.
1799
+ All attributes of the mock will also have the spec of the corresponding
1800
+ attribute of the object being replaced. Methods and functions being
1801
+ mocked will have their arguments checked and will raise a `TypeError` if
1802
+ they are called with the wrong signature. For mocks replacing a class,
1803
+ their return value (the 'instance') will have the same spec as the class.
1804
+
1805
+ Instead of `autospec=True` you can pass `autospec=some_object` to use an
1806
+ arbitrary object as the spec instead of the one being replaced.
1807
+
1808
+ By default `patch` will fail to replace attributes that don't exist. If
1809
+ you pass in `create=True`, and the attribute doesn't exist, patch will
1810
+ create the attribute for you when the patched function is called, and
1811
+ delete it again afterwards. This is useful for writing tests against
1812
+ attributes that your production code creates at runtime. It is off by
1813
+ default because it can be dangerous. With it switched on you can write
1814
+ passing tests against APIs that don't actually exist!
1815
+
1816
+ Patch can be used as a `TestCase` class decorator. It works by
1817
+ decorating each test method in the class. This reduces the boilerplate
1818
+ code when your test methods share a common patchings set. `patch` finds
1819
+ tests by looking for method names that start with `patch.TEST_PREFIX`.
1820
+ By default this is `test`, which matches the way `unittest` finds tests.
1821
+ You can specify an alternative prefix by setting `patch.TEST_PREFIX`.
1822
+
1823
+ Patch can be used as a context manager, with the with statement. Here the
1824
+ patching applies to the indented block after the with statement. If you
1825
+ use "as" then the patched object will be bound to the name after the
1826
+ "as"; very useful if `patch` is creating a mock object for you.
1827
+
1828
+ Patch will raise a `RuntimeError` if passed some common misspellings of
1829
+ the arguments autospec and spec_set. Pass the argument `unsafe` with the
1830
+ value True to disable that check.
1831
+
1832
+ `patch` takes arbitrary keyword arguments. These will be passed to
1833
+ `AsyncMock` if the patched object is asynchronous, to `MagicMock`
1834
+ otherwise or to `new_callable` if specified.
1835
+
1836
+ `patch.dict(...)`, `patch.multiple(...)` and `patch.object(...)` are
1837
+ available for alternate use-cases.
1838
+ """
1839
+ getter, attribute = _get_target(target)
1840
+ return _patch(
1841
+ getter, attribute, new, spec, create,
1842
+ spec_set, autospec, new_callable, kwargs, unsafe=unsafe
1843
+ )
1844
+
1845
+
1846
+ class _patch_dict(object):
1847
+ """
1848
+ Patch a dictionary, or dictionary like object, and restore the dictionary
1849
+ to its original state after the test.
1850
+
1851
+ `in_dict` can be a dictionary or a mapping like container. If it is a
1852
+ mapping then it must at least support getting, setting and deleting items
1853
+ plus iterating over keys.
1854
+
1855
+ `in_dict` can also be a string specifying the name of the dictionary, which
1856
+ will then be fetched by importing it.
1857
+
1858
+ `values` can be a dictionary of values to set in the dictionary. `values`
1859
+ can also be an iterable of `(key, value)` pairs.
1860
+
1861
+ If `clear` is True then the dictionary will be cleared before the new
1862
+ values are set.
1863
+
1864
+ `patch.dict` can also be called with arbitrary keyword arguments to set
1865
+ values in the dictionary::
1866
+
1867
+ with patch.dict('sys.modules', mymodule=Mock(), other_module=Mock()):
1868
+ ...
1869
+
1870
+ `patch.dict` can be used as a context manager, decorator or class
1871
+ decorator. When used as a class decorator `patch.dict` honours
1872
+ `patch.TEST_PREFIX` for choosing which methods to wrap.
1873
+ """
1874
+
1875
+ def __init__(self, in_dict, values=(), clear=False, **kwargs):
1876
+ self.in_dict = in_dict
1877
+ # support any argument supported by dict(...) constructor
1878
+ self.values = dict(values)
1879
+ self.values.update(kwargs)
1880
+ self.clear = clear
1881
+ self._original = None
1882
+
1883
+
1884
+ def __call__(self, f):
1885
+ if isinstance(f, type):
1886
+ return self.decorate_class(f)
1887
+ if inspect.iscoroutinefunction(f):
1888
+ return self.decorate_async_callable(f)
1889
+ return self.decorate_callable(f)
1890
+
1891
+
1892
+ def decorate_callable(self, f):
1893
+ @wraps(f)
1894
+ def _inner(*args, **kw):
1895
+ self._patch_dict()
1896
+ try:
1897
+ return f(*args, **kw)
1898
+ finally:
1899
+ self._unpatch_dict()
1900
+
1901
+ return _inner
1902
+
1903
+
1904
+ def decorate_async_callable(self, f):
1905
+ @wraps(f)
1906
+ async def _inner(*args, **kw):
1907
+ self._patch_dict()
1908
+ try:
1909
+ return await f(*args, **kw)
1910
+ finally:
1911
+ self._unpatch_dict()
1912
+
1913
+ return _inner
1914
+
1915
+
1916
+ def decorate_class(self, klass):
1917
+ for attr in dir(klass):
1918
+ attr_value = getattr(klass, attr)
1919
+ if (attr.startswith(patch.TEST_PREFIX) and
1920
+ hasattr(attr_value, "__call__")):
1921
+ decorator = _patch_dict(self.in_dict, self.values, self.clear)
1922
+ decorated = decorator(attr_value)
1923
+ setattr(klass, attr, decorated)
1924
+ return klass
1925
+
1926
+
1927
+ def __enter__(self):
1928
+ """Patch the dict."""
1929
+ self._patch_dict()
1930
+ return self.in_dict
1931
+
1932
+
1933
+ def _patch_dict(self):
1934
+ values = self.values
1935
+ if isinstance(self.in_dict, str):
1936
+ self.in_dict = pkgutil.resolve_name(self.in_dict)
1937
+ in_dict = self.in_dict
1938
+ clear = self.clear
1939
+
1940
+ try:
1941
+ original = in_dict.copy()
1942
+ except AttributeError:
1943
+ # dict like object with no copy method
1944
+ # must support iteration over keys
1945
+ original = {}
1946
+ for key in in_dict:
1947
+ original[key] = in_dict[key]
1948
+ self._original = original
1949
+
1950
+ if clear:
1951
+ _clear_dict(in_dict)
1952
+
1953
+ try:
1954
+ in_dict.update(values)
1955
+ except AttributeError:
1956
+ # dict like object with no update method
1957
+ for key in values:
1958
+ in_dict[key] = values[key]
1959
+
1960
+
1961
+ def _unpatch_dict(self):
1962
+ in_dict = self.in_dict
1963
+ original = self._original
1964
+
1965
+ _clear_dict(in_dict)
1966
+
1967
+ try:
1968
+ in_dict.update(original)
1969
+ except AttributeError:
1970
+ for key in original:
1971
+ in_dict[key] = original[key]
1972
+
1973
+
1974
+ def __exit__(self, *args):
1975
+ """Unpatch the dict."""
1976
+ if self._original is not None:
1977
+ self._unpatch_dict()
1978
+ return False
1979
+
1980
+
1981
+ def start(self):
1982
+ """Activate a patch, returning any created mock."""
1983
+ result = self.__enter__()
1984
+ _patch._active_patches.append(self)
1985
+ return result
1986
+
1987
+
1988
+ def stop(self):
1989
+ """Stop an active patch."""
1990
+ try:
1991
+ _patch._active_patches.remove(self)
1992
+ except ValueError:
1993
+ # If the patch hasn't been started this will fail
1994
+ return None
1995
+
1996
+ return self.__exit__(None, None, None)
1997
+
1998
+
1999
+ def _clear_dict(in_dict):
2000
+ try:
2001
+ in_dict.clear()
2002
+ except AttributeError:
2003
+ keys = list(in_dict)
2004
+ for key in keys:
2005
+ del in_dict[key]
2006
+
2007
+
2008
+ def _patch_stopall():
2009
+ """Stop all active patches. LIFO to unroll nested patches."""
2010
+ for patch in reversed(_patch._active_patches):
2011
+ patch.stop()
2012
+
2013
+
2014
+ patch.object = _patch_object
2015
+ patch.dict = _patch_dict
2016
+ patch.multiple = _patch_multiple
2017
+ patch.stopall = _patch_stopall
2018
+ patch.TEST_PREFIX = 'test'
2019
+
2020
+ magic_methods = (
2021
+ "lt le gt ge eq ne "
2022
+ "getitem setitem delitem "
2023
+ "len contains iter "
2024
+ "hash str sizeof "
2025
+ "enter exit "
2026
+ # we added divmod and rdivmod here instead of numerics
2027
+ # because there is no idivmod
2028
+ "divmod rdivmod neg pos abs invert "
2029
+ "complex int float index "
2030
+ "round trunc floor ceil "
2031
+ "bool next "
2032
+ "fspath "
2033
+ "aiter "
2034
+ )
2035
+
2036
+ numerics = (
2037
+ "add sub mul matmul truediv floordiv mod lshift rshift and xor or pow"
2038
+ )
2039
+ inplace = ' '.join('i%s' % n for n in numerics.split())
2040
+ right = ' '.join('r%s' % n for n in numerics.split())
2041
+
2042
+ # not including __prepare__, __instancecheck__, __subclasscheck__
2043
+ # (as they are metaclass methods)
2044
+ # __del__ is not supported at all as it causes problems if it exists
2045
+
2046
+ _non_defaults = {
2047
+ '__get__', '__set__', '__delete__', '__reversed__', '__missing__',
2048
+ '__reduce__', '__reduce_ex__', '__getinitargs__', '__getnewargs__',
2049
+ '__getstate__', '__setstate__', '__getformat__',
2050
+ '__repr__', '__dir__', '__subclasses__', '__format__',
2051
+ '__getnewargs_ex__',
2052
+ }
2053
+
2054
+
2055
+ def _get_method(name, func):
2056
+ "Turns a callable object (like a mock) into a real function"
2057
+ def method(self, /, *args, **kw):
2058
+ return func(self, *args, **kw)
2059
+ method.__name__ = name
2060
+ return method
2061
+
2062
+
2063
+ _magics = {
2064
+ '__%s__' % method for method in
2065
+ ' '.join([magic_methods, numerics, inplace, right]).split()
2066
+ }
2067
+
2068
+ # Magic methods used for async `with` statements
2069
+ _async_method_magics = {"__aenter__", "__aexit__", "__anext__"}
2070
+ # Magic methods that are only used with async calls but are synchronous functions themselves
2071
+ _sync_async_magics = {"__aiter__"}
2072
+ _async_magics = _async_method_magics | _sync_async_magics
2073
+
2074
+ _all_sync_magics = _magics | _non_defaults
2075
+ _all_magics = _all_sync_magics | _async_magics
2076
+
2077
+ _unsupported_magics = {
2078
+ '__getattr__', '__setattr__',
2079
+ '__init__', '__new__', '__prepare__',
2080
+ '__instancecheck__', '__subclasscheck__',
2081
+ '__del__'
2082
+ }
2083
+
2084
+ _calculate_return_value = {
2085
+ '__hash__': lambda self: object.__hash__(self),
2086
+ '__str__': lambda self: object.__str__(self),
2087
+ '__sizeof__': lambda self: object.__sizeof__(self),
2088
+ '__fspath__': lambda self: f"{type(self).__name__}/{self._extract_mock_name()}/{id(self)}",
2089
+ }
2090
+
2091
+ _return_values = {
2092
+ '__lt__': NotImplemented,
2093
+ '__gt__': NotImplemented,
2094
+ '__le__': NotImplemented,
2095
+ '__ge__': NotImplemented,
2096
+ '__int__': 1,
2097
+ '__contains__': False,
2098
+ '__len__': 0,
2099
+ '__exit__': False,
2100
+ '__complex__': 1j,
2101
+ '__float__': 1.0,
2102
+ '__bool__': True,
2103
+ '__index__': 1,
2104
+ '__aexit__': False,
2105
+ }
2106
+
2107
+
2108
+ def _get_eq(self):
2109
+ def __eq__(other):
2110
+ ret_val = self.__eq__._mock_return_value
2111
+ if ret_val is not DEFAULT:
2112
+ return ret_val
2113
+ if self is other:
2114
+ return True
2115
+ return NotImplemented
2116
+ return __eq__
2117
+
2118
+ def _get_ne(self):
2119
+ def __ne__(other):
2120
+ if self.__ne__._mock_return_value is not DEFAULT:
2121
+ return DEFAULT
2122
+ if self is other:
2123
+ return False
2124
+ return NotImplemented
2125
+ return __ne__
2126
+
2127
+ def _get_iter(self):
2128
+ def __iter__():
2129
+ ret_val = self.__iter__._mock_return_value
2130
+ if ret_val is DEFAULT:
2131
+ return iter([])
2132
+ # if ret_val was already an iterator, then calling iter on it should
2133
+ # return the iterator unchanged
2134
+ return iter(ret_val)
2135
+ return __iter__
2136
+
2137
+ def _get_async_iter(self):
2138
+ def __aiter__():
2139
+ ret_val = self.__aiter__._mock_return_value
2140
+ if ret_val is DEFAULT:
2141
+ return _AsyncIterator(iter([]))
2142
+ return _AsyncIterator(iter(ret_val))
2143
+ return __aiter__
2144
+
2145
+ _side_effect_methods = {
2146
+ '__eq__': _get_eq,
2147
+ '__ne__': _get_ne,
2148
+ '__iter__': _get_iter,
2149
+ '__aiter__': _get_async_iter
2150
+ }
2151
+
2152
+
2153
+
2154
+ def _set_return_value(mock, method, name):
2155
+ fixed = _return_values.get(name, DEFAULT)
2156
+ if fixed is not DEFAULT:
2157
+ method.return_value = fixed
2158
+ return
2159
+
2160
+ return_calculator = _calculate_return_value.get(name)
2161
+ if return_calculator is not None:
2162
+ return_value = return_calculator(mock)
2163
+ method.return_value = return_value
2164
+ return
2165
+
2166
+ side_effector = _side_effect_methods.get(name)
2167
+ if side_effector is not None:
2168
+ method.side_effect = side_effector(mock)
2169
+
2170
+
2171
+
2172
+ class MagicMixin(Base):
2173
+ def __init__(self, /, *args, **kw):
2174
+ self._mock_set_magics() # make magic work for kwargs in init
2175
+ _safe_super(MagicMixin, self).__init__(*args, **kw)
2176
+ self._mock_set_magics() # fix magic broken by upper level init
2177
+
2178
+
2179
+ def _mock_set_magics(self):
2180
+ orig_magics = _magics | _async_method_magics
2181
+ these_magics = orig_magics
2182
+
2183
+ if getattr(self, "_mock_methods", None) is not None:
2184
+ these_magics = orig_magics.intersection(self._mock_methods)
2185
+
2186
+ remove_magics = set()
2187
+ remove_magics = orig_magics - these_magics
2188
+
2189
+ for entry in remove_magics:
2190
+ if entry in type(self).__dict__:
2191
+ # remove unneeded magic methods
2192
+ delattr(self, entry)
2193
+
2194
+ # don't overwrite existing attributes if called a second time
2195
+ these_magics = these_magics - set(type(self).__dict__)
2196
+
2197
+ _type = type(self)
2198
+ for entry in these_magics:
2199
+ setattr(_type, entry, MagicProxy(entry, self))
2200
+
2201
+
2202
+
2203
+ class NonCallableMagicMock(MagicMixin, NonCallableMock):
2204
+ """A version of `MagicMock` that isn't callable."""
2205
+ def mock_add_spec(self, spec, spec_set=False):
2206
+ """Add a spec to a mock. `spec` can either be an object or a
2207
+ list of strings. Only attributes on the `spec` can be fetched as
2208
+ attributes from the mock.
2209
+
2210
+ If `spec_set` is True then only attributes on the spec can be set."""
2211
+ self._mock_add_spec(spec, spec_set)
2212
+ self._mock_set_magics()
2213
+
2214
+
2215
+ class AsyncMagicMixin(MagicMixin):
2216
+ pass
2217
+
2218
+
2219
+ class MagicMock(MagicMixin, Mock):
2220
+ """
2221
+ MagicMock is a subclass of Mock with default implementations
2222
+ of most of the magic methods. You can use MagicMock without having to
2223
+ configure the magic methods yourself.
2224
+
2225
+ If you use the `spec` or `spec_set` arguments then *only* magic
2226
+ methods that exist in the spec will be created.
2227
+
2228
+ Attributes and the return value of a `MagicMock` will also be `MagicMocks`.
2229
+ """
2230
+ def mock_add_spec(self, spec, spec_set=False):
2231
+ """Add a spec to a mock. `spec` can either be an object or a
2232
+ list of strings. Only attributes on the `spec` can be fetched as
2233
+ attributes from the mock.
2234
+
2235
+ If `spec_set` is True then only attributes on the spec can be set."""
2236
+ self._mock_add_spec(spec, spec_set)
2237
+ self._mock_set_magics()
2238
+
2239
+ def reset_mock(self, /, *args, return_value: bool = False, **kwargs):
2240
+ if (
2241
+ return_value
2242
+ and self._mock_name
2243
+ and _is_magic(self._mock_name)
2244
+ ):
2245
+ # Don't reset return values for magic methods,
2246
+ # otherwise `m.__str__` will start
2247
+ # to return `MagicMock` instances, instead of `str` instances.
2248
+ return_value = False
2249
+ super().reset_mock(*args, return_value=return_value, **kwargs)
2250
+
2251
+
2252
+ class MagicProxy(Base):
2253
+ def __init__(self, name, parent):
2254
+ self.name = name
2255
+ self.parent = parent
2256
+
2257
+ def create_mock(self):
2258
+ entry = self.name
2259
+ parent = self.parent
2260
+ m = parent._get_child_mock(name=entry, _new_name=entry,
2261
+ _new_parent=parent)
2262
+ setattr(parent, entry, m)
2263
+ _set_return_value(parent, m, entry)
2264
+ return m
2265
+
2266
+ def __get__(self, obj, _type=None):
2267
+ return self.create_mock()
2268
+
2269
+
2270
+ try:
2271
+ _CODE_SIG = inspect.signature(partial(CodeType.__init__, None))
2272
+ _CODE_ATTRS = dir(CodeType)
2273
+ except ValueError:
2274
+ _CODE_SIG = None
2275
+
2276
+
2277
+ class AsyncMockMixin(Base):
2278
+ await_count = _delegating_property('await_count')
2279
+ await_args = _delegating_property('await_args')
2280
+ await_args_list = _delegating_property('await_args_list')
2281
+
2282
+ def __init__(self, /, *args, **kwargs):
2283
+ super().__init__(*args, **kwargs)
2284
+ # iscoroutinefunction() checks _is_coroutine property to say if an
2285
+ # object is a coroutine. Without this check it looks to see if it is a
2286
+ # function/method, which in this case it is not (since it is an
2287
+ # AsyncMock).
2288
+ # It is set through __dict__ because when spec_set is True, this
2289
+ # attribute is likely undefined.
2290
+ self.__dict__['_is_coroutine'] = asyncio.coroutines._is_coroutine
2291
+ self.__dict__['_mock_await_count'] = 0
2292
+ self.__dict__['_mock_await_args'] = None
2293
+ self.__dict__['_mock_await_args_list'] = _CallList()
2294
+ if _CODE_SIG:
2295
+ code_mock = NonCallableMock(spec_set=_CODE_ATTRS)
2296
+ code_mock.__dict__["_spec_class"] = CodeType
2297
+ code_mock.__dict__["_spec_signature"] = _CODE_SIG
2298
+ else:
2299
+ code_mock = NonCallableMock(spec_set=CodeType)
2300
+ code_mock.co_flags = (
2301
+ inspect.CO_COROUTINE
2302
+ + inspect.CO_VARARGS
2303
+ + inspect.CO_VARKEYWORDS
2304
+ )
2305
+ code_mock.co_argcount = 0
2306
+ code_mock.co_varnames = ('args', 'kwargs')
2307
+ code_mock.co_posonlyargcount = 0
2308
+ code_mock.co_kwonlyargcount = 0
2309
+ self.__dict__['__code__'] = code_mock
2310
+ self.__dict__['__name__'] = 'AsyncMock'
2311
+ self.__dict__['__defaults__'] = tuple()
2312
+ self.__dict__['__kwdefaults__'] = {}
2313
+ self.__dict__['__annotations__'] = None
2314
+
2315
+ async def _execute_mock_call(self, /, *args, **kwargs):
2316
+ # This is nearly just like super(), except for special handling
2317
+ # of coroutines
2318
+
2319
+ _call = _Call((args, kwargs), two=True)
2320
+ self.await_count += 1
2321
+ self.await_args = _call
2322
+ self.await_args_list.append(_call)
2323
+
2324
+ effect = self.side_effect
2325
+ if effect is not None:
2326
+ if _is_exception(effect):
2327
+ raise effect
2328
+ elif not _callable(effect):
2329
+ try:
2330
+ result = next(effect)
2331
+ except StopIteration:
2332
+ # It is impossible to propagate a StopIteration
2333
+ # through coroutines because of PEP 479
2334
+ raise StopAsyncIteration
2335
+ if _is_exception(result):
2336
+ raise result
2337
+ elif iscoroutinefunction(effect):
2338
+ result = await effect(*args, **kwargs)
2339
+ else:
2340
+ result = effect(*args, **kwargs)
2341
+
2342
+ if result is not DEFAULT:
2343
+ return result
2344
+
2345
+ if self._mock_return_value is not DEFAULT:
2346
+ return self.return_value
2347
+
2348
+ if self._mock_wraps is not None:
2349
+ if iscoroutinefunction(self._mock_wraps):
2350
+ return await self._mock_wraps(*args, **kwargs)
2351
+ return self._mock_wraps(*args, **kwargs)
2352
+
2353
+ return self.return_value
2354
+
2355
+ def assert_awaited(self):
2356
+ """
2357
+ Assert that the mock was awaited at least once.
2358
+ """
2359
+ if self.await_count == 0:
2360
+ msg = f"Expected {self._mock_name or 'mock'} to have been awaited."
2361
+ raise AssertionError(msg)
2362
+
2363
+ def assert_awaited_once(self):
2364
+ """
2365
+ Assert that the mock was awaited exactly once.
2366
+ """
2367
+ if not self.await_count == 1:
2368
+ msg = (f"Expected {self._mock_name or 'mock'} to have been awaited once."
2369
+ f" Awaited {self.await_count} times.")
2370
+ raise AssertionError(msg)
2371
+
2372
+ def assert_awaited_with(self, /, *args, **kwargs):
2373
+ """
2374
+ Assert that the last await was with the specified arguments.
2375
+ """
2376
+ if self.await_args is None:
2377
+ expected = self._format_mock_call_signature(args, kwargs)
2378
+ raise AssertionError(f'Expected await: {expected}\nNot awaited')
2379
+
2380
+ def _error_message():
2381
+ msg = self._format_mock_failure_message(args, kwargs, action='await')
2382
+ return msg
2383
+
2384
+ expected = self._call_matcher(_Call((args, kwargs), two=True))
2385
+ actual = self._call_matcher(self.await_args)
2386
+ if actual != expected:
2387
+ cause = expected if isinstance(expected, Exception) else None
2388
+ raise AssertionError(_error_message()) from cause
2389
+
2390
+ def assert_awaited_once_with(self, /, *args, **kwargs):
2391
+ """
2392
+ Assert that the mock was awaited exactly once and with the specified
2393
+ arguments.
2394
+ """
2395
+ if not self.await_count == 1:
2396
+ msg = (f"Expected {self._mock_name or 'mock'} to have been awaited once."
2397
+ f" Awaited {self.await_count} times.")
2398
+ raise AssertionError(msg)
2399
+ return self.assert_awaited_with(*args, **kwargs)
2400
+
2401
+ def assert_any_await(self, /, *args, **kwargs):
2402
+ """
2403
+ Assert the mock has ever been awaited with the specified arguments.
2404
+ """
2405
+ expected = self._call_matcher(_Call((args, kwargs), two=True))
2406
+ cause = expected if isinstance(expected, Exception) else None
2407
+ actual = [self._call_matcher(c) for c in self.await_args_list]
2408
+ if cause or expected not in _AnyComparer(actual):
2409
+ expected_string = self._format_mock_call_signature(args, kwargs)
2410
+ raise AssertionError(
2411
+ '%s await not found' % expected_string
2412
+ ) from cause
2413
+
2414
+ def assert_has_awaits(self, calls, any_order=False):
2415
+ """
2416
+ Assert the mock has been awaited with the specified calls.
2417
+ The :attr:`await_args_list` list is checked for the awaits.
2418
+
2419
+ If `any_order` is False (the default) then the awaits must be
2420
+ sequential. There can be extra calls before or after the
2421
+ specified awaits.
2422
+
2423
+ If `any_order` is True then the awaits can be in any order, but
2424
+ they must all appear in :attr:`await_args_list`.
2425
+ """
2426
+ expected = [self._call_matcher(c) for c in calls]
2427
+ cause = next((e for e in expected if isinstance(e, Exception)), None)
2428
+ all_awaits = _CallList(self._call_matcher(c) for c in self.await_args_list)
2429
+ if not any_order:
2430
+ if expected not in all_awaits:
2431
+ if cause is None:
2432
+ problem = 'Awaits not found.'
2433
+ else:
2434
+ problem = ('Error processing expected awaits.\n'
2435
+ 'Errors: {}').format(
2436
+ [e if isinstance(e, Exception) else None
2437
+ for e in expected])
2438
+ raise AssertionError(
2439
+ f'{problem}\n'
2440
+ f'Expected: {_CallList(calls)}\n'
2441
+ f'Actual: {self.await_args_list}'
2442
+ ) from cause
2443
+ return
2444
+
2445
+ all_awaits = list(all_awaits)
2446
+
2447
+ not_found = []
2448
+ for kall in expected:
2449
+ try:
2450
+ all_awaits.remove(kall)
2451
+ except ValueError:
2452
+ not_found.append(kall)
2453
+ if not_found:
2454
+ raise AssertionError(
2455
+ '%r not all found in await list' % (tuple(not_found),)
2456
+ ) from cause
2457
+
2458
+ def assert_not_awaited(self):
2459
+ """
2460
+ Assert that the mock was never awaited.
2461
+ """
2462
+ if self.await_count != 0:
2463
+ msg = (f"Expected {self._mock_name or 'mock'} to not have been awaited."
2464
+ f" Awaited {self.await_count} times.")
2465
+ raise AssertionError(msg)
2466
+
2467
+ def reset_mock(self, /, *args, **kwargs):
2468
+ """
2469
+ See :func:`.Mock.reset_mock()`
2470
+ """
2471
+ super().reset_mock(*args, **kwargs)
2472
+ self.await_count = 0
2473
+ self.await_args = None
2474
+ self.await_args_list = _CallList()
2475
+
2476
+
2477
+ class AsyncMock(AsyncMockMixin, AsyncMagicMixin, Mock):
2478
+ """
2479
+ Enhance :class:`Mock` with features allowing to mock
2480
+ an async function.
2481
+
2482
+ The :class:`AsyncMock` object will behave so the object is
2483
+ recognized as an async function, and the result of a call is an awaitable:
2484
+
2485
+ >>> mock = AsyncMock()
2486
+ >>> iscoroutinefunction(mock)
2487
+ True
2488
+ >>> inspect.isawaitable(mock())
2489
+ True
2490
+
2491
+
2492
+ The result of ``mock()`` is an async function which will have the outcome
2493
+ of ``side_effect`` or ``return_value``:
2494
+
2495
+ - if ``side_effect`` is a function, the async function will return the
2496
+ result of that function,
2497
+ - if ``side_effect`` is an exception, the async function will raise the
2498
+ exception,
2499
+ - if ``side_effect`` is an iterable, the async function will return the
2500
+ next value of the iterable, however, if the sequence of result is
2501
+ exhausted, ``StopIteration`` is raised immediately,
2502
+ - if ``side_effect`` is not defined, the async function will return the
2503
+ value defined by ``return_value``, hence, by default, the async function
2504
+ returns a new :class:`AsyncMock` object.
2505
+
2506
+ If the outcome of ``side_effect`` or ``return_value`` is an async function,
2507
+ the mock async function obtained when the mock object is called will be this
2508
+ async function itself (and not an async function returning an async
2509
+ function).
2510
+
2511
+ The test author can also specify a wrapped object with ``wraps``. In this
2512
+ case, the :class:`Mock` object behavior is the same as with an
2513
+ :class:`.Mock` object: the wrapped object may have methods
2514
+ defined as async function functions.
2515
+
2516
+ Based on Martin Richard's asynctest project.
2517
+ """
2518
+
2519
+
2520
+ class _ANY(object):
2521
+ "A helper object that compares equal to everything."
2522
+
2523
+ def __eq__(self, other):
2524
+ return True
2525
+
2526
+ def __ne__(self, other):
2527
+ return False
2528
+
2529
+ def __repr__(self):
2530
+ return '<ANY>'
2531
+
2532
+ ANY = _ANY()
2533
+
2534
+
2535
+
2536
+ def _format_call_signature(name, args, kwargs):
2537
+ message = '%s(%%s)' % name
2538
+ formatted_args = ''
2539
+ args_string = ', '.join([repr(arg) for arg in args])
2540
+ kwargs_string = ', '.join([
2541
+ '%s=%r' % (key, value) for key, value in kwargs.items()
2542
+ ])
2543
+ if args_string:
2544
+ formatted_args = args_string
2545
+ if kwargs_string:
2546
+ if formatted_args:
2547
+ formatted_args += ', '
2548
+ formatted_args += kwargs_string
2549
+
2550
+ return message % formatted_args
2551
+
2552
+
2553
+
2554
+ class _Call(tuple):
2555
+ """
2556
+ A tuple for holding the results of a call to a mock, either in the form
2557
+ `(args, kwargs)` or `(name, args, kwargs)`.
2558
+
2559
+ If args or kwargs are empty then a call tuple will compare equal to
2560
+ a tuple without those values. This makes comparisons less verbose::
2561
+
2562
+ _Call(('name', (), {})) == ('name',)
2563
+ _Call(('name', (1,), {})) == ('name', (1,))
2564
+ _Call(((), {'a': 'b'})) == ({'a': 'b'},)
2565
+
2566
+ The `_Call` object provides a useful shortcut for comparing with call::
2567
+
2568
+ _Call(((1, 2), {'a': 3})) == call(1, 2, a=3)
2569
+ _Call(('foo', (1, 2), {'a': 3})) == call.foo(1, 2, a=3)
2570
+
2571
+ If the _Call has no name then it will match any name.
2572
+ """
2573
+ def __new__(cls, value=(), name='', parent=None, two=False,
2574
+ from_kall=True):
2575
+ args = ()
2576
+ kwargs = {}
2577
+ _len = len(value)
2578
+ if _len == 3:
2579
+ name, args, kwargs = value
2580
+ elif _len == 2:
2581
+ first, second = value
2582
+ if isinstance(first, str):
2583
+ name = first
2584
+ if isinstance(second, tuple):
2585
+ args = second
2586
+ else:
2587
+ kwargs = second
2588
+ else:
2589
+ args, kwargs = first, second
2590
+ elif _len == 1:
2591
+ value, = value
2592
+ if isinstance(value, str):
2593
+ name = value
2594
+ elif isinstance(value, tuple):
2595
+ args = value
2596
+ else:
2597
+ kwargs = value
2598
+
2599
+ if two:
2600
+ return tuple.__new__(cls, (args, kwargs))
2601
+
2602
+ return tuple.__new__(cls, (name, args, kwargs))
2603
+
2604
+
2605
+ def __init__(self, value=(), name=None, parent=None, two=False,
2606
+ from_kall=True):
2607
+ self._mock_name = name
2608
+ self._mock_parent = parent
2609
+ self._mock_from_kall = from_kall
2610
+
2611
+
2612
+ def __eq__(self, other):
2613
+ try:
2614
+ len_other = len(other)
2615
+ except TypeError:
2616
+ return NotImplemented
2617
+
2618
+ self_name = ''
2619
+ if len(self) == 2:
2620
+ self_args, self_kwargs = self
2621
+ else:
2622
+ self_name, self_args, self_kwargs = self
2623
+
2624
+ if (getattr(self, '_mock_parent', None) and getattr(other, '_mock_parent', None)
2625
+ and self._mock_parent != other._mock_parent):
2626
+ return False
2627
+
2628
+ other_name = ''
2629
+ if len_other == 0:
2630
+ other_args, other_kwargs = (), {}
2631
+ elif len_other == 3:
2632
+ other_name, other_args, other_kwargs = other
2633
+ elif len_other == 1:
2634
+ value, = other
2635
+ if isinstance(value, tuple):
2636
+ other_args = value
2637
+ other_kwargs = {}
2638
+ elif isinstance(value, str):
2639
+ other_name = value
2640
+ other_args, other_kwargs = (), {}
2641
+ else:
2642
+ other_args = ()
2643
+ other_kwargs = value
2644
+ elif len_other == 2:
2645
+ # could be (name, args) or (name, kwargs) or (args, kwargs)
2646
+ first, second = other
2647
+ if isinstance(first, str):
2648
+ other_name = first
2649
+ if isinstance(second, tuple):
2650
+ other_args, other_kwargs = second, {}
2651
+ else:
2652
+ other_args, other_kwargs = (), second
2653
+ else:
2654
+ other_args, other_kwargs = first, second
2655
+ else:
2656
+ return False
2657
+
2658
+ if self_name and other_name != self_name:
2659
+ return False
2660
+
2661
+ # this order is important for ANY to work!
2662
+ return (other_args, other_kwargs) == (self_args, self_kwargs)
2663
+
2664
+
2665
+ __ne__ = object.__ne__
2666
+
2667
+
2668
+ def __call__(self, /, *args, **kwargs):
2669
+ if self._mock_name is None:
2670
+ return _Call(('', args, kwargs), name='()')
2671
+
2672
+ name = self._mock_name + '()'
2673
+ return _Call((self._mock_name, args, kwargs), name=name, parent=self)
2674
+
2675
+
2676
+ def __getattr__(self, attr):
2677
+ if self._mock_name is None:
2678
+ return _Call(name=attr, from_kall=False)
2679
+ name = '%s.%s' % (self._mock_name, attr)
2680
+ return _Call(name=name, parent=self, from_kall=False)
2681
+
2682
+
2683
+ def __getattribute__(self, attr):
2684
+ if attr in tuple.__dict__:
2685
+ raise AttributeError
2686
+ return tuple.__getattribute__(self, attr)
2687
+
2688
+
2689
+ def _get_call_arguments(self):
2690
+ if len(self) == 2:
2691
+ args, kwargs = self
2692
+ else:
2693
+ name, args, kwargs = self
2694
+
2695
+ return args, kwargs
2696
+
2697
+ @property
2698
+ def args(self):
2699
+ return self._get_call_arguments()[0]
2700
+
2701
+ @property
2702
+ def kwargs(self):
2703
+ return self._get_call_arguments()[1]
2704
+
2705
+ def __repr__(self):
2706
+ if not self._mock_from_kall:
2707
+ name = self._mock_name or 'call'
2708
+ if name.startswith('()'):
2709
+ name = 'call%s' % name
2710
+ return name
2711
+
2712
+ if len(self) == 2:
2713
+ name = 'call'
2714
+ args, kwargs = self
2715
+ else:
2716
+ name, args, kwargs = self
2717
+ if not name:
2718
+ name = 'call'
2719
+ elif not name.startswith('()'):
2720
+ name = 'call.%s' % name
2721
+ else:
2722
+ name = 'call%s' % name
2723
+ return _format_call_signature(name, args, kwargs)
2724
+
2725
+
2726
+ def call_list(self):
2727
+ """For a call object that represents multiple calls, `call_list`
2728
+ returns a list of all the intermediate calls as well as the
2729
+ final call."""
2730
+ vals = []
2731
+ thing = self
2732
+ while thing is not None:
2733
+ if thing._mock_from_kall:
2734
+ vals.append(thing)
2735
+ thing = thing._mock_parent
2736
+ return _CallList(reversed(vals))
2737
+
2738
+
2739
+ call = _Call(from_kall=False)
2740
+
2741
+
2742
+ def create_autospec(spec, spec_set=False, instance=False, _parent=None,
2743
+ _name=None, *, unsafe=False, **kwargs):
2744
+ """Create a mock object using another object as a spec. Attributes on the
2745
+ mock will use the corresponding attribute on the `spec` object as their
2746
+ spec.
2747
+
2748
+ Functions or methods being mocked will have their arguments checked
2749
+ to check that they are called with the correct signature.
2750
+
2751
+ If `spec_set` is True then attempting to set attributes that don't exist
2752
+ on the spec object will raise an `AttributeError`.
2753
+
2754
+ If a class is used as a spec then the return value of the mock (the
2755
+ instance of the class) will have the same spec. You can use a class as the
2756
+ spec for an instance object by passing `instance=True`. The returned mock
2757
+ will only be callable if instances of the mock are callable.
2758
+
2759
+ `create_autospec` will raise a `RuntimeError` if passed some common
2760
+ misspellings of the arguments autospec and spec_set. Pass the argument
2761
+ `unsafe` with the value True to disable that check.
2762
+
2763
+ `create_autospec` also takes arbitrary keyword arguments that are passed to
2764
+ the constructor of the created mock."""
2765
+ if _is_list(spec):
2766
+ # can't pass a list instance to the mock constructor as it will be
2767
+ # interpreted as a list of strings
2768
+ spec = type(spec)
2769
+
2770
+ is_type = isinstance(spec, type)
2771
+ if _is_instance_mock(spec):
2772
+ raise InvalidSpecError(f'Cannot autospec a Mock object. '
2773
+ f'[object={spec!r}]')
2774
+ is_async_func = _is_async_func(spec)
2775
+ _kwargs = {'spec': spec}
2776
+ if spec_set:
2777
+ _kwargs = {'spec_set': spec}
2778
+ elif spec is None:
2779
+ # None we mock with a normal mock without a spec
2780
+ _kwargs = {}
2781
+ if _kwargs and instance:
2782
+ _kwargs['_spec_as_instance'] = True
2783
+ if not unsafe:
2784
+ _check_spec_arg_typos(kwargs)
2785
+
2786
+ _name = kwargs.pop('name', _name)
2787
+ _new_name = _name
2788
+ if _parent is None:
2789
+ # for a top level object no _new_name should be set
2790
+ _new_name = ''
2791
+
2792
+ _kwargs.update(kwargs)
2793
+
2794
+ Klass = MagicMock
2795
+ if inspect.isdatadescriptor(spec):
2796
+ # descriptors don't have a spec
2797
+ # because we don't know what type they return
2798
+ _kwargs = {}
2799
+ elif is_async_func:
2800
+ if instance:
2801
+ raise RuntimeError("Instance can not be True when create_autospec "
2802
+ "is mocking an async function")
2803
+ Klass = AsyncMock
2804
+ elif not _callable(spec):
2805
+ Klass = NonCallableMagicMock
2806
+ elif is_type and instance and not _instance_callable(spec):
2807
+ Klass = NonCallableMagicMock
2808
+
2809
+ mock = Klass(parent=_parent, _new_parent=_parent, _new_name=_new_name,
2810
+ name=_name, **_kwargs)
2811
+
2812
+ if isinstance(spec, FunctionTypes):
2813
+ # should only happen at the top level because we don't
2814
+ # recurse for functions
2815
+ if is_async_func:
2816
+ mock = _set_async_signature(mock, spec)
2817
+ else:
2818
+ mock = _set_signature(mock, spec)
2819
+ else:
2820
+ _check_signature(spec, mock, is_type, instance)
2821
+
2822
+ if _parent is not None and not instance:
2823
+ _parent._mock_children[_name] = mock
2824
+
2825
+ # Pop wraps from kwargs because it must not be passed to configure_mock.
2826
+ wrapped = kwargs.pop('wraps', None)
2827
+ if is_type and not instance and 'return_value' not in kwargs:
2828
+ mock.return_value = create_autospec(spec, spec_set, instance=True,
2829
+ _name='()', _parent=mock,
2830
+ wraps=wrapped)
2831
+
2832
+ for entry in dir(spec):
2833
+ if _is_magic(entry):
2834
+ # MagicMock already does the useful magic methods for us
2835
+ continue
2836
+
2837
+ # XXXX do we need a better way of getting attributes without
2838
+ # triggering code execution (?) Probably not - we need the actual
2839
+ # object to mock it so we would rather trigger a property than mock
2840
+ # the property descriptor. Likewise we want to mock out dynamically
2841
+ # provided attributes.
2842
+ # XXXX what about attributes that raise exceptions other than
2843
+ # AttributeError on being fetched?
2844
+ # we could be resilient against it, or catch and propagate the
2845
+ # exception when the attribute is fetched from the mock
2846
+ try:
2847
+ original = getattr(spec, entry)
2848
+ except AttributeError:
2849
+ continue
2850
+
2851
+ child_kwargs = {'spec': original}
2852
+ # Wrap child attributes also.
2853
+ if wrapped and hasattr(wrapped, entry):
2854
+ child_kwargs.update(wraps=original)
2855
+ if spec_set:
2856
+ child_kwargs = {'spec_set': original}
2857
+
2858
+ if not isinstance(original, FunctionTypes):
2859
+ new = _SpecState(original, spec_set, mock, entry, instance)
2860
+ mock._mock_children[entry] = new
2861
+ else:
2862
+ parent = mock
2863
+ if isinstance(spec, FunctionTypes):
2864
+ parent = mock.mock
2865
+
2866
+ skipfirst = _must_skip(spec, entry, is_type)
2867
+ child_kwargs['_eat_self'] = skipfirst
2868
+ if iscoroutinefunction(original):
2869
+ child_klass = AsyncMock
2870
+ else:
2871
+ child_klass = MagicMock
2872
+ new = child_klass(parent=parent, name=entry, _new_name=entry,
2873
+ _new_parent=parent, **child_kwargs)
2874
+ mock._mock_children[entry] = new
2875
+ new.return_value = child_klass()
2876
+ _check_signature(original, new, skipfirst=skipfirst)
2877
+
2878
+ # so functions created with _set_signature become instance attributes,
2879
+ # *plus* their underlying mock exists in _mock_children of the parent
2880
+ # mock. Adding to _mock_children may be unnecessary where we are also
2881
+ # setting as an instance attribute?
2882
+ if isinstance(new, FunctionTypes):
2883
+ setattr(mock, entry, new)
2884
+ # kwargs are passed with respect to the parent mock so, they are not used
2885
+ # for creating return_value of the parent mock. So, this condition
2886
+ # should be true only for the parent mock if kwargs are given.
2887
+ if _is_instance_mock(mock) and kwargs:
2888
+ mock.configure_mock(**kwargs)
2889
+
2890
+ return mock
2891
+
2892
+
2893
+ def _must_skip(spec, entry, is_type):
2894
+ """
2895
+ Return whether we should skip the first argument on spec's `entry`
2896
+ attribute.
2897
+ """
2898
+ if not isinstance(spec, type):
2899
+ if entry in getattr(spec, '__dict__', {}):
2900
+ # instance attribute - shouldn't skip
2901
+ return False
2902
+ spec = spec.__class__
2903
+
2904
+ for klass in spec.__mro__:
2905
+ result = klass.__dict__.get(entry, DEFAULT)
2906
+ if result is DEFAULT:
2907
+ continue
2908
+ if isinstance(result, (staticmethod, classmethod)):
2909
+ return False
2910
+ elif isinstance(result, FunctionTypes):
2911
+ # Normal method => skip if looked up on type
2912
+ # (if looked up on instance, self is already skipped)
2913
+ return is_type
2914
+ else:
2915
+ return False
2916
+
2917
+ # function is a dynamically provided attribute
2918
+ return is_type
2919
+
2920
+
2921
+ class _SpecState(object):
2922
+
2923
+ def __init__(self, spec, spec_set=False, parent=None,
2924
+ name=None, ids=None, instance=False):
2925
+ self.spec = spec
2926
+ self.ids = ids
2927
+ self.spec_set = spec_set
2928
+ self.parent = parent
2929
+ self.instance = instance
2930
+ self.name = name
2931
+
2932
+
2933
+ FunctionTypes = (
2934
+ # python function
2935
+ type(create_autospec),
2936
+ # instance method
2937
+ type(ANY.__eq__),
2938
+ )
2939
+
2940
+
2941
+ file_spec = None
2942
+ open_spec = None
2943
+
2944
+
2945
+ def _to_stream(read_data):
2946
+ if isinstance(read_data, bytes):
2947
+ return io.BytesIO(read_data)
2948
+ else:
2949
+ return io.StringIO(read_data)
2950
+
2951
+
2952
+ def mock_open(mock=None, read_data=''):
2953
+ """
2954
+ A helper function to create a mock to replace the use of `open`. It works
2955
+ for `open` called directly or used as a context manager.
2956
+
2957
+ The `mock` argument is the mock object to configure. If `None` (the
2958
+ default) then a `MagicMock` will be created for you, with the API limited
2959
+ to methods or attributes available on standard file handles.
2960
+
2961
+ `read_data` is a string for the `read`, `readline` and `readlines` of the
2962
+ file handle to return. This is an empty string by default.
2963
+ """
2964
+ _read_data = _to_stream(read_data)
2965
+ _state = [_read_data, None]
2966
+
2967
+ def _readlines_side_effect(*args, **kwargs):
2968
+ if handle.readlines.return_value is not None:
2969
+ return handle.readlines.return_value
2970
+ return _state[0].readlines(*args, **kwargs)
2971
+
2972
+ def _read_side_effect(*args, **kwargs):
2973
+ if handle.read.return_value is not None:
2974
+ return handle.read.return_value
2975
+ return _state[0].read(*args, **kwargs)
2976
+
2977
+ def _readline_side_effect(*args, **kwargs):
2978
+ yield from _iter_side_effect()
2979
+ while True:
2980
+ yield _state[0].readline(*args, **kwargs)
2981
+
2982
+ def _iter_side_effect():
2983
+ if handle.readline.return_value is not None:
2984
+ while True:
2985
+ yield handle.readline.return_value
2986
+ for line in _state[0]:
2987
+ yield line
2988
+
2989
+ def _next_side_effect():
2990
+ if handle.readline.return_value is not None:
2991
+ return handle.readline.return_value
2992
+ return next(_state[0])
2993
+
2994
+ def _exit_side_effect(*args):
2995
+ handle.close()
2996
+
2997
+ global file_spec
2998
+ if file_spec is None:
2999
+ import _io
3000
+ file_spec = list(set(dir(_io.TextIOWrapper)).union(set(dir(_io.BytesIO))))
3001
+
3002
+ global open_spec
3003
+ if open_spec is None:
3004
+ import _io
3005
+ open_spec = list(set(dir(_io.open)))
3006
+ if mock is None:
3007
+ mock = MagicMock(name='open', spec=open_spec)
3008
+
3009
+ handle = MagicMock(spec=file_spec)
3010
+ handle.__enter__.return_value = handle
3011
+
3012
+ handle.write.return_value = None
3013
+ handle.read.return_value = None
3014
+ handle.readline.return_value = None
3015
+ handle.readlines.return_value = None
3016
+
3017
+ handle.read.side_effect = _read_side_effect
3018
+ _state[1] = _readline_side_effect()
3019
+ handle.readline.side_effect = _state[1]
3020
+ handle.readlines.side_effect = _readlines_side_effect
3021
+ handle.__iter__.side_effect = _iter_side_effect
3022
+ handle.__next__.side_effect = _next_side_effect
3023
+ handle.__exit__.side_effect = _exit_side_effect
3024
+
3025
+ def reset_data(*args, **kwargs):
3026
+ _state[0] = _to_stream(read_data)
3027
+ if handle.readline.side_effect == _state[1]:
3028
+ # Only reset the side effect if the user hasn't overridden it.
3029
+ _state[1] = _readline_side_effect()
3030
+ handle.readline.side_effect = _state[1]
3031
+ return DEFAULT
3032
+
3033
+ mock.side_effect = reset_data
3034
+ mock.return_value = handle
3035
+ return mock
3036
+
3037
+
3038
+ class PropertyMock(Mock):
3039
+ """
3040
+ A mock intended to be used as a property, or other descriptor, on a class.
3041
+ `PropertyMock` provides `__get__` and `__set__` methods so you can specify
3042
+ a return value when it is fetched.
3043
+
3044
+ Fetching a `PropertyMock` instance from an object calls the mock, with
3045
+ no args. Setting it calls the mock with the value being set.
3046
+ """
3047
+ def _get_child_mock(self, /, **kwargs):
3048
+ return MagicMock(**kwargs)
3049
+
3050
+ def __get__(self, obj, obj_type=None):
3051
+ return self()
3052
+ def __set__(self, obj, val):
3053
+ self(val)
3054
+
3055
+
3056
+ _timeout_unset = sentinel.TIMEOUT_UNSET
3057
+
3058
+ class ThreadingMixin(Base):
3059
+
3060
+ DEFAULT_TIMEOUT = None
3061
+
3062
+ def _get_child_mock(self, /, **kw):
3063
+ if isinstance(kw.get("parent"), ThreadingMixin):
3064
+ kw["timeout"] = kw["parent"]._mock_wait_timeout
3065
+ elif isinstance(kw.get("_new_parent"), ThreadingMixin):
3066
+ kw["timeout"] = kw["_new_parent"]._mock_wait_timeout
3067
+ return super()._get_child_mock(**kw)
3068
+
3069
+ def __init__(self, *args, timeout=_timeout_unset, **kwargs):
3070
+ super().__init__(*args, **kwargs)
3071
+ if timeout is _timeout_unset:
3072
+ timeout = self.DEFAULT_TIMEOUT
3073
+ self.__dict__["_mock_event"] = threading.Event() # Event for any call
3074
+ self.__dict__["_mock_calls_events"] = [] # Events for each of the calls
3075
+ self.__dict__["_mock_calls_events_lock"] = threading.Lock()
3076
+ self.__dict__["_mock_wait_timeout"] = timeout
3077
+
3078
+ def reset_mock(self, /, *args, **kwargs):
3079
+ """
3080
+ See :func:`.Mock.reset_mock()`
3081
+ """
3082
+ super().reset_mock(*args, **kwargs)
3083
+ self.__dict__["_mock_event"] = threading.Event()
3084
+ self.__dict__["_mock_calls_events"] = []
3085
+
3086
+ def __get_event(self, expected_args, expected_kwargs):
3087
+ with self._mock_calls_events_lock:
3088
+ for args, kwargs, event in self._mock_calls_events:
3089
+ if (args, kwargs) == (expected_args, expected_kwargs):
3090
+ return event
3091
+ new_event = threading.Event()
3092
+ self._mock_calls_events.append((expected_args, expected_kwargs, new_event))
3093
+ return new_event
3094
+
3095
+ def _mock_call(self, *args, **kwargs):
3096
+ ret_value = super()._mock_call(*args, **kwargs)
3097
+
3098
+ call_event = self.__get_event(args, kwargs)
3099
+ call_event.set()
3100
+
3101
+ self._mock_event.set()
3102
+
3103
+ return ret_value
3104
+
3105
+ def _increment_mock_call(self, /, *args, **kwargs):
3106
+ with self._mock_calls_events_lock:
3107
+ super()._increment_mock_call(*args, **kwargs)
3108
+
3109
+ def wait_until_called(self, *, timeout=_timeout_unset):
3110
+ """Wait until the mock object is called.
3111
+
3112
+ `timeout` - time to wait for in seconds, waits forever otherwise.
3113
+ Defaults to the constructor provided timeout.
3114
+ Use None to block undefinetively.
3115
+ """
3116
+ if timeout is _timeout_unset:
3117
+ timeout = self._mock_wait_timeout
3118
+ if not self._mock_event.wait(timeout=timeout):
3119
+ msg = (f"{self._mock_name or 'mock'} was not called before"
3120
+ f" timeout({timeout}).")
3121
+ raise AssertionError(msg)
3122
+
3123
+ def wait_until_any_call_with(self, *args, **kwargs):
3124
+ """Wait until the mock object is called with given args.
3125
+
3126
+ Waits for the timeout in seconds provided in the constructor.
3127
+ """
3128
+ event = self.__get_event(args, kwargs)
3129
+ if not event.wait(timeout=self._mock_wait_timeout):
3130
+ expected_string = self._format_mock_call_signature(args, kwargs)
3131
+ raise AssertionError(f'{expected_string} call not found')
3132
+
3133
+
3134
+ class ThreadingMock(ThreadingMixin, MagicMixin, Mock):
3135
+ """
3136
+ A mock that can be used to wait until on calls happening
3137
+ in a different thread.
3138
+
3139
+ The constructor can take a `timeout` argument which
3140
+ controls the timeout in seconds for all `wait` calls of the mock.
3141
+
3142
+ You can change the default timeout of all instances via the
3143
+ `ThreadingMock.DEFAULT_TIMEOUT` attribute.
3144
+
3145
+ If no timeout is set, it will block undefinetively.
3146
+ """
3147
+ pass
3148
+
3149
+
3150
+ def seal(mock):
3151
+ """Disable the automatic generation of child mocks.
3152
+
3153
+ Given an input Mock, seals it to ensure no further mocks will be generated
3154
+ when accessing an attribute that was not already defined.
3155
+
3156
+ The operation recursively seals the mock passed in, meaning that
3157
+ the mock itself, any mocks generated by accessing one of its attributes,
3158
+ and all assigned mocks without a name or spec will be sealed.
3159
+ """
3160
+ mock._mock_sealed = True
3161
+ for attr in dir(mock):
3162
+ try:
3163
+ m = getattr(mock, attr)
3164
+ except AttributeError:
3165
+ continue
3166
+ if not isinstance(m, NonCallableMock):
3167
+ continue
3168
+ if isinstance(m._mock_children.get(attr), _SpecState):
3169
+ continue
3170
+ if m._mock_new_parent is mock:
3171
+ seal(m)
3172
+
3173
+
3174
+ class _AsyncIterator:
3175
+ """
3176
+ Wraps an iterator in an asynchronous iterator.
3177
+ """
3178
+ def __init__(self, iterator):
3179
+ self.iterator = iterator
3180
+ code_mock = NonCallableMock(spec_set=CodeType)
3181
+ code_mock.co_flags = inspect.CO_ITERABLE_COROUTINE
3182
+ self.__dict__['__code__'] = code_mock
3183
+
3184
+ async def __anext__(self):
3185
+ try:
3186
+ return next(self.iterator)
3187
+ except StopIteration:
3188
+ pass
3189
+ raise StopAsyncIteration