MapProxy 2.1.0__py3-none-any.whl

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 (459) hide show
  1. MapProxy-2.1.0.dist-info/AUTHORS.txt +33 -0
  2. MapProxy-2.1.0.dist-info/COPYING.txt +60 -0
  3. MapProxy-2.1.0.dist-info/LICENSE.txt +202 -0
  4. MapProxy-2.1.0.dist-info/METADATA +165 -0
  5. MapProxy-2.1.0.dist-info/RECORD +459 -0
  6. MapProxy-2.1.0.dist-info/WHEEL +5 -0
  7. MapProxy-2.1.0.dist-info/entry_points.txt +4 -0
  8. MapProxy-2.1.0.dist-info/top_level.txt +1 -0
  9. mapproxy/__init__.py +0 -0
  10. mapproxy/cache/__init__.py +36 -0
  11. mapproxy/cache/azureblob.py +145 -0
  12. mapproxy/cache/base.py +120 -0
  13. mapproxy/cache/compact.py +665 -0
  14. mapproxy/cache/couchdb.py +301 -0
  15. mapproxy/cache/dummy.py +36 -0
  16. mapproxy/cache/file.py +200 -0
  17. mapproxy/cache/geopackage.py +647 -0
  18. mapproxy/cache/legend.py +87 -0
  19. mapproxy/cache/mbtiles.py +411 -0
  20. mapproxy/cache/meta.py +80 -0
  21. mapproxy/cache/path.py +261 -0
  22. mapproxy/cache/redis.py +152 -0
  23. mapproxy/cache/renderd.py +100 -0
  24. mapproxy/cache/riak.py +206 -0
  25. mapproxy/cache/s3.py +209 -0
  26. mapproxy/cache/tile.py +736 -0
  27. mapproxy/client/__init__.py +0 -0
  28. mapproxy/client/arcgis.py +82 -0
  29. mapproxy/client/cgi.py +141 -0
  30. mapproxy/client/http.py +295 -0
  31. mapproxy/client/log.py +33 -0
  32. mapproxy/client/tile.py +158 -0
  33. mapproxy/client/wms.py +255 -0
  34. mapproxy/compat/__init__.py +0 -0
  35. mapproxy/compat/image.py +86 -0
  36. mapproxy/config/__init__.py +22 -0
  37. mapproxy/config/config-schema.json +813 -0
  38. mapproxy/config/config.py +213 -0
  39. mapproxy/config/coverage.py +108 -0
  40. mapproxy/config/defaults.py +102 -0
  41. mapproxy/config/loader.py +2399 -0
  42. mapproxy/config/spec.py +657 -0
  43. mapproxy/config/validator.py +242 -0
  44. mapproxy/config_template/__init__.py +0 -0
  45. mapproxy/config_template/base_config/config.wsgi +10 -0
  46. mapproxy/config_template/base_config/full_example.yaml +598 -0
  47. mapproxy/config_template/base_config/full_seed_example.yaml +79 -0
  48. mapproxy/config_template/base_config/log.ini +35 -0
  49. mapproxy/config_template/base_config/mapproxy.yaml +60 -0
  50. mapproxy/config_template/base_config/seed.yaml +27 -0
  51. mapproxy/exception.py +149 -0
  52. mapproxy/featureinfo.py +251 -0
  53. mapproxy/grid.py +1199 -0
  54. mapproxy/image/__init__.py +549 -0
  55. mapproxy/image/fonts/DejaVuSans.ttf +0 -0
  56. mapproxy/image/fonts/DejaVuSansMono.ttf +0 -0
  57. mapproxy/image/fonts/LICENSE +99 -0
  58. mapproxy/image/fonts/__init__.py +0 -0
  59. mapproxy/image/mask.py +79 -0
  60. mapproxy/image/merge.py +323 -0
  61. mapproxy/image/message.py +357 -0
  62. mapproxy/image/opts.py +185 -0
  63. mapproxy/image/tile.py +171 -0
  64. mapproxy/image/transform.py +350 -0
  65. mapproxy/layer.py +489 -0
  66. mapproxy/multiapp.py +230 -0
  67. mapproxy/proj.py +309 -0
  68. mapproxy/request/__init__.py +18 -0
  69. mapproxy/request/arcgis.py +268 -0
  70. mapproxy/request/base.py +466 -0
  71. mapproxy/request/tile.py +131 -0
  72. mapproxy/request/wms/__init__.py +829 -0
  73. mapproxy/request/wms/exception.py +107 -0
  74. mapproxy/request/wmts.py +442 -0
  75. mapproxy/response.py +237 -0
  76. mapproxy/script/__init__.py +0 -0
  77. mapproxy/script/conf/__init__.py +0 -0
  78. mapproxy/script/conf/app.py +222 -0
  79. mapproxy/script/conf/caches.py +44 -0
  80. mapproxy/script/conf/geopackage.py +136 -0
  81. mapproxy/script/conf/layers.py +54 -0
  82. mapproxy/script/conf/seeds.py +36 -0
  83. mapproxy/script/conf/sources.py +88 -0
  84. mapproxy/script/conf/utils.py +148 -0
  85. mapproxy/script/defrag.py +187 -0
  86. mapproxy/script/export.py +337 -0
  87. mapproxy/script/grids.py +198 -0
  88. mapproxy/script/scales.py +134 -0
  89. mapproxy/script/util.py +410 -0
  90. mapproxy/script/wms_capabilities.py +160 -0
  91. mapproxy/seed/__init__.py +0 -0
  92. mapproxy/seed/cachelock.py +127 -0
  93. mapproxy/seed/cleanup.py +191 -0
  94. mapproxy/seed/config.py +481 -0
  95. mapproxy/seed/script.py +391 -0
  96. mapproxy/seed/seeder.py +551 -0
  97. mapproxy/seed/spec.py +66 -0
  98. mapproxy/seed/util.py +266 -0
  99. mapproxy/service/__init__.py +14 -0
  100. mapproxy/service/base.py +45 -0
  101. mapproxy/service/demo.py +364 -0
  102. mapproxy/service/kml.py +333 -0
  103. mapproxy/service/ows.py +39 -0
  104. mapproxy/service/template_helper.py +55 -0
  105. mapproxy/service/templates/demo/capabilities_demo.html +18 -0
  106. mapproxy/service/templates/demo/demo.html +181 -0
  107. mapproxy/service/templates/demo/openlayers-demo.cfg +16 -0
  108. mapproxy/service/templates/demo/static/img/blank.gif +0 -0
  109. mapproxy/service/templates/demo/static/img/east-mini.png +0 -0
  110. mapproxy/service/templates/demo/static/img/north-mini.png +0 -0
  111. mapproxy/service/templates/demo/static/img/south-mini.png +0 -0
  112. mapproxy/service/templates/demo/static/img/west-mini.png +0 -0
  113. mapproxy/service/templates/demo/static/img/zoom-minus-mini.png +0 -0
  114. mapproxy/service/templates/demo/static/img/zoom-plus-mini.png +0 -0
  115. mapproxy/service/templates/demo/static/img/zoom-world-mini.png +0 -0
  116. mapproxy/service/templates/demo/static/logo.png +0 -0
  117. mapproxy/service/templates/demo/static/ol.css +345 -0
  118. mapproxy/service/templates/demo/static/ol.js +4 -0
  119. mapproxy/service/templates/demo/static/proj4.min.js +1 -0
  120. mapproxy/service/templates/demo/static/proj4defs.js +1 -0
  121. mapproxy/service/templates/demo/static/site.css +137 -0
  122. mapproxy/service/templates/demo/static/theme/default/framedCloud.css +0 -0
  123. mapproxy/service/templates/demo/static/theme/default/google.css +17 -0
  124. mapproxy/service/templates/demo/static/theme/default/ie6-style.css +10 -0
  125. mapproxy/service/templates/demo/static/theme/default/style.css +482 -0
  126. mapproxy/service/templates/demo/static.html +34 -0
  127. mapproxy/service/templates/demo/tms_demo.html +117 -0
  128. mapproxy/service/templates/demo/wms_demo.html +144 -0
  129. mapproxy/service/templates/demo/wmts_demo.html +118 -0
  130. mapproxy/service/templates/tms_capabilities.xml +13 -0
  131. mapproxy/service/templates/tms_exception.xml +4 -0
  132. mapproxy/service/templates/tms_root_resource.xml +7 -0
  133. mapproxy/service/templates/tms_tilemap_capabilities.xml +14 -0
  134. mapproxy/service/templates/wms100capabilities.xml +112 -0
  135. mapproxy/service/templates/wms100exception.xml +4 -0
  136. mapproxy/service/templates/wms110capabilities.xml +152 -0
  137. mapproxy/service/templates/wms110exception.xml +5 -0
  138. mapproxy/service/templates/wms111capabilities.xml +183 -0
  139. mapproxy/service/templates/wms111exception.xml +5 -0
  140. mapproxy/service/templates/wms130capabilities.xml +326 -0
  141. mapproxy/service/templates/wms130exception.xml +8 -0
  142. mapproxy/service/templates/wmts100capabilities.xml +155 -0
  143. mapproxy/service/templates/wmts100exception.xml +9 -0
  144. mapproxy/service/tile.py +540 -0
  145. mapproxy/service/wms.py +868 -0
  146. mapproxy/service/wmts.py +387 -0
  147. mapproxy/source/__init__.py +83 -0
  148. mapproxy/source/arcgis.py +39 -0
  149. mapproxy/source/error.py +40 -0
  150. mapproxy/source/mapnik.py +262 -0
  151. mapproxy/source/tile.py +97 -0
  152. mapproxy/source/wms.py +273 -0
  153. mapproxy/srs.py +734 -0
  154. mapproxy/template.py +54 -0
  155. mapproxy/test/__init__.py +0 -0
  156. mapproxy/test/conftest.py +8 -0
  157. mapproxy/test/helper.py +255 -0
  158. mapproxy/test/http.py +511 -0
  159. mapproxy/test/image.py +219 -0
  160. mapproxy/test/mocker.py +2291 -0
  161. mapproxy/test/schemas/inspire/common/1.0/common.xsd +1461 -0
  162. mapproxy/test/schemas/inspire/common/1.0/enums/enum_bul.xsd +108 -0
  163. mapproxy/test/schemas/inspire/common/1.0/enums/enum_cze.xsd +108 -0
  164. mapproxy/test/schemas/inspire/common/1.0/enums/enum_dan.xsd +108 -0
  165. mapproxy/test/schemas/inspire/common/1.0/enums/enum_dut.xsd +108 -0
  166. mapproxy/test/schemas/inspire/common/1.0/enums/enum_eng.xsd +155 -0
  167. mapproxy/test/schemas/inspire/common/1.0/enums/enum_est.xsd +108 -0
  168. mapproxy/test/schemas/inspire/common/1.0/enums/enum_fin.xsd +108 -0
  169. mapproxy/test/schemas/inspire/common/1.0/enums/enum_fre.xsd +108 -0
  170. mapproxy/test/schemas/inspire/common/1.0/enums/enum_ger.xsd +108 -0
  171. mapproxy/test/schemas/inspire/common/1.0/enums/enum_gle.xsd +109 -0
  172. mapproxy/test/schemas/inspire/common/1.0/enums/enum_gre.xsd +108 -0
  173. mapproxy/test/schemas/inspire/common/1.0/enums/enum_hun.xsd +108 -0
  174. mapproxy/test/schemas/inspire/common/1.0/enums/enum_ita.xsd +108 -0
  175. mapproxy/test/schemas/inspire/common/1.0/enums/enum_lav.xsd +108 -0
  176. mapproxy/test/schemas/inspire/common/1.0/enums/enum_lit.xsd +108 -0
  177. mapproxy/test/schemas/inspire/common/1.0/enums/enum_mlt.xsd +108 -0
  178. mapproxy/test/schemas/inspire/common/1.0/enums/enum_pol.xsd +108 -0
  179. mapproxy/test/schemas/inspire/common/1.0/enums/enum_por.xsd +108 -0
  180. mapproxy/test/schemas/inspire/common/1.0/enums/enum_rum.xsd +108 -0
  181. mapproxy/test/schemas/inspire/common/1.0/enums/enum_slo.xsd +108 -0
  182. mapproxy/test/schemas/inspire/common/1.0/enums/enum_slv.xsd +108 -0
  183. mapproxy/test/schemas/inspire/common/1.0/enums/enum_spa.xsd +108 -0
  184. mapproxy/test/schemas/inspire/common/1.0/enums/enum_swe.xsd +108 -0
  185. mapproxy/test/schemas/inspire/common/1.0/network.xsd +521 -0
  186. mapproxy/test/schemas/inspire/inspire_vs/1.0/inspire_vs.xsd +19 -0
  187. mapproxy/test/schemas/kml/2.2.0/ReadMe.txt +14 -0
  188. mapproxy/test/schemas/kml/2.2.0/atom-author-link.xsd +66 -0
  189. mapproxy/test/schemas/kml/2.2.0/ogckml22.xsd +1646 -0
  190. mapproxy/test/schemas/kml/2.2.0/xAL.xsd +1680 -0
  191. mapproxy/test/schemas/ows/1.1.0/ReadMe.txt +87 -0
  192. mapproxy/test/schemas/ows/1.1.0/ows19115subset.xsd +235 -0
  193. mapproxy/test/schemas/ows/1.1.0/owsAll.xsd +23 -0
  194. mapproxy/test/schemas/ows/1.1.0/owsCommon.xsd +157 -0
  195. mapproxy/test/schemas/ows/1.1.0/owsContents.xsd +86 -0
  196. mapproxy/test/schemas/ows/1.1.0/owsDataIdentification.xsd +127 -0
  197. mapproxy/test/schemas/ows/1.1.0/owsDomainType.xsd +279 -0
  198. mapproxy/test/schemas/ows/1.1.0/owsExceptionReport.xsd +76 -0
  199. mapproxy/test/schemas/ows/1.1.0/owsGetCapabilities.xsd +112 -0
  200. mapproxy/test/schemas/ows/1.1.0/owsGetResourceByID.xsd +51 -0
  201. mapproxy/test/schemas/ows/1.1.0/owsInputOutputData.xsd +59 -0
  202. mapproxy/test/schemas/ows/1.1.0/owsManifest.xsd +125 -0
  203. mapproxy/test/schemas/ows/1.1.0/owsOperationsMetadata.xsd +140 -0
  204. mapproxy/test/schemas/ows/1.1.0/owsServiceIdentification.xsd +60 -0
  205. mapproxy/test/schemas/ows/1.1.0/owsServiceProvider.xsd +47 -0
  206. mapproxy/test/schemas/sld/1.1.0/sld_capabilities.xsd +27 -0
  207. mapproxy/test/schemas/wms/1.0.0/capabilities_1_0_0.dtd +353 -0
  208. mapproxy/test/schemas/wms/1.0.0/capabilities_1_0_0.xml +188 -0
  209. mapproxy/test/schemas/wms/1.0.7/capabilities_1_0_7.dtd +524 -0
  210. mapproxy/test/schemas/wms/1.0.7/capabilities_1_0_7.xml +260 -0
  211. mapproxy/test/schemas/wms/1.1.0/capabilities_1_1_0.dtd +273 -0
  212. mapproxy/test/schemas/wms/1.1.0/capabilities_1_1_0.xml +303 -0
  213. mapproxy/test/schemas/wms/1.1.0/exception_1_1_0.dtd +6 -0
  214. mapproxy/test/schemas/wms/1.1.0/exception_1_1_0.xml +33 -0
  215. mapproxy/test/schemas/wms/1.1.1/OGC-exception.xsd +68 -0
  216. mapproxy/test/schemas/wms/1.1.1/WMS_DescribeLayerResponse.dtd +22 -0
  217. mapproxy/test/schemas/wms/1.1.1/WMS_MS_Capabilities.dtd +274 -0
  218. mapproxy/test/schemas/wms/1.1.1/WMS_exception_1_1_1.dtd +5 -0
  219. mapproxy/test/schemas/wms/1.1.1/capabilities_1_1_1.dtd +276 -0
  220. mapproxy/test/schemas/wms/1.1.1/capabilities_1_1_1.xml +303 -0
  221. mapproxy/test/schemas/wms/1.1.1/exception_1_1_1.dtd +6 -0
  222. mapproxy/test/schemas/wms/1.1.1/exception_1_1_1.xml +33 -0
  223. mapproxy/test/schemas/wms/1.3.0/ReadMe.txt +8 -0
  224. mapproxy/test/schemas/wms/1.3.0/capabilities_1_3_0.xml +277 -0
  225. mapproxy/test/schemas/wms/1.3.0/capabilities_1_3_0.xsd +611 -0
  226. mapproxy/test/schemas/wms/1.3.0/exceptions_1_3_0.xml +34 -0
  227. mapproxy/test/schemas/wms/1.3.0/exceptions_1_3_0.xsd +28 -0
  228. mapproxy/test/schemas/wmsc/1.1.1/OGC-exception.xsd +68 -0
  229. mapproxy/test/schemas/wmsc/1.1.1/WMS_DescribeLayerResponse.dtd +22 -0
  230. mapproxy/test/schemas/wmsc/1.1.1/WMS_MS_Capabilities.dtd +283 -0
  231. mapproxy/test/schemas/wmsc/1.1.1/WMS_exception_1_1_1.dtd +5 -0
  232. mapproxy/test/schemas/wmsc/1.1.1/capabilities_1_1_1.dtd +276 -0
  233. mapproxy/test/schemas/wmsc/1.1.1/capabilities_1_1_1.xml +303 -0
  234. mapproxy/test/schemas/wmsc/1.1.1/exception_1_1_1.dtd +6 -0
  235. mapproxy/test/schemas/wmsc/1.1.1/exception_1_1_1.xml +33 -0
  236. mapproxy/test/schemas/wmts/1.0/ReadMe.txt +32 -0
  237. mapproxy/test/schemas/wmts/1.0/wmts.xsd +28 -0
  238. mapproxy/test/schemas/wmts/1.0/wmtsAbstract.wsdl +151 -0
  239. mapproxy/test/schemas/wmts/1.0/wmtsGetCapabilities_request.xsd +38 -0
  240. mapproxy/test/schemas/wmts/1.0/wmtsGetCapabilities_response.xsd +564 -0
  241. mapproxy/test/schemas/wmts/1.0/wmtsGetFeatureInfo_request.xsd +57 -0
  242. mapproxy/test/schemas/wmts/1.0/wmtsGetFeatureInfo_response.xsd +72 -0
  243. mapproxy/test/schemas/wmts/1.0/wmtsGetTile_request.xsd +91 -0
  244. mapproxy/test/schemas/wmts/1.0/wmtsKVP.xsd +76 -0
  245. mapproxy/test/schemas/wmts/1.0/wmtsPayload_response.xsd +70 -0
  246. mapproxy/test/schemas/xlink/1.0.0/ReadMe.txt +6 -0
  247. mapproxy/test/schemas/xlink/1.0.0/xlinks.xsd +122 -0
  248. mapproxy/test/schemas/xml.xsd +287 -0
  249. mapproxy/test/system/__init__.py +98 -0
  250. mapproxy/test/system/fixture/arcgis.yaml +57 -0
  251. mapproxy/test/system/fixture/auth.yaml +70 -0
  252. mapproxy/test/system/fixture/cache.mbtiles +0 -0
  253. mapproxy/test/system/fixture/cache_azureblob.yaml +59 -0
  254. mapproxy/test/system/fixture/cache_band_merge.yaml +73 -0
  255. mapproxy/test/system/fixture/cache_bulk_meta_tiles.yaml +24 -0
  256. mapproxy/test/system/fixture/cache_coverage.yaml +84 -0
  257. mapproxy/test/system/fixture/cache_data/dop_cache_EPSG3857/00/000/000/000/000/000/000.png +0 -0
  258. mapproxy/test/system/fixture/cache_data/wms_cache_EPSG900913/01/000/000/000/000/000/001.jpeg +0 -0
  259. mapproxy/test/system/fixture/cache_data/wms_cache_transparent_EPSG900913/01/000/000/000/000/000/001.png +0 -0
  260. mapproxy/test/system/fixture/cache_geopackage.yaml +56 -0
  261. mapproxy/test/system/fixture/cache_grid_names.yaml +50 -0
  262. mapproxy/test/system/fixture/cache_mbtiles.yaml +28 -0
  263. mapproxy/test/system/fixture/cache_s3.yaml +58 -0
  264. mapproxy/test/system/fixture/cache_source.yaml +81 -0
  265. mapproxy/test/system/fixture/combined_sources.yaml +130 -0
  266. mapproxy/test/system/fixture/coverage.yaml +77 -0
  267. mapproxy/test/system/fixture/demo.yaml +135 -0
  268. mapproxy/test/system/fixture/dimension.yaml +59 -0
  269. mapproxy/test/system/fixture/disable_storage.yaml +25 -0
  270. mapproxy/test/system/fixture/empty_ogrdata.geojson +1 -0
  271. mapproxy/test/system/fixture/formats.yaml +72 -0
  272. mapproxy/test/system/fixture/inspire.yaml +101 -0
  273. mapproxy/test/system/fixture/inspire_full.yaml +124 -0
  274. mapproxy/test/system/fixture/kml_layer.yaml +66 -0
  275. mapproxy/test/system/fixture/layer.yaml +260 -0
  276. mapproxy/test/system/fixture/layergroups.yaml +57 -0
  277. mapproxy/test/system/fixture/layergroups_root.yaml +106 -0
  278. mapproxy/test/system/fixture/legendgraphic.yaml +93 -0
  279. mapproxy/test/system/fixture/mapnik_source.yaml +66 -0
  280. mapproxy/test/system/fixture/mapproxy_export.yaml +12 -0
  281. mapproxy/test/system/fixture/mapserver.yaml +23 -0
  282. mapproxy/test/system/fixture/minimal_cgi.py +16 -0
  283. mapproxy/test/system/fixture/mixed_mode.yaml +49 -0
  284. mapproxy/test/system/fixture/multi_cache_layers.yaml +111 -0
  285. mapproxy/test/system/fixture/multiapp1.yaml +20 -0
  286. mapproxy/test/system/fixture/multiapp2.yaml +19 -0
  287. mapproxy/test/system/fixture/renderd_client.yaml +55 -0
  288. mapproxy/test/system/fixture/scalehints.yaml +70 -0
  289. mapproxy/test/system/fixture/seed.yaml +94 -0
  290. mapproxy/test/system/fixture/seed_mapproxy.yaml +39 -0
  291. mapproxy/test/system/fixture/seed_old.yaml +12 -0
  292. mapproxy/test/system/fixture/seed_timeouts.yaml +12 -0
  293. mapproxy/test/system/fixture/seed_timeouts_mapproxy.yaml +27 -0
  294. mapproxy/test/system/fixture/seedonly.yaml +51 -0
  295. mapproxy/test/system/fixture/sld.yaml +35 -0
  296. mapproxy/test/system/fixture/source_errors.yaml +84 -0
  297. mapproxy/test/system/fixture/source_errors_raise.yaml +82 -0
  298. mapproxy/test/system/fixture/tileservice_origin.yaml +26 -0
  299. mapproxy/test/system/fixture/tileservice_refresh.yaml +59 -0
  300. mapproxy/test/system/fixture/tilesource_minmax_res.yaml +22 -0
  301. mapproxy/test/system/fixture/util-conf-base-grids.yaml +5 -0
  302. mapproxy/test/system/fixture/util-conf-overwrite.yaml +13 -0
  303. mapproxy/test/system/fixture/util-conf-wms-111-cap.xml +90 -0
  304. mapproxy/test/system/fixture/util_grids.yaml +29 -0
  305. mapproxy/test/system/fixture/util_wms_capabilities111.xml +130 -0
  306. mapproxy/test/system/fixture/util_wms_capabilities130.xml +100 -0
  307. mapproxy/test/system/fixture/util_wms_capabilities_service_exception.xml +5 -0
  308. mapproxy/test/system/fixture/watermark.yaml +50 -0
  309. mapproxy/test/system/fixture/wms_srs_extent.yaml +39 -0
  310. mapproxy/test/system/fixture/wms_versions.yaml +38 -0
  311. mapproxy/test/system/fixture/wmts.yaml +134 -0
  312. mapproxy/test/system/fixture/wmts_dimensions.yaml +57 -0
  313. mapproxy/test/system/fixture/xslt_featureinfo.yaml +54 -0
  314. mapproxy/test/system/fixture/xslt_featureinfo_input.yaml +51 -0
  315. mapproxy/test/system/test_arcgis.py +156 -0
  316. mapproxy/test/system/test_auth.py +1133 -0
  317. mapproxy/test/system/test_behind_proxy.py +75 -0
  318. mapproxy/test/system/test_bulk_meta_tiles.py +106 -0
  319. mapproxy/test/system/test_cache_azureblob.py +127 -0
  320. mapproxy/test/system/test_cache_band_merge.py +103 -0
  321. mapproxy/test/system/test_cache_coverage.py +168 -0
  322. mapproxy/test/system/test_cache_geopackage.py +144 -0
  323. mapproxy/test/system/test_cache_grid_names.py +89 -0
  324. mapproxy/test/system/test_cache_mbtiles.py +85 -0
  325. mapproxy/test/system/test_cache_s3.py +115 -0
  326. mapproxy/test/system/test_cache_source.py +146 -0
  327. mapproxy/test/system/test_combined_sources.py +335 -0
  328. mapproxy/test/system/test_coverage.py +140 -0
  329. mapproxy/test/system/test_decorate_img.py +214 -0
  330. mapproxy/test/system/test_demo.py +56 -0
  331. mapproxy/test/system/test_demo_with_extra_service.py +57 -0
  332. mapproxy/test/system/test_dimensions.py +279 -0
  333. mapproxy/test/system/test_disable_storage.py +42 -0
  334. mapproxy/test/system/test_formats.py +219 -0
  335. mapproxy/test/system/test_inspire_vs.py +173 -0
  336. mapproxy/test/system/test_kml.py +264 -0
  337. mapproxy/test/system/test_layergroups.py +160 -0
  338. mapproxy/test/system/test_legendgraphic.py +308 -0
  339. mapproxy/test/system/test_mapnik.py +162 -0
  340. mapproxy/test/system/test_mapserver.py +83 -0
  341. mapproxy/test/system/test_mixed_mode_format.py +201 -0
  342. mapproxy/test/system/test_multi_cache_layers.py +169 -0
  343. mapproxy/test/system/test_multiapp.py +92 -0
  344. mapproxy/test/system/test_refresh.py +206 -0
  345. mapproxy/test/system/test_renderd_client.py +304 -0
  346. mapproxy/test/system/test_response_headers.py +54 -0
  347. mapproxy/test/system/test_scalehints.py +140 -0
  348. mapproxy/test/system/test_seed.py +425 -0
  349. mapproxy/test/system/test_seed_only.py +93 -0
  350. mapproxy/test/system/test_sld.py +120 -0
  351. mapproxy/test/system/test_source_errors.py +377 -0
  352. mapproxy/test/system/test_tilesource_minmax_res.py +54 -0
  353. mapproxy/test/system/test_tms.py +277 -0
  354. mapproxy/test/system/test_tms_origin.py +46 -0
  355. mapproxy/test/system/test_util_conf.py +434 -0
  356. mapproxy/test/system/test_util_export.py +210 -0
  357. mapproxy/test/system/test_util_grids.py +88 -0
  358. mapproxy/test/system/test_util_wms_capabilities.py +182 -0
  359. mapproxy/test/system/test_watermark.py +91 -0
  360. mapproxy/test/system/test_wms.py +1616 -0
  361. mapproxy/test/system/test_wms_srs_extent.py +165 -0
  362. mapproxy/test/system/test_wms_version.py +85 -0
  363. mapproxy/test/system/test_wmsc.py +116 -0
  364. mapproxy/test/system/test_wmts.py +334 -0
  365. mapproxy/test/system/test_wmts_dimensions.py +206 -0
  366. mapproxy/test/system/test_wmts_restful.py +198 -0
  367. mapproxy/test/system/test_xslt_featureinfo.py +423 -0
  368. mapproxy/test/test_http_helper.py +217 -0
  369. mapproxy/test/unit/__init__.py +0 -0
  370. mapproxy/test/unit/epsg +2 -0
  371. mapproxy/test/unit/polygons/polygons.dbf +0 -0
  372. mapproxy/test/unit/polygons/polygons.shp +0 -0
  373. mapproxy/test/unit/polygons/polygons.shx +0 -0
  374. mapproxy/test/unit/test_async.py +242 -0
  375. mapproxy/test/unit/test_auth.py +430 -0
  376. mapproxy/test/unit/test_cache.py +1356 -0
  377. mapproxy/test/unit/test_cache_azureblob.py +97 -0
  378. mapproxy/test/unit/test_cache_compact.py +324 -0
  379. mapproxy/test/unit/test_cache_couchdb.py +118 -0
  380. mapproxy/test/unit/test_cache_geopackage.py +256 -0
  381. mapproxy/test/unit/test_cache_redis.py +123 -0
  382. mapproxy/test/unit/test_cache_riak.py +80 -0
  383. mapproxy/test/unit/test_cache_s3.py +93 -0
  384. mapproxy/test/unit/test_cache_tile.py +477 -0
  385. mapproxy/test/unit/test_client.py +488 -0
  386. mapproxy/test/unit/test_client_arcgis.py +74 -0
  387. mapproxy/test/unit/test_client_cgi.py +140 -0
  388. mapproxy/test/unit/test_collections.py +116 -0
  389. mapproxy/test/unit/test_concat_legends.py +37 -0
  390. mapproxy/test/unit/test_conf_loader.py +1267 -0
  391. mapproxy/test/unit/test_conf_validator.py +427 -0
  392. mapproxy/test/unit/test_config.py +118 -0
  393. mapproxy/test/unit/test_decorate_img.py +185 -0
  394. mapproxy/test/unit/test_exceptions.py +270 -0
  395. mapproxy/test/unit/test_featureinfo.py +313 -0
  396. mapproxy/test/unit/test_file_lock_load.py +49 -0
  397. mapproxy/test/unit/test_geom.py +512 -0
  398. mapproxy/test/unit/test_grid.py +1279 -0
  399. mapproxy/test/unit/test_image.py +1051 -0
  400. mapproxy/test/unit/test_image_mask.py +181 -0
  401. mapproxy/test/unit/test_image_messages.py +209 -0
  402. mapproxy/test/unit/test_image_options.py +160 -0
  403. mapproxy/test/unit/test_isodate.py +118 -0
  404. mapproxy/test/unit/test_multiapp.py +163 -0
  405. mapproxy/test/unit/test_ogr_reader.py +51 -0
  406. mapproxy/test/unit/test_request.py +745 -0
  407. mapproxy/test/unit/test_request_wmts.py +178 -0
  408. mapproxy/test/unit/test_response.py +78 -0
  409. mapproxy/test/unit/test_seed.py +365 -0
  410. mapproxy/test/unit/test_seed_cachelock.py +91 -0
  411. mapproxy/test/unit/test_srs.py +215 -0
  412. mapproxy/test/unit/test_tiled_source.py +122 -0
  413. mapproxy/test/unit/test_tilefilter.py +31 -0
  414. mapproxy/test/unit/test_times.py +25 -0
  415. mapproxy/test/unit/test_timeutils.py +50 -0
  416. mapproxy/test/unit/test_util_conf_utils.py +75 -0
  417. mapproxy/test/unit/test_utils.py +476 -0
  418. mapproxy/test/unit/test_wms_capabilities.py +44 -0
  419. mapproxy/test/unit/test_wms_layer.py +113 -0
  420. mapproxy/test/unit/test_yaml.py +68 -0
  421. mapproxy/tilefilter.py +61 -0
  422. mapproxy/util/__init__.py +0 -0
  423. mapproxy/util/async_.py +229 -0
  424. mapproxy/util/collections.py +134 -0
  425. mapproxy/util/coverage.py +337 -0
  426. mapproxy/util/ext/__init__.py +14 -0
  427. mapproxy/util/ext/dictspec/__init__.py +1 -0
  428. mapproxy/util/ext/dictspec/spec.py +131 -0
  429. mapproxy/util/ext/dictspec/test/__init__.py +0 -0
  430. mapproxy/util/ext/dictspec/test/test_validator.py +278 -0
  431. mapproxy/util/ext/dictspec/validator.py +194 -0
  432. mapproxy/util/ext/local.py +198 -0
  433. mapproxy/util/ext/lockfile.py +140 -0
  434. mapproxy/util/ext/odict.py +321 -0
  435. mapproxy/util/ext/serving.py +491 -0
  436. mapproxy/util/ext/tempita/__init__.py +1093 -0
  437. mapproxy/util/ext/tempita/_looper.py +163 -0
  438. mapproxy/util/ext/tempita/string_utils.py +24 -0
  439. mapproxy/util/ext/wmsparse/__init__.py +3 -0
  440. mapproxy/util/ext/wmsparse/duration.py +600 -0
  441. mapproxy/util/ext/wmsparse/parse.py +307 -0
  442. mapproxy/util/ext/wmsparse/test/__init__.py +0 -0
  443. mapproxy/util/ext/wmsparse/test/test_parse.py +111 -0
  444. mapproxy/util/ext/wmsparse/test/test_util.py +23 -0
  445. mapproxy/util/ext/wmsparse/test/wms-example-111.xml +90 -0
  446. mapproxy/util/ext/wmsparse/test/wms-example-130.xml +120 -0
  447. mapproxy/util/ext/wmsparse/test/wms-large-111.xml +2114 -0
  448. mapproxy/util/ext/wmsparse/test/wms_nasa_cap.xml +386 -0
  449. mapproxy/util/ext/wmsparse/util.py +189 -0
  450. mapproxy/util/fs.py +164 -0
  451. mapproxy/util/geom.py +307 -0
  452. mapproxy/util/lib.py +117 -0
  453. mapproxy/util/lock.py +171 -0
  454. mapproxy/util/ogr.py +247 -0
  455. mapproxy/util/py.py +75 -0
  456. mapproxy/util/times.py +78 -0
  457. mapproxy/util/yaml.py +58 -0
  458. mapproxy/version.py +33 -0
  459. mapproxy/wsgiapp.py +167 -0
@@ -0,0 +1,2291 @@
1
+ """
2
+ Mocker
3
+
4
+ Graceful platform for test doubles in Python: mocks, stubs, fakes, and dummies.
5
+
6
+ Copyright (c) 2007-2010, Gustavo Niemeyer <gustavo@niemeyer.net>
7
+
8
+ All rights reserved.
9
+
10
+ Redistribution and use in source and binary forms, with or without
11
+ modification, are permitted provided that the following conditions are met:
12
+
13
+ * Redistributions of source code must retain the above copyright notice,
14
+ this list of conditions and the following disclaimer.
15
+ * Redistributions in binary form must reproduce the above copyright notice,
16
+ this list of conditions and the following disclaimer in the documentation
17
+ and/or other materials provided with the distribution.
18
+ * Neither the name of the copyright holder nor the names of its
19
+ contributors may be used to endorse or promote products derived from
20
+ this software without specific prior written permission.
21
+
22
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
23
+ "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
24
+ LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
25
+ A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
26
+ CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
27
+ EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
28
+ PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
29
+ PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
30
+ LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
31
+ NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
32
+ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
33
+ """
34
+ import tempfile
35
+ import unittest
36
+ import inspect
37
+ import shutil
38
+ import types
39
+ import sys
40
+ import os
41
+ import re
42
+ import gc
43
+
44
+
45
+ if sys.version_info < (2, 4):
46
+ from sets import Set as set # pragma: nocover
47
+
48
+ if sys.version_info[0] == 2:
49
+ import __builtin__
50
+ else:
51
+ import builtins as __builtin__
52
+
53
+
54
+ __all__ = ["Mocker", "Expect", "expect", "IS", "CONTAINS", "IN", "MATCH",
55
+ "ANY", "ARGS", "KWARGS", "MockerTestCase"]
56
+
57
+
58
+ __author__ = "Gustavo Niemeyer <gustavo@niemeyer.net>"
59
+ __license__ = "BSD"
60
+ __version__ = "1.1"
61
+
62
+
63
+ ERROR_PREFIX = "[Mocker] "
64
+
65
+
66
+ # --------------------------------------------------------------------
67
+ # Exceptions
68
+
69
+ class MatchError(AssertionError):
70
+ """Raised when an unknown expression is seen in playback mode."""
71
+
72
+
73
+ # --------------------------------------------------------------------
74
+ # Helper for chained-style calling.
75
+
76
+ class expect(object):
77
+ """This is a simple helper that allows a different call-style.
78
+
79
+ With this class one can comfortably do chaining of calls to the
80
+ mocker object responsible by the object being handled. For instance::
81
+
82
+ expect(obj.attr).result(3).count(1, 2)
83
+
84
+ Is the same as::
85
+
86
+ obj.attr
87
+ mocker.result(3)
88
+ mocker.count(1, 2)
89
+
90
+ """
91
+
92
+ __mocker__ = None
93
+
94
+ def __init__(self, mock, attr=None):
95
+ self._mock = mock
96
+ self._attr = attr
97
+
98
+ def __getattr__(self, attr):
99
+ return self.__class__(self._mock, attr)
100
+
101
+ def __call__(self, *args, **kwargs):
102
+ mocker = self.__mocker__
103
+ if not mocker:
104
+ mocker = self._mock.__mocker__
105
+ getattr(mocker, self._attr)(*args, **kwargs)
106
+ return self
107
+
108
+
109
+ def Expect(mocker):
110
+ """Create an expect() "function" using the given Mocker instance.
111
+
112
+ This helper allows defining an expect() "function" which works even
113
+ in trickier cases such as:
114
+
115
+ expect = Expect(mymocker)
116
+ expect(iter(mock)).generate([1, 2, 3])
117
+
118
+ """
119
+ return type("Expect", (expect,), {"__mocker__": mocker})
120
+
121
+
122
+ # --------------------------------------------------------------------
123
+ # Extensions to Python's unittest.
124
+
125
+ class MockerTestCase(unittest.TestCase):
126
+ """unittest.TestCase subclass with Mocker support.
127
+
128
+ @ivar mocker: The mocker instance.
129
+
130
+ This is a convenience only. Mocker may easily be used with the
131
+ standard C{unittest.TestCase} class if wanted.
132
+
133
+ Test methods have a Mocker instance available on C{self.mocker}.
134
+ At the end of each test method, expectations of the mocker will
135
+ be verified, and any requested changes made to the environment
136
+ will be restored.
137
+
138
+ In addition to the integration with Mocker, this class provides
139
+ a few additional helper methods.
140
+ """
141
+
142
+ def __init__(self, methodName="runTest"):
143
+ # So here is the trick: we take the real test method, wrap it on
144
+ # a function that do the job we have to do, and insert it in the
145
+ # *instance* dictionary, so that getattr() will return our
146
+ # replacement rather than the class method.
147
+ test_method = getattr(self, methodName, None)
148
+ if test_method is not None:
149
+ def test_method_wrapper():
150
+ try:
151
+ result = test_method()
152
+ except Exception:
153
+ raise
154
+ else:
155
+ if (self.mocker.is_recording() and
156
+ self.mocker.get_events()):
157
+ raise RuntimeError("Mocker must be put in replay "
158
+ "mode with self.mocker.replay()")
159
+ if (hasattr(result, "addCallback") and
160
+ hasattr(result, "addErrback")):
161
+ def verify(result):
162
+ self.mocker.verify()
163
+ return result
164
+ result.addCallback(verify)
165
+ else:
166
+ self.mocker.verify()
167
+ self.mocker.restore()
168
+ return result
169
+ # Copy all attributes from the original method..
170
+ for attr in dir(test_method):
171
+ # .. unless they're present in our wrapper already.
172
+ if not hasattr(test_method_wrapper, attr) or attr == "__doc__":
173
+ setattr(test_method_wrapper, attr,
174
+ getattr(test_method, attr))
175
+ setattr(self, methodName, test_method_wrapper)
176
+
177
+ # We could overload run() normally, but other well-known testing
178
+ # frameworks do it as well, and some of them won't call the super,
179
+ # which might mean that cleanup wouldn't happen. With that in mind,
180
+ # we make integration easier by using the following trick.
181
+ run_method = self.run
182
+
183
+ def run_wrapper(*args, **kwargs):
184
+ try:
185
+ return run_method(*args, **kwargs)
186
+ finally:
187
+ self.__cleanup()
188
+ self.run = run_wrapper
189
+
190
+ self.mocker = Mocker()
191
+ self.expect = Expect(self.mocker)
192
+
193
+ self.__cleanup_funcs = []
194
+ self.__cleanup_paths = []
195
+
196
+ super(MockerTestCase, self).__init__(methodName)
197
+
198
+ def __call__(self, *args, **kwargs):
199
+ # This is necessary for Python 2.3 only, because it didn't use run(),
200
+ # which is supported above.
201
+ try:
202
+ super(MockerTestCase, self).__call__(*args, **kwargs)
203
+ finally:
204
+ if sys.version_info < (2, 4):
205
+ self.__cleanup()
206
+
207
+ def __cleanup(self):
208
+ for path in self.__cleanup_paths:
209
+ if os.path.isfile(path):
210
+ os.unlink(path)
211
+ elif os.path.isdir(path):
212
+ shutil.rmtree(path)
213
+ self.mocker.reset()
214
+ for func, args, kwargs in self.__cleanup_funcs:
215
+ func(*args, **kwargs)
216
+
217
+ def addCleanup(self, func, *args, **kwargs):
218
+ self.__cleanup_funcs.append((func, args, kwargs))
219
+
220
+ def makeFile(self, content=None, suffix="", prefix="tmp", basename=None,
221
+ dirname=None, path=None):
222
+ """Create a temporary file and return the path to it.
223
+
224
+ @param content: Initial content for the file.
225
+ @param suffix: Suffix to be given to the file's basename.
226
+ @param prefix: Prefix to be given to the file's basename.
227
+ @param basename: Full basename for the file.
228
+ @param dirname: Put file inside this directory.
229
+
230
+ The file is removed after the test runs.
231
+ """
232
+ if path is not None:
233
+ self.__cleanup_paths.append(path)
234
+ elif basename is not None:
235
+ if dirname is None:
236
+ dirname = tempfile.mkdtemp()
237
+ self.__cleanup_paths.append(dirname)
238
+ path = os.path.join(dirname, basename)
239
+ else:
240
+ fd, path = tempfile.mkstemp(suffix, prefix, dirname)
241
+ self.__cleanup_paths.append(path)
242
+ os.close(fd)
243
+ if content is None:
244
+ os.unlink(path)
245
+ if content is not None:
246
+ file = open(path, "w")
247
+ file.write(content)
248
+ file.close()
249
+ return path
250
+
251
+ def makeDir(self, suffix="", prefix="tmp", dirname=None, path=None):
252
+ """Create a temporary directory and return the path to it.
253
+
254
+ @param suffix: Suffix to be given to the file's basename.
255
+ @param prefix: Prefix to be given to the file's basename.
256
+ @param dirname: Put directory inside this parent directory.
257
+
258
+ The directory is removed after the test runs.
259
+ """
260
+ if path is not None:
261
+ os.makedirs(path)
262
+ else:
263
+ path = tempfile.mkdtemp(suffix, prefix, dirname)
264
+ self.__cleanup_paths.append(path)
265
+ return path
266
+
267
+ def failUnlessIs(self, first, second, msg=None):
268
+ """Assert that C{first} is the same object as C{second}."""
269
+ if first is not second:
270
+ raise self.failureException(msg or "%r is not %r" % (first, second))
271
+
272
+ def failIfIs(self, first, second, msg=None):
273
+ """Assert that C{first} is not the same object as C{second}."""
274
+ if first is second:
275
+ raise self.failureException(msg or "%r is %r" % (first, second))
276
+
277
+ def failUnlessIn(self, first, second, msg=None):
278
+ """Assert that C{first} is contained in C{second}."""
279
+ if first not in second:
280
+ raise self.failureException(msg or "%r not in %r" % (first, second))
281
+
282
+ def failUnlessStartsWith(self, first, second, msg=None):
283
+ """Assert that C{first} starts with C{second}."""
284
+ if first[:len(second)] != second:
285
+ raise self.failureException(msg or "%r doesn't start with %r" %
286
+ (first, second))
287
+
288
+ def failIfStartsWith(self, first, second, msg=None):
289
+ """Assert that C{first} doesn't start with C{second}."""
290
+ if first[:len(second)] == second:
291
+ raise self.failureException(msg or "%r starts with %r" %
292
+ (first, second))
293
+
294
+ def failUnlessEndsWith(self, first, second, msg=None):
295
+ """Assert that C{first} starts with C{second}."""
296
+ if first[len(first)-len(second):] != second:
297
+ raise self.failureException(msg or "%r doesn't end with %r" %
298
+ (first, second))
299
+
300
+ def failIfEndsWith(self, first, second, msg=None):
301
+ """Assert that C{first} doesn't start with C{second}."""
302
+ if first[len(first)-len(second):] == second:
303
+ raise self.failureException(msg or "%r ends with %r" %
304
+ (first, second))
305
+
306
+ def failIfIn(self, first, second, msg=None):
307
+ """Assert that C{first} is not contained in C{second}."""
308
+ if first in second:
309
+ raise self.failureException(msg or "%r in %r" % (first, second))
310
+
311
+ def failUnlessApproximates(self, first, second, tolerance, msg=None):
312
+ """Assert that C{first} is near C{second} by at most C{tolerance}."""
313
+ if abs(first - second) > tolerance:
314
+ raise self.failureException(msg or "abs(%r - %r) > %r" %
315
+ (first, second, tolerance))
316
+
317
+ def failIfApproximates(self, first, second, tolerance, msg=None):
318
+ """Assert that C{first} is far from C{second} by at least C{tolerance}.
319
+ """
320
+ if abs(first - second) <= tolerance:
321
+ raise self.failureException(msg or "abs(%r - %r) <= %r" %
322
+ (first, second, tolerance))
323
+
324
+ def failUnlessMethodsMatch(self, first, second):
325
+ """Assert that public methods in C{first} are present in C{second}.
326
+
327
+ This method asserts that all public methods found in C{first} are also
328
+ present in C{second} and accept the same arguments. C{first} may
329
+ have its own private methods, though, and may not have all methods
330
+ found in C{second}. Note that if a private method in C{first} matches
331
+ the name of one in C{second}, their specification is still compared.
332
+
333
+ This is useful to verify if a fake or stub class have the same API as
334
+ the real class being simulated.
335
+ """
336
+ first_methods = dict(inspect.getmembers(first, inspect.ismethod))
337
+ second_methods = dict(inspect.getmembers(second, inspect.ismethod))
338
+ for name, first_method in first_methods.items():
339
+ first_argspec = inspect.getargspec(first_method)
340
+ first_formatted = inspect.formatargspec(*first_argspec)
341
+
342
+ second_method = second_methods.get(name)
343
+ if second_method is None:
344
+ if name[:1] == "_":
345
+ continue # First may have its own private methods.
346
+ raise self.failureException("%s.%s%s not present in %s" %
347
+ (first.__name__, name, first_formatted, second.__name__))
348
+
349
+ second_argspec = inspect.getargspec(second_method)
350
+ if first_argspec != second_argspec:
351
+ second_formatted = inspect.formatargspec(*second_argspec)
352
+ raise self.failureException("%s.%s%s != %s.%s%s" %
353
+ (first.__name__, name, first_formatted,
354
+ second.__name__, name, second_formatted))
355
+
356
+ def failUnlessRaises(self, excClass, *args, **kwargs):
357
+ """
358
+ Fail unless an exception of class excClass is thrown by callableObj
359
+ when invoked with arguments args and keyword arguments kwargs. If a
360
+ different type of exception is thrown, it will not be caught, and the
361
+ test case will be deemed to have suffered an error, exactly as for an
362
+ unexpected exception. It returns the exception instance if it matches
363
+ the given exception class.
364
+
365
+ This may also be used as a context manager when provided with a single
366
+ argument, as such:
367
+
368
+ with self.failUnlessRaises(ExcClass):
369
+ logic_which_should_raise()
370
+ """
371
+ return self.failUnlessRaisesRegexp(excClass, None, *args, **kwargs)
372
+
373
+ def failUnlessRaisesRegexp(self, excClass, regexp, *args, **kwargs):
374
+ """
375
+ Fail unless an exception of class excClass is thrown by callableObj
376
+ when invoked with arguments args and keyword arguments kwargs, and
377
+ the str(error) value matches the provided regexp. If a different type
378
+ of exception is thrown, it will not be caught, and the test case will
379
+ be deemed to have suffered an error, exactly as for an unexpected
380
+ exception. It returns the exception instance if it matches the given
381
+ exception class.
382
+
383
+ This may also be used as a context manager when provided with a single
384
+ argument, as such:
385
+
386
+ with self.failUnlessRaisesRegexp(ExcClass, "something like.*happened"):
387
+ logic_which_should_raise()
388
+ """
389
+ def match_regexp(error):
390
+ error_str = str(error)
391
+ if regexp is not None and not re.search(regexp, error_str):
392
+ raise self.failureException("%r doesn't match %r" %
393
+ (error_str, regexp))
394
+ excName = self.__class_name(excClass)
395
+ if args:
396
+ callableObj = args[0]
397
+ try:
398
+ result = callableObj(*args[1:], **kwargs)
399
+ except excClass as e:
400
+ match_regexp(e)
401
+ return e
402
+ else:
403
+ raise self.failureException("%s not raised (%r returned)" %
404
+ (excName, result))
405
+ else:
406
+ test = self
407
+
408
+ class AssertRaisesContextManager(object):
409
+ def __enter__(self):
410
+ return self
411
+
412
+ def __exit__(self, type, value, traceback):
413
+ self.exception = value
414
+ if value is None:
415
+ raise test.failureException("%s not raised" % excName)
416
+ elif isinstance(value, excClass):
417
+ match_regexp(value)
418
+ return True
419
+ return AssertRaisesContextManager()
420
+
421
+ def __class_name(self, cls):
422
+ return getattr(cls, "__name__", str(cls))
423
+
424
+ def failUnlessIsInstance(self, obj, cls, msg=None):
425
+ """Assert that isinstance(obj, cls)."""
426
+ if not isinstance(obj, cls):
427
+ if msg is None:
428
+ msg = "%r is not an instance of %s" % \
429
+ (obj, self.__class_name(cls))
430
+ raise self.failureException(msg)
431
+
432
+ def failIfIsInstance(self, obj, cls, msg=None):
433
+ """Assert that isinstance(obj, cls) is False."""
434
+ if isinstance(obj, cls):
435
+ if msg is None:
436
+ msg = "%r is an instance of %s" % \
437
+ (obj, self.__class_name(cls))
438
+ raise self.failureException(msg)
439
+
440
+ assertIs = failUnlessIs
441
+ assertIsNot = failIfIs
442
+ assertIn = failUnlessIn
443
+ assertNotIn = failIfIn
444
+ assertStartsWith = failUnlessStartsWith
445
+ assertNotStartsWith = failIfStartsWith
446
+ assertEndsWith = failUnlessEndsWith
447
+ assertNotEndsWith = failIfEndsWith
448
+ assertApproximates = failUnlessApproximates
449
+ assertNotApproximates = failIfApproximates
450
+ assertMethodsMatch = failUnlessMethodsMatch
451
+ assertRaises = failUnlessRaises
452
+ assertRaisesRegexp = failUnlessRaisesRegexp
453
+ assertIsInstance = failUnlessIsInstance
454
+ assertIsNotInstance = failIfIsInstance
455
+ assertNotIsInstance = failIfIsInstance # Poor choice in 2.7/3.2+.
456
+
457
+ # The following are missing in Python < 2.4.
458
+ if sys.version_info < (2, 4):
459
+ assertTrue = unittest.TestCase.failUnless
460
+ assertFalse = unittest.TestCase.failIf
461
+ else:
462
+ assertTrue = unittest.TestCase.assertTrue
463
+ assertFalse = unittest.TestCase.assertFalse
464
+
465
+ # The following is provided for compatibility with Twisted's trial.
466
+ assertIdentical = assertIs
467
+ assertNotIdentical = assertIsNot
468
+ failUnlessIdentical = failUnlessIs
469
+ failIfIdentical = failIfIs
470
+
471
+
472
+ # --------------------------------------------------------------------
473
+ # Mocker.
474
+
475
+ class classinstancemethod(object):
476
+
477
+ def __init__(self, method):
478
+ self.method = method
479
+
480
+ def __get__(self, obj, cls=None):
481
+ def bound_method(*args, **kwargs):
482
+ return self.method(cls, obj, *args, **kwargs)
483
+ return bound_method
484
+
485
+
486
+ class MockerBase(object):
487
+ """Controller of mock objects.
488
+
489
+ A mocker instance is used to command recording and replay of
490
+ expectations on any number of mock objects.
491
+
492
+ Expectations should be expressed for the mock object while in
493
+ record mode (the initial one) by using the mock object itself,
494
+ and using the mocker (and/or C{expect()} as a helper) to define
495
+ additional behavior for each event. For instance::
496
+
497
+ mock = mocker.mock()
498
+ mock.hello()
499
+ mocker.result("Hi!")
500
+ mocker.replay()
501
+ assert mock.hello() == "Hi!"
502
+ mock.restore()
503
+ mock.verify()
504
+
505
+ In this short excerpt a mock object is being created, then an
506
+ expectation of a call to the C{hello()} method was recorded, and
507
+ when called the method should return the value C{10}. Then, the
508
+ mocker is put in replay mode, and the expectation is satisfied by
509
+ calling the C{hello()} method, which indeed returns 10. Finally,
510
+ a call to the L{restore()} method is performed to undo any needed
511
+ changes made in the environment, and the L{verify()} method is
512
+ called to ensure that all defined expectations were met.
513
+
514
+ The same logic can be expressed more elegantly using the
515
+ C{with mocker:} statement, as follows::
516
+
517
+ mock = mocker.mock()
518
+ mock.hello()
519
+ mocker.result("Hi!")
520
+ with mocker:
521
+ assert mock.hello() == "Hi!"
522
+
523
+ Also, the MockerTestCase class, which integrates the mocker on
524
+ a unittest.TestCase subclass, may be used to reduce the overhead
525
+ of controlling the mocker. A test could be written as follows::
526
+
527
+ class SampleTest(MockerTestCase):
528
+
529
+ def test_hello(self):
530
+ mock = self.mocker.mock()
531
+ mock.hello()
532
+ self.mocker.result("Hi!")
533
+ self.mocker.replay()
534
+ self.assertEquals(mock.hello(), "Hi!")
535
+ """
536
+
537
+ _recorders = []
538
+
539
+ # For convenience only.
540
+ on = expect
541
+
542
+ class __metaclass__(type):
543
+ def __init__(self, name, bases, dict):
544
+ # Make independent lists on each subclass, inheriting from parent.
545
+ self._recorders = list(getattr(self, "_recorders", ()))
546
+
547
+ def __init__(self):
548
+ self._recorders = self._recorders[:]
549
+ self._events = []
550
+ self._recording = True
551
+ self._ordering = False
552
+ self._last_orderer = None
553
+
554
+ def is_recording(self):
555
+ """Return True if in recording mode, False if in replay mode.
556
+
557
+ Recording is the initial state.
558
+ """
559
+ return self._recording
560
+
561
+ def replay(self):
562
+ """Change to replay mode, where recorded events are reproduced.
563
+
564
+ If already in replay mode, the mocker will be restored, with all
565
+ expectations reset, and then put again in replay mode.
566
+
567
+ An alternative and more comfortable way to replay changes is
568
+ using the 'with' statement, as follows::
569
+
570
+ mocker = Mocker()
571
+ <record events>
572
+ with mocker:
573
+ <reproduce events>
574
+
575
+ The 'with' statement will automatically put mocker in replay
576
+ mode, and will also verify if all events were correctly reproduced
577
+ at the end (using L{verify()}), and also restore any changes done
578
+ in the environment (with L{restore()}).
579
+
580
+ Also check the MockerTestCase class, which integrates the
581
+ unittest.TestCase class with mocker.
582
+ """
583
+ if not self._recording:
584
+ for event in self._events:
585
+ event.restore()
586
+ else:
587
+ self._recording = False
588
+ for event in self._events:
589
+ event.replay()
590
+
591
+ def restore(self):
592
+ """Restore changes in the environment, and return to recording mode.
593
+
594
+ This should always be called after the test is complete (succeeding
595
+ or not). There are ways to call this method automatically on
596
+ completion (e.g. using a C{with mocker:} statement, or using the
597
+ L{MockerTestCase} class.
598
+ """
599
+ if not self._recording:
600
+ self._recording = True
601
+ for event in self._events:
602
+ event.restore()
603
+
604
+ def reset(self):
605
+ """Reset the mocker state.
606
+
607
+ This will restore environment changes, if currently in replay
608
+ mode, and then remove all events previously recorded.
609
+ """
610
+ if not self._recording:
611
+ self.restore()
612
+ self.unorder()
613
+ del self._events[:]
614
+
615
+ def get_events(self):
616
+ """Return all recorded events."""
617
+ return self._events[:]
618
+
619
+ def add_event(self, event):
620
+ """Add an event.
621
+
622
+ This method is used internally by the implementation, and
623
+ shouldn't be needed on normal mocker usage.
624
+ """
625
+ self._events.append(event)
626
+ if self._ordering:
627
+ orderer = event.add_task(Orderer(event.path))
628
+ if self._last_orderer:
629
+ orderer.add_dependency(self._last_orderer)
630
+ self._last_orderer = orderer
631
+ return event
632
+
633
+ def verify(self):
634
+ """Check if all expectations were met, and raise AssertionError if not.
635
+
636
+ The exception message will include a nice description of which
637
+ expectations were not met, and why.
638
+ """
639
+ errors = []
640
+ for event in self._events:
641
+ try:
642
+ event.verify()
643
+ except AssertionError as e:
644
+ error = str(e)
645
+ if not error:
646
+ raise RuntimeError("Empty error message from %r"
647
+ % event)
648
+ errors.append(error)
649
+ if errors:
650
+ message = [ERROR_PREFIX + "Unmet expectations:", ""]
651
+ for error in errors:
652
+ lines = error.splitlines()
653
+ message.append("=> " + lines.pop(0))
654
+ message.extend([" " + line for line in lines])
655
+ message.append("")
656
+ raise AssertionError(os.linesep.join(message))
657
+
658
+ def mock(self, spec_and_type=None, spec=None, type=None,
659
+ name=None, count=True):
660
+ """Return a new mock object.
661
+
662
+ @param spec_and_type: Handy positional argument which sets both
663
+ spec and type.
664
+ @param spec: Method calls will be checked for correctness against
665
+ the given class.
666
+ @param type: If set, the Mock's __class__ attribute will return
667
+ the given type. This will make C{isinstance()} calls
668
+ on the object work.
669
+ @param name: Name for the mock object, used in the representation of
670
+ expressions. The name is rarely needed, as it's usually
671
+ guessed correctly from the variable name used.
672
+ @param count: If set to false, expressions may be executed any number
673
+ of times, unless an expectation is explicitly set using
674
+ the L{count()} method. By default, expressions are
675
+ expected once.
676
+ """
677
+ if spec_and_type is not None:
678
+ spec = type = spec_and_type
679
+ return Mock(self, spec=spec, type=type, name=name, count=count)
680
+
681
+ def proxy(self, object, spec=True, type=True, name=None, count=True,
682
+ passthrough=True):
683
+ """Return a new mock object which proxies to the given object.
684
+
685
+ Proxies are useful when only part of the behavior of an object
686
+ is to be mocked. Unknown expressions may be passed through to
687
+ the real implementation implicitly (if the C{passthrough} argument
688
+ is True), or explicitly (using the L{passthrough()} method
689
+ on the event).
690
+
691
+ @param object: Real object to be proxied, and replaced by the mock
692
+ on replay mode. It may also be an "import path",
693
+ such as C{"time.time"}, in which case the object
694
+ will be the C{time} function from the C{time} module.
695
+ @param spec: Method calls will be checked for correctness against
696
+ the given object, which may be a class or an instance
697
+ where attributes will be looked up. Defaults to the
698
+ the C{object} parameter. May be set to None explicitly,
699
+ in which case spec checking is disabled. Checks may
700
+ also be disabled explicitly on a per-event basis with
701
+ the L{nospec()} method.
702
+ @param type: If set, the Mock's __class__ attribute will return
703
+ the given type. This will make C{isinstance()} calls
704
+ on the object work. Defaults to the type of the
705
+ C{object} parameter. May be set to None explicitly.
706
+ @param name: Name for the mock object, used in the representation of
707
+ expressions. The name is rarely needed, as it's usually
708
+ guessed correctly from the variable name used.
709
+ @param count: If set to false, expressions may be executed any number
710
+ of times, unless an expectation is explicitly set using
711
+ the L{count()} method. By default, expressions are
712
+ expected once.
713
+ @param passthrough: If set to False, passthrough of actions on the
714
+ proxy to the real object will only happen when
715
+ explicitly requested via the L{passthrough()}
716
+ method.
717
+ """
718
+ if isinstance(object, str): # todo: what did basestring do here?
719
+ if name is None:
720
+ name = object
721
+ import_stack = object.split(".")
722
+ attr_stack = []
723
+ while import_stack:
724
+ module_path = ".".join(import_stack)
725
+ try:
726
+ __import__(module_path)
727
+ except ImportError:
728
+ attr_stack.insert(0, import_stack.pop())
729
+ if not import_stack:
730
+ raise
731
+ continue
732
+ else:
733
+ object = sys.modules[module_path]
734
+ for attr in attr_stack:
735
+ object = getattr(object, attr)
736
+ break
737
+ if isinstance(object, types.UnboundMethodType):
738
+ object = object.__func__
739
+ if spec is True:
740
+ spec = object
741
+ if type is True:
742
+ type = __builtin__.type(object)
743
+ return Mock(self, spec=spec, type=type, object=object,
744
+ name=name, count=count, passthrough=passthrough)
745
+
746
+ def replace(self, object, spec=True, type=True, name=None, count=True,
747
+ passthrough=True):
748
+ """Create a proxy, and replace the original object with the mock.
749
+
750
+ On replay, the original object will be replaced by the returned
751
+ proxy in all dictionaries found in the running interpreter via
752
+ the garbage collecting system. This should cover module
753
+ namespaces, class namespaces, instance namespaces, and so on.
754
+
755
+ @param object: Real object to be proxied, and replaced by the mock
756
+ on replay mode. It may also be an "import path",
757
+ such as C{"time.time"}, in which case the object
758
+ will be the C{time} function from the C{time} module.
759
+ @param spec: Method calls will be checked for correctness against
760
+ the given object, which may be a class or an instance
761
+ where attributes will be looked up. Defaults to the
762
+ the C{object} parameter. May be set to None explicitly,
763
+ in which case spec checking is disabled. Checks may
764
+ also be disabled explicitly on a per-event basis with
765
+ the L{nospec()} method.
766
+ @param type: If set, the Mock's __class__ attribute will return
767
+ the given type. This will make C{isinstance()} calls
768
+ on the object work. Defaults to the type of the
769
+ C{object} parameter. May be set to None explicitly.
770
+ @param name: Name for the mock object, used in the representation of
771
+ expressions. The name is rarely needed, as it's usually
772
+ guessed correctly from the variable name used.
773
+ @param passthrough: If set to False, passthrough of actions on the
774
+ proxy to the real object will only happen when
775
+ explicitly requested via the L{passthrough()}
776
+ method.
777
+ """
778
+ mock = self.proxy(object, spec, type, name, count, passthrough)
779
+ event = self._get_replay_restore_event()
780
+ event.add_task(ProxyReplacer(mock))
781
+ return mock
782
+
783
+ def patch(self, object, spec=True):
784
+ """Patch an existing object to reproduce recorded events.
785
+
786
+ @param object: Class or instance to be patched.
787
+ @param spec: Method calls will be checked for correctness against
788
+ the given object, which may be a class or an instance
789
+ where attributes will be looked up. Defaults to the
790
+ the C{object} parameter. May be set to None explicitly,
791
+ in which case spec checking is disabled. Checks may
792
+ also be disabled explicitly on a per-event basis with
793
+ the L{nospec()} method.
794
+
795
+ The result of this method is still a mock object, which can be
796
+ used like any other mock object to record events. The difference
797
+ is that when the mocker is put on replay mode, the *real* object
798
+ will be modified to behave according to recorded expectations.
799
+
800
+ Patching works in individual instances, and also in classes.
801
+ When an instance is patched, recorded events will only be
802
+ considered on this specific instance, and other instances should
803
+ behave normally. When a class is patched, the reproduction of
804
+ events will be considered on any instance of this class once
805
+ created (collectively).
806
+
807
+ Observe that, unlike with proxies which catch only events done
808
+ through the mock object, *all* accesses to recorded expectations
809
+ will be considered; even these coming from the object itself
810
+ (e.g. C{self.hello()} is considered if this method was patched).
811
+ While this is a very powerful feature, and many times the reason
812
+ to use patches in the first place, it's important to keep this
813
+ behavior in mind.
814
+
815
+ Patching of the original object only takes place when the mocker
816
+ is put on replay mode, and the patched object will be restored
817
+ to its original state once the L{restore()} method is called
818
+ (explicitly, or implicitly with alternative conventions, such as
819
+ a C{with mocker:} block, or a MockerTestCase class).
820
+ """
821
+ if spec is True:
822
+ spec = object
823
+ patcher = Patcher()
824
+ event = self._get_replay_restore_event()
825
+ event.add_task(patcher)
826
+ mock = Mock(self, object=object, patcher=patcher,
827
+ passthrough=True, spec=spec)
828
+ patcher.patch_attr(object, '__mocker_mock__', mock)
829
+ return mock
830
+
831
+ def act(self, path):
832
+ """This is called by mock objects whenever something happens to them.
833
+
834
+ This method is part of the interface between the mocker
835
+ and mock objects.
836
+ """
837
+ if self._recording:
838
+ event = self.add_event(Event(path))
839
+ for recorder in self._recorders:
840
+ recorder(self, event)
841
+ return Mock(self, path)
842
+ else:
843
+ # First run events that may run, then run unsatisfied events, then
844
+ # ones not previously run. We put the index in the ordering tuple
845
+ # instead of the actual event because we want a stable sort
846
+ # (ordering between 2 events is undefined).
847
+ events = self._events
848
+ order = [(events[i].satisfied()*2 + events[i].has_run(), i)
849
+ for i in range(len(events))]
850
+ order.sort()
851
+ postponed = None
852
+ for weight, i in order:
853
+ event = events[i]
854
+ if event.matches(path):
855
+ if event.may_run(path):
856
+ return event.run(path)
857
+ elif postponed is None:
858
+ postponed = event
859
+ if postponed is not None:
860
+ return postponed.run(path)
861
+ raise MatchError(ERROR_PREFIX + "Unexpected expression: %s" % path)
862
+
863
+ def get_recorders(cls, self):
864
+ """Return recorders associated with this mocker class or instance.
865
+
866
+ This method may be called on mocker instances and also on mocker
867
+ classes. See the L{add_recorder()} method for more information.
868
+ """
869
+ return (self or cls)._recorders[:]
870
+ get_recorders = classinstancemethod(get_recorders)
871
+
872
+ def add_recorder(cls, self, recorder):
873
+ """Add a recorder to this mocker class or instance.
874
+
875
+ @param recorder: Callable accepting C{(mocker, event)} as parameters.
876
+
877
+ This is part of the implementation of mocker.
878
+
879
+ All registered recorders are called for translating events that
880
+ happen during recording into expectations to be met once the state
881
+ is switched to replay mode.
882
+
883
+ This method may be called on mocker instances and also on mocker
884
+ classes. When called on a class, the recorder will be used by
885
+ all instances, and also inherited on subclassing. When called on
886
+ instances, the recorder is added only to the given instance.
887
+ """
888
+ (self or cls)._recorders.append(recorder)
889
+ return recorder
890
+ add_recorder = classinstancemethod(add_recorder)
891
+
892
+ def remove_recorder(cls, self, recorder):
893
+ """Remove the given recorder from this mocker class or instance.
894
+
895
+ This method may be called on mocker classes and also on mocker
896
+ instances. See the L{add_recorder()} method for more information.
897
+ """
898
+ (self or cls)._recorders.remove(recorder)
899
+ remove_recorder = classinstancemethod(remove_recorder)
900
+
901
+ def result(self, value):
902
+ """Make the last recorded event return the given value on replay.
903
+
904
+ @param value: Object to be returned when the event is replayed.
905
+ """
906
+ self.call(lambda *args, **kwargs: value)
907
+
908
+ def generate(self, sequence):
909
+ """Last recorded event will return a generator with the given sequence.
910
+
911
+ @param sequence: Sequence of values to be generated.
912
+ """
913
+ def generate(*args, **kwargs):
914
+ for value in sequence:
915
+ yield value
916
+ self.call(generate)
917
+
918
+ def throw(self, exception):
919
+ """Make the last recorded event raise the given exception on replay.
920
+
921
+ @param exception: Class or instance of exception to be raised.
922
+ """
923
+ def raise_exception(*args, **kwargs):
924
+ raise exception
925
+ self.call(raise_exception)
926
+
927
+ def call(self, func, with_object=False):
928
+ """Make the last recorded event cause the given function to be called.
929
+
930
+ @param func: Function to be called.
931
+ @param with_object: If True, the called function will receive the
932
+ patched or proxied object so that its state may be used or verified
933
+ in checks.
934
+
935
+ The result of the function will be used as the event result.
936
+ """
937
+ event = self._events[-1]
938
+ if with_object and event.path.root_object is None:
939
+ raise TypeError("Mock object isn't a proxy")
940
+ event.add_task(FunctionRunner(func, with_root_object=with_object))
941
+
942
+ def count(self, min, max=False):
943
+ """Last recorded event must be replayed between min and max times.
944
+
945
+ @param min: Minimum number of times that the event must happen.
946
+ @param max: Maximum number of times that the event must happen. If
947
+ not given, it defaults to the same value of the C{min}
948
+ parameter. If set to None, there is no upper limit, and
949
+ the expectation is met as long as it happens at least
950
+ C{min} times.
951
+ """
952
+ event = self._events[-1]
953
+ for task in event.get_tasks():
954
+ if isinstance(task, RunCounter):
955
+ event.remove_task(task)
956
+ event.prepend_task(RunCounter(min, max))
957
+
958
+ def is_ordering(self):
959
+ """Return true if all events are being ordered.
960
+
961
+ See the L{order()} method.
962
+ """
963
+ return self._ordering
964
+
965
+ def unorder(self):
966
+ """Disable the ordered mode.
967
+
968
+ See the L{order()} method for more information.
969
+ """
970
+ self._ordering = False
971
+ self._last_orderer = None
972
+
973
+ def order(self, *path_holders):
974
+ """Create an expectation of order between two or more events.
975
+
976
+ @param path_holders: Objects returned as the result of recorded events.
977
+
978
+ By default, mocker won't force events to happen precisely in
979
+ the order they were recorded. Calling this method will change
980
+ this behavior so that events will only match if reproduced in
981
+ the correct order.
982
+
983
+ There are two ways in which this method may be used. Which one
984
+ is used in a given occasion depends only on convenience.
985
+
986
+ If no arguments are passed, the mocker will be put in a mode where
987
+ all the recorded events following the method call will only be met
988
+ if they happen in order. When that's used, the mocker may be put
989
+ back in unordered mode by calling the L{unorder()} method, or by
990
+ using a 'with' block, like so::
991
+
992
+ with mocker.ordered():
993
+ <record events>
994
+
995
+ In this case, only expressions in <record events> will be ordered,
996
+ and the mocker will be back in unordered mode after the 'with' block.
997
+
998
+ The second way to use it is by specifying precisely which events
999
+ should be ordered. As an example::
1000
+
1001
+ mock = mocker.mock()
1002
+ expr1 = mock.hello()
1003
+ expr2 = mock.world
1004
+ expr3 = mock.x.y.z
1005
+ mocker.order(expr1, expr2, expr3)
1006
+
1007
+ This method of ordering only works when the expression returns
1008
+ another object.
1009
+
1010
+ Also check the L{after()} and L{before()} methods, which are
1011
+ alternative ways to perform this.
1012
+ """
1013
+ if not path_holders:
1014
+ self._ordering = True
1015
+ return OrderedContext(self)
1016
+
1017
+ last_orderer = None
1018
+ for path_holder in path_holders:
1019
+ if type(path_holder) is Path:
1020
+ path = path_holder
1021
+ else:
1022
+ path = path_holder.__mocker_path__
1023
+ for event in self._events:
1024
+ if event.path is path:
1025
+ for task in event.get_tasks():
1026
+ if isinstance(task, Orderer):
1027
+ orderer = task
1028
+ break
1029
+ else:
1030
+ orderer = Orderer(path)
1031
+ event.add_task(orderer)
1032
+ if last_orderer:
1033
+ orderer.add_dependency(last_orderer)
1034
+ last_orderer = orderer
1035
+ break
1036
+
1037
+ def after(self, *path_holders):
1038
+ """Last recorded event must happen after events referred to.
1039
+
1040
+ @param path_holders: Objects returned as the result of recorded events
1041
+ which should happen before the last recorded event
1042
+
1043
+ As an example, the idiom::
1044
+
1045
+ expect(mock.x).after(mock.y, mock.z)
1046
+
1047
+ is an alternative way to say::
1048
+
1049
+ expr_x = mock.x
1050
+ expr_y = mock.y
1051
+ expr_z = mock.z
1052
+ mocker.order(expr_y, expr_x)
1053
+ mocker.order(expr_z, expr_x)
1054
+
1055
+ See L{order()} for more information.
1056
+ """
1057
+ last_path = self._events[-1].path
1058
+ for path_holder in path_holders:
1059
+ self.order(path_holder, last_path)
1060
+
1061
+ def before(self, *path_holders):
1062
+ """Last recorded event must happen before events referred to.
1063
+
1064
+ @param path_holders: Objects returned as the result of recorded events
1065
+ which should happen after the last recorded event
1066
+
1067
+ As an example, the idiom::
1068
+
1069
+ expect(mock.x).before(mock.y, mock.z)
1070
+
1071
+ is an alternative way to say::
1072
+
1073
+ expr_x = mock.x
1074
+ expr_y = mock.y
1075
+ expr_z = mock.z
1076
+ mocker.order(expr_x, expr_y)
1077
+ mocker.order(expr_x, expr_z)
1078
+
1079
+ See L{order()} for more information.
1080
+ """
1081
+ last_path = self._events[-1].path
1082
+ for path_holder in path_holders:
1083
+ self.order(last_path, path_holder)
1084
+
1085
+ def nospec(self):
1086
+ """Don't check method specification of real object on last event.
1087
+
1088
+ By default, when using a mock created as the result of a call to
1089
+ L{proxy()}, L{replace()}, and C{patch()}, or when passing the spec
1090
+ attribute to the L{mock()} method, method calls on the given object
1091
+ are checked for correctness against the specification of the real
1092
+ object (or the explicitly provided spec).
1093
+
1094
+ This method will disable that check specifically for the last
1095
+ recorded event.
1096
+ """
1097
+ event = self._events[-1]
1098
+ for task in event.get_tasks():
1099
+ if isinstance(task, SpecChecker):
1100
+ event.remove_task(task)
1101
+
1102
+ def passthrough(self, result_callback=None):
1103
+ """Make the last recorded event run on the real object once seen.
1104
+
1105
+ @param result_callback: If given, this function will be called with
1106
+ the result of the *real* method call as the only argument.
1107
+
1108
+ This can only be used on proxies, as returned by the L{proxy()}
1109
+ and L{replace()} methods, or on mocks representing patched objects,
1110
+ as returned by the L{patch()} method.
1111
+ """
1112
+ event = self._events[-1]
1113
+ if event.path.root_object is None:
1114
+ raise TypeError("Mock object isn't a proxy")
1115
+ event.add_task(PathExecuter(result_callback))
1116
+
1117
+ def __enter__(self):
1118
+ """Enter in a 'with' context. This will run replay()."""
1119
+ self.replay()
1120
+ return self
1121
+
1122
+ def __exit__(self, type, value, traceback):
1123
+ """Exit from a 'with' context.
1124
+
1125
+ This will run restore() at all times, but will only run verify()
1126
+ if the 'with' block itself hasn't raised an exception. Exceptions
1127
+ in that block are never swallowed.
1128
+ """
1129
+ self.restore()
1130
+ if type is None:
1131
+ self.verify()
1132
+ return False
1133
+
1134
+ def _get_replay_restore_event(self):
1135
+ """Return unique L{ReplayRestoreEvent}, creating if needed.
1136
+
1137
+ Some tasks only want to replay/restore. When that's the case,
1138
+ they shouldn't act on other events during replay. Also, they
1139
+ can all be put in a single event when that's the case. Thus,
1140
+ we add a single L{ReplayRestoreEvent} as the first element of
1141
+ the list.
1142
+ """
1143
+ if not self._events or isinstance(self._events[0], ReplayRestoreEvent):
1144
+ self._events.insert(0, ReplayRestoreEvent())
1145
+ return self._events[0]
1146
+
1147
+
1148
+ class OrderedContext(object):
1149
+
1150
+ def __init__(self, mocker):
1151
+ self._mocker = mocker
1152
+
1153
+ def __enter__(self):
1154
+ return None
1155
+
1156
+ def __exit__(self, type, value, traceback):
1157
+ self._mocker.unorder()
1158
+
1159
+
1160
+ class Mocker(MockerBase):
1161
+ __doc__ = MockerBase.__doc__
1162
+
1163
+
1164
+ # Decorator to add recorders on the standard Mocker class.
1165
+ recorder = Mocker.add_recorder
1166
+
1167
+
1168
+ # --------------------------------------------------------------------
1169
+ # Mock object.
1170
+
1171
+ class Mock(object):
1172
+
1173
+ def __init__(self, mocker, path=None, name=None, spec=None, type=None,
1174
+ object=None, passthrough=False, patcher=None, count=True):
1175
+ self.__mocker__ = mocker
1176
+ self.__mocker_path__ = path or Path(self, object)
1177
+ self.__mocker_name__ = name
1178
+ self.__mocker_spec__ = spec
1179
+ self.__mocker_object__ = object
1180
+ self.__mocker_passthrough__ = passthrough
1181
+ self.__mocker_patcher__ = patcher
1182
+ self.__mocker_replace__ = False
1183
+ self.__mocker_type__ = type
1184
+ self.__mocker_count__ = count
1185
+
1186
+ def __mocker_act__(self, kind, args=(), kwargs={}, object=None):
1187
+ if self.__mocker_name__ is None:
1188
+ self.__mocker_name__ = find_object_name(self, 2)
1189
+ action = Action(kind, args, kwargs, self.__mocker_path__)
1190
+ path = self.__mocker_path__ + action
1191
+ if object is not None:
1192
+ path.root_object = object
1193
+ try:
1194
+ return self.__mocker__.act(path)
1195
+ except MatchError as exception:
1196
+ root_mock = path.root_mock
1197
+ if (path.root_object is not None and
1198
+ root_mock.__mocker_passthrough__):
1199
+ return path.execute(path.root_object)
1200
+ # Reinstantiate to show raise statement on traceback, and
1201
+ # also to make the traceback shown shorter.
1202
+ raise MatchError(str(exception))
1203
+ except AssertionError as e:
1204
+ lines = str(e).splitlines()
1205
+ message = [ERROR_PREFIX + "Unmet expectation:", ""]
1206
+ message.append("=> " + lines.pop(0))
1207
+ message.extend([" " + line for line in lines])
1208
+ message.append("")
1209
+ raise AssertionError(os.linesep.join(message))
1210
+
1211
+ def __getattribute__(self, name):
1212
+ if name.startswith("__mocker_"):
1213
+ return super(Mock, self).__getattribute__(name)
1214
+ if name == "__class__":
1215
+ if self.__mocker__.is_recording() or self.__mocker_type__ is None:
1216
+ return type(self)
1217
+ return self.__mocker_type__
1218
+ if name == "__length_hint__":
1219
+ # This is used by Python 2.6+ to optimize the allocation
1220
+ # of arrays in certain cases. Pretend it doesn't exist.
1221
+ raise AttributeError("No __length_hint__ here!")
1222
+ return self.__mocker_act__("getattr", (name,))
1223
+
1224
+ def __setattr__(self, name, value):
1225
+ if name.startswith("__mocker_"):
1226
+ return super(Mock, self).__setattr__(name, value)
1227
+ return self.__mocker_act__("setattr", (name, value))
1228
+
1229
+ def __delattr__(self, name):
1230
+ return self.__mocker_act__("delattr", (name,))
1231
+
1232
+ def __call__(self, *args, **kwargs):
1233
+ return self.__mocker_act__("call", args, kwargs)
1234
+
1235
+ def __contains__(self, value):
1236
+ return self.__mocker_act__("contains", (value,))
1237
+
1238
+ def __getitem__(self, key):
1239
+ return self.__mocker_act__("getitem", (key,))
1240
+
1241
+ def __setitem__(self, key, value):
1242
+ return self.__mocker_act__("setitem", (key, value))
1243
+
1244
+ def __delitem__(self, key):
1245
+ return self.__mocker_act__("delitem", (key,))
1246
+
1247
+ def __len__(self):
1248
+ # MatchError is turned on an AttributeError so that list() and
1249
+ # friends act properly when trying to get length hints on
1250
+ # something that doesn't offer them.
1251
+ try:
1252
+ result = self.__mocker_act__("len")
1253
+ except MatchError as e:
1254
+ raise AttributeError(str(e))
1255
+ if type(result) is Mock:
1256
+ return 0
1257
+ return result
1258
+
1259
+ def __nonzero__(self):
1260
+ try:
1261
+ result = self.__mocker_act__("nonzero")
1262
+ except MatchError:
1263
+ return True
1264
+ if type(result) is Mock:
1265
+ return True
1266
+ return result
1267
+
1268
+ def __iter__(self):
1269
+ # XXX On py3k, when next() becomes __next__(), we'll be able
1270
+ # to return the mock itself because it will be considered
1271
+ # an iterator (we'll be mocking __next__ as well, which we
1272
+ # can't now).
1273
+ result = self.__mocker_act__("iter")
1274
+ if type(result) is Mock:
1275
+ return iter([])
1276
+ return result
1277
+
1278
+ # When adding a new action kind here, also add support for it on
1279
+ # Action.execute() and Path.__str__().
1280
+
1281
+
1282
+ def find_object_name(obj, depth=0):
1283
+ """Try to detect how the object is named on a previous scope."""
1284
+ try:
1285
+ frame = sys._getframe(depth+1)
1286
+ except Exception:
1287
+ return None
1288
+ for name, frame_obj in frame.f_locals.items():
1289
+ if frame_obj is obj:
1290
+ return name
1291
+ self = frame.f_locals.get("self")
1292
+ if self is not None:
1293
+ try:
1294
+ items = list(self.__dict__.items())
1295
+ except Exception:
1296
+ pass
1297
+ else:
1298
+ for name, self_obj in items:
1299
+ if self_obj is obj:
1300
+ return name
1301
+ return None
1302
+
1303
+
1304
+ # --------------------------------------------------------------------
1305
+ # Action and path.
1306
+
1307
+ class Action(object):
1308
+
1309
+ def __init__(self, kind, args, kwargs, path=None):
1310
+ self.kind = kind
1311
+ self.args = args
1312
+ self.kwargs = kwargs
1313
+ self.path = path
1314
+ self._execute_cache = {}
1315
+
1316
+ def __repr__(self):
1317
+ if self.path is None:
1318
+ return "Action(%r, %r, %r)" % (self.kind, self.args, self.kwargs)
1319
+ return "Action(%r, %r, %r, %r)" % \
1320
+ (self.kind, self.args, self.kwargs, self.path)
1321
+
1322
+ def __eq__(self, other):
1323
+ return (self.kind == other.kind and
1324
+ self.args == other.args and
1325
+ self.kwargs == other.kwargs)
1326
+
1327
+ def __ne__(self, other):
1328
+ return not self.__eq__(other)
1329
+
1330
+ def matches(self, other):
1331
+ return (self.kind == other.kind and
1332
+ match_params(self.args, self.kwargs, other.args, other.kwargs))
1333
+
1334
+ def execute(self, object):
1335
+ # This caching scheme may fail if the object gets deallocated before
1336
+ # the action, as the id might get reused. It's somewhat easy to fix
1337
+ # that with a weakref callback. For our uses, though, the object
1338
+ # should never get deallocated before the action itself, so we'll
1339
+ # just keep it simple.
1340
+ if id(object) in self._execute_cache:
1341
+ return self._execute_cache[id(object)]
1342
+ execute = getattr(object, "__mocker_execute__", None)
1343
+ if execute is not None:
1344
+ result = execute(self, object)
1345
+ else:
1346
+ kind = self.kind
1347
+ if kind == "getattr":
1348
+ result = getattr(object, self.args[0])
1349
+ elif kind == "setattr":
1350
+ result = setattr(object, self.args[0], self.args[1])
1351
+ elif kind == "delattr":
1352
+ result = delattr(object, self.args[0])
1353
+ elif kind == "call":
1354
+ result = object(*self.args, **self.kwargs)
1355
+ elif kind == "contains":
1356
+ result = self.args[0] in object
1357
+ elif kind == "getitem":
1358
+ result = object[self.args[0]]
1359
+ elif kind == "setitem":
1360
+ result = object[self.args[0]] = self.args[1]
1361
+ elif kind == "delitem":
1362
+ del object[self.args[0]]
1363
+ result = None
1364
+ elif kind == "len":
1365
+ result = len(object)
1366
+ elif kind == "nonzero":
1367
+ result = bool(object)
1368
+ elif kind == "iter":
1369
+ result = iter(object)
1370
+ else:
1371
+ raise RuntimeError("Don't know how to execute %r kind." % kind)
1372
+ self._execute_cache[id(object)] = result
1373
+ return result
1374
+
1375
+
1376
+ class Path(object):
1377
+
1378
+ def __init__(self, root_mock, root_object=None, actions=()):
1379
+ self.root_mock = root_mock
1380
+ self.root_object = root_object
1381
+ self.actions = tuple(actions)
1382
+ self.__mocker_replace__ = False
1383
+
1384
+ def parent_path(self):
1385
+ if not self.actions:
1386
+ return None
1387
+ return self.actions[-1].path
1388
+ parent_path = property(parent_path)
1389
+
1390
+ def __add__(self, action):
1391
+ """Return a new path which includes the given action at the end."""
1392
+ return self.__class__(self.root_mock, self.root_object,
1393
+ self.actions + (action,))
1394
+
1395
+ def __eq__(self, other):
1396
+ """Verify if the two paths are equal.
1397
+
1398
+ Two paths are equal if they refer to the same mock object, and
1399
+ have the actions with equal kind, args and kwargs.
1400
+ """
1401
+ if (self.root_mock is not other.root_mock or
1402
+ self.root_object is not other.root_object or
1403
+ len(self.actions) != len(other.actions)):
1404
+ return False
1405
+ for action, other_action in zip(self.actions, other.actions):
1406
+ if action != other_action:
1407
+ return False
1408
+ return True
1409
+
1410
+ def matches(self, other):
1411
+ """Verify if the two paths are equivalent.
1412
+
1413
+ Two paths are equal if they refer to the same mock object, and
1414
+ have the same actions performed on them.
1415
+ """
1416
+ if (self.root_mock is not other.root_mock or
1417
+ len(self.actions) != len(other.actions)):
1418
+ return False
1419
+ for action, other_action in zip(self.actions, other.actions):
1420
+ if not action.matches(other_action):
1421
+ return False
1422
+ return True
1423
+
1424
+ def execute(self, object):
1425
+ """Execute all actions sequentially on object, and return result.
1426
+ """
1427
+ for action in self.actions:
1428
+ object = action.execute(object)
1429
+ return object
1430
+
1431
+ def __str__(self):
1432
+ """Transform the path into a nice string such as obj.x.y('z')."""
1433
+ result = self.root_mock.__mocker_name__ or "<mock>"
1434
+ for action in self.actions:
1435
+ if action.kind == "getattr":
1436
+ result = "%s.%s" % (result, action.args[0])
1437
+ elif action.kind == "setattr":
1438
+ result = "%s.%s = %r" % (result, action.args[0], action.args[1])
1439
+ elif action.kind == "delattr":
1440
+ result = "del %s.%s" % (result, action.args[0])
1441
+ elif action.kind == "call":
1442
+ args = [repr(x) for x in action.args]
1443
+ items = list(action.kwargs.items())
1444
+ items.sort()
1445
+ for pair in items:
1446
+ args.append("%s=%r" % pair)
1447
+ result = "%s(%s)" % (result, ", ".join(args))
1448
+ elif action.kind == "contains":
1449
+ result = "%r in %s" % (action.args[0], result)
1450
+ elif action.kind == "getitem":
1451
+ result = "%s[%r]" % (result, action.args[0])
1452
+ elif action.kind == "setitem":
1453
+ result = "%s[%r] = %r" % (result, action.args[0],
1454
+ action.args[1])
1455
+ elif action.kind == "delitem":
1456
+ result = "del %s[%r]" % (result, action.args[0])
1457
+ elif action.kind == "len":
1458
+ result = "len(%s)" % result
1459
+ elif action.kind == "nonzero":
1460
+ result = "bool(%s)" % result
1461
+ elif action.kind == "iter":
1462
+ result = "iter(%s)" % result
1463
+ else:
1464
+ raise RuntimeError("Don't know how to format kind %r" %
1465
+ action.kind)
1466
+ return result
1467
+
1468
+
1469
+ class SpecialArgument(object):
1470
+ """Base for special arguments for matching parameters."""
1471
+
1472
+ def __init__(self, object=None):
1473
+ self.object = object
1474
+
1475
+ def __repr__(self):
1476
+ if self.object is None:
1477
+ return self.__class__.__name__
1478
+ else:
1479
+ return "%s(%r)" % (self.__class__.__name__, self.object)
1480
+
1481
+ def matches(self, other):
1482
+ return True
1483
+
1484
+ def __eq__(self, other):
1485
+ return isinstance(other, type(self)) and self.object == other.object
1486
+
1487
+
1488
+ class ANY(SpecialArgument):
1489
+ """Matches any single argument."""
1490
+
1491
+
1492
+ ANY = ANY()
1493
+
1494
+
1495
+ class ARGS(SpecialArgument):
1496
+ """Matches zero or more positional arguments."""
1497
+
1498
+
1499
+ ARGS = ARGS()
1500
+
1501
+
1502
+ class KWARGS(SpecialArgument):
1503
+ """Matches zero or more keyword arguments."""
1504
+
1505
+
1506
+ KWARGS = KWARGS()
1507
+
1508
+
1509
+ class IS(SpecialArgument):
1510
+
1511
+ def matches(self, other):
1512
+ return self.object is other
1513
+
1514
+ def __eq__(self, other):
1515
+ return isinstance(other, type(self)) and self.object is other.object
1516
+
1517
+
1518
+ class CONTAINS(SpecialArgument):
1519
+
1520
+ def matches(self, other):
1521
+ try:
1522
+ other.__contains__
1523
+ except AttributeError:
1524
+ try:
1525
+ iter(other)
1526
+ except TypeError:
1527
+ # If an object can't be iterated, and has no __contains__
1528
+ # hook, it'd blow up on the test below. We test this in
1529
+ # advance to prevent catching more errors than we really
1530
+ # want.
1531
+ return False
1532
+ return self.object in other
1533
+
1534
+
1535
+ class IN(SpecialArgument):
1536
+
1537
+ def matches(self, other):
1538
+ return other in self.object
1539
+
1540
+
1541
+ class MATCH(SpecialArgument):
1542
+
1543
+ def matches(self, other):
1544
+ return bool(self.object(other))
1545
+
1546
+ def __eq__(self, other):
1547
+ return isinstance(other, type(self)) and self.object is other.object
1548
+
1549
+
1550
+ def match_params(args1, kwargs1, args2, kwargs2):
1551
+ """Match the two sets of parameters, considering special parameters."""
1552
+
1553
+ has_args = ARGS in args1
1554
+ has_kwargs = KWARGS in args1
1555
+
1556
+ if has_kwargs:
1557
+ args1 = [arg1 for arg1 in args1 if arg1 is not KWARGS]
1558
+ elif len(kwargs1) != len(kwargs2):
1559
+ return False
1560
+
1561
+ if not has_args and len(args1) != len(args2):
1562
+ return False
1563
+
1564
+ # Either we have the same number of kwargs, or unknown keywords are
1565
+ # accepted (KWARGS was used), so check just the ones in kwargs1.
1566
+ for key, arg1 in kwargs1.items():
1567
+ if key not in kwargs2:
1568
+ return False
1569
+ arg2 = kwargs2[key]
1570
+ if isinstance(arg1, SpecialArgument):
1571
+ if not arg1.matches(arg2):
1572
+ return False
1573
+ elif arg1 != arg2:
1574
+ return False
1575
+
1576
+ # Keywords match. Now either we have the same number of
1577
+ # arguments, or ARGS was used. If ARGS wasn't used, arguments
1578
+ # must match one-on-one necessarily.
1579
+ if not has_args:
1580
+ for arg1, arg2 in zip(args1, args2):
1581
+ if isinstance(arg1, SpecialArgument):
1582
+ if not arg1.matches(arg2):
1583
+ return False
1584
+ elif arg1 != arg2:
1585
+ return False
1586
+ return True
1587
+
1588
+ # Easy choice. Keywords are matching, and anything on args is accepted.
1589
+ if (ARGS,) == args1:
1590
+ return True
1591
+
1592
+ # We have something different there. If we don't have positional
1593
+ # arguments on the original call, it can't match.
1594
+ if not args2:
1595
+ # Unless we have just several ARGS (which is bizarre, but..).
1596
+ for arg1 in args1:
1597
+ if arg1 is not ARGS:
1598
+ return False
1599
+ return True
1600
+
1601
+ # Ok, all bets are lost. We have to actually do the more expensive
1602
+ # matching. This is an algorithm based on the idea of the Levenshtein
1603
+ # Distance between two strings, but heavily hacked for this purpose.
1604
+ args2l = len(args2)
1605
+ if args1[0] is ARGS:
1606
+ args1 = args1[1:]
1607
+ array = [0]*args2l
1608
+ else:
1609
+ array = [1]*args2l
1610
+ for i in range(len(args1)):
1611
+ last = array[0]
1612
+ if args1[i] is ARGS:
1613
+ for j in range(1, args2l):
1614
+ last, array[j] = array[j], min(array[j-1], array[j], last)
1615
+ else:
1616
+ array[0] = i or int(args1[i] != args2[0])
1617
+ for j in range(1, args2l):
1618
+ last, array[j] = array[j], last or int(args1[i] != args2[j])
1619
+ if 0 not in array:
1620
+ return False
1621
+ if array[-1] != 0:
1622
+ return False
1623
+ return True
1624
+
1625
+
1626
+ # --------------------------------------------------------------------
1627
+ # Event and task base.
1628
+
1629
+ class Event(object):
1630
+ """Aggregation of tasks that keep track of a recorded action.
1631
+
1632
+ An event represents something that may or may not happen while the
1633
+ mocked environment is running, such as an attribute access, or a
1634
+ method call. The event is composed of several tasks that are
1635
+ orchestrated together to create a composed meaning for the event,
1636
+ including for which actions it should be run, what happens when it
1637
+ runs, and what's the expectations about the actions run.
1638
+ """
1639
+
1640
+ def __init__(self, path=None):
1641
+ self.path = path
1642
+ self._tasks = []
1643
+ self._has_run = False
1644
+
1645
+ def add_task(self, task):
1646
+ """Add a new task to this task."""
1647
+ self._tasks.append(task)
1648
+ return task
1649
+
1650
+ def prepend_task(self, task):
1651
+ """Add a task at the front of the list."""
1652
+ self._tasks.insert(0, task)
1653
+ return task
1654
+
1655
+ def remove_task(self, task):
1656
+ self._tasks.remove(task)
1657
+
1658
+ def replace_task(self, old_task, new_task):
1659
+ """Replace old_task with new_task, in the same position."""
1660
+ for i in range(len(self._tasks)):
1661
+ if self._tasks[i] is old_task:
1662
+ self._tasks[i] = new_task
1663
+ return new_task
1664
+
1665
+ def get_tasks(self):
1666
+ return self._tasks[:]
1667
+
1668
+ def matches(self, path):
1669
+ """Return true if *all* tasks match the given path."""
1670
+ for task in self._tasks:
1671
+ if not task.matches(path):
1672
+ return False
1673
+ return bool(self._tasks)
1674
+
1675
+ def has_run(self):
1676
+ return self._has_run
1677
+
1678
+ def may_run(self, path):
1679
+ """Verify if any task would certainly raise an error if run.
1680
+
1681
+ This will call the C{may_run()} method on each task and return
1682
+ false if any of them returns false.
1683
+ """
1684
+ for task in self._tasks:
1685
+ if not task.may_run(path):
1686
+ return False
1687
+ return True
1688
+
1689
+ def run(self, path):
1690
+ """Run all tasks with the given action.
1691
+
1692
+ @param path: The path of the expression run.
1693
+
1694
+ Running an event means running all of its tasks individually and in
1695
+ order. An event should only ever be run if all of its tasks claim to
1696
+ match the given action.
1697
+
1698
+ The result of this method will be the last result of a task
1699
+ which isn't None, or None if they're all None.
1700
+ """
1701
+ self._has_run = True
1702
+ result = None
1703
+ errors = []
1704
+ for task in self._tasks:
1705
+ if not errors or not task.may_run_user_code():
1706
+ try:
1707
+ task_result = task.run(path)
1708
+ except AssertionError as e:
1709
+ error = str(e)
1710
+ if not error:
1711
+ raise RuntimeError("Empty error message from %r" % task)
1712
+ errors.append(error)
1713
+ else:
1714
+ # XXX That's actually a bit weird. What if a call() really
1715
+ # returned None? This would improperly change the semantic
1716
+ # of this process without any good reason. Test that with two
1717
+ # call()s in sequence.
1718
+ if task_result is not None:
1719
+ result = task_result
1720
+ if errors:
1721
+ message = [str(self.path)]
1722
+ if str(path) != message[0]:
1723
+ message.append("- Run: %s" % path)
1724
+ for error in errors:
1725
+ lines = error.splitlines()
1726
+ message.append("- " + lines.pop(0))
1727
+ message.extend([" " + line for line in lines])
1728
+ raise AssertionError(os.linesep.join(message))
1729
+ return result
1730
+
1731
+ def satisfied(self):
1732
+ """Return true if all tasks are satisfied.
1733
+
1734
+ Being satisfied means that there are no unmet expectations.
1735
+ """
1736
+ for task in self._tasks:
1737
+ try:
1738
+ task.verify()
1739
+ except AssertionError:
1740
+ return False
1741
+ return True
1742
+
1743
+ def verify(self):
1744
+ """Run verify on all tasks.
1745
+
1746
+ The verify method is supposed to raise an AssertionError if the
1747
+ task has unmet expectations, with a one-line explanation about
1748
+ why this item is unmet. This method should be safe to be called
1749
+ multiple times without side effects.
1750
+ """
1751
+ errors = []
1752
+ for task in self._tasks:
1753
+ try:
1754
+ task.verify()
1755
+ except AssertionError as e:
1756
+ error = str(e)
1757
+ if not error:
1758
+ raise RuntimeError("Empty error message from %r" % task)
1759
+ errors.append(error)
1760
+ if errors:
1761
+ message = [str(self.path)]
1762
+ for error in errors:
1763
+ lines = error.splitlines()
1764
+ message.append("- " + lines.pop(0))
1765
+ message.extend([" " + line for line in lines])
1766
+ raise AssertionError(os.linesep.join(message))
1767
+
1768
+ def replay(self):
1769
+ """Put all tasks in replay mode."""
1770
+ self._has_run = False
1771
+ for task in self._tasks:
1772
+ task.replay()
1773
+
1774
+ def restore(self):
1775
+ """Restore the state of all tasks."""
1776
+ for task in self._tasks:
1777
+ task.restore()
1778
+
1779
+
1780
+ class ReplayRestoreEvent(Event):
1781
+ """Helper event for tasks which need replay/restore but shouldn't match."""
1782
+
1783
+ def matches(self, path):
1784
+ return False
1785
+
1786
+
1787
+ class Task(object):
1788
+ """Element used to track one specific aspect on an event.
1789
+
1790
+ A task is responsible for adding any kind of logic to an event.
1791
+ Examples of that are counting the number of times the event was
1792
+ made, verifying parameters if any, and so on.
1793
+ """
1794
+
1795
+ def matches(self, path):
1796
+ """Return true if the task is supposed to be run for the given path.
1797
+ """
1798
+ return True
1799
+
1800
+ def may_run(self, path):
1801
+ """Return false if running this task would certainly raise an error."""
1802
+ return True
1803
+
1804
+ def may_run_user_code(self):
1805
+ """Return true if there's a chance this task may run custom code.
1806
+
1807
+ Whenever errors are detected, running user code should be avoided,
1808
+ because the situation is already known to be incorrect, and any
1809
+ errors in the user code are side effects rather than the cause.
1810
+ """
1811
+ return False
1812
+
1813
+ def run(self, path):
1814
+ """Perform the task item, considering that the given action happened.
1815
+ """
1816
+
1817
+ def verify(self):
1818
+ """Raise AssertionError if expectations for this item are unmet.
1819
+
1820
+ The verify method is supposed to raise an AssertionError if the
1821
+ task has unmet expectations, with a one-line explanation about
1822
+ why this item is unmet. This method should be safe to be called
1823
+ multiple times without side effects.
1824
+ """
1825
+
1826
+ def replay(self):
1827
+ """Put the task in replay mode.
1828
+
1829
+ Any expectations of the task should be reset.
1830
+ """
1831
+
1832
+ def restore(self):
1833
+ """Restore any environmental changes made by the task.
1834
+
1835
+ Verify should continue to work after this is called.
1836
+ """
1837
+
1838
+
1839
+ # --------------------------------------------------------------------
1840
+ # Task implementations.
1841
+
1842
+ class OnRestoreCaller(Task):
1843
+ """Call a given callback when restoring."""
1844
+
1845
+ def __init__(self, callback):
1846
+ self._callback = callback
1847
+
1848
+ def restore(self):
1849
+ self._callback()
1850
+
1851
+
1852
+ class PathMatcher(Task):
1853
+ """Match the action path against a given path."""
1854
+
1855
+ def __init__(self, path):
1856
+ self.path = path
1857
+
1858
+ def matches(self, path):
1859
+ return self.path.matches(path)
1860
+
1861
+
1862
+ def path_matcher_recorder(mocker, event):
1863
+ event.add_task(PathMatcher(event.path))
1864
+
1865
+
1866
+ Mocker.add_recorder(path_matcher_recorder)
1867
+
1868
+
1869
+ class RunCounter(Task):
1870
+ """Task which verifies if the number of runs are within given boundaries.
1871
+ """
1872
+
1873
+ def __init__(self, min, max=False):
1874
+ self.min = min
1875
+ if max is None:
1876
+ self.max = sys.maxint
1877
+ elif max is False:
1878
+ self.max = min
1879
+ else:
1880
+ self.max = max
1881
+ self._runs = 0
1882
+
1883
+ def replay(self):
1884
+ self._runs = 0
1885
+
1886
+ def may_run(self, path):
1887
+ return self._runs < self.max
1888
+
1889
+ def run(self, path):
1890
+ self._runs += 1
1891
+ if self._runs > self.max:
1892
+ self.verify()
1893
+
1894
+ def verify(self):
1895
+ if not self.min <= self._runs <= self.max:
1896
+ if self._runs < self.min:
1897
+ raise AssertionError("Performed fewer times than expected.")
1898
+ raise AssertionError("Performed more times than expected.")
1899
+
1900
+
1901
+ class ImplicitRunCounter(RunCounter):
1902
+ """RunCounter inserted by default on any event.
1903
+
1904
+ This is a way to differentiate explicitly added counters and
1905
+ implicit ones.
1906
+ """
1907
+
1908
+
1909
+ def run_counter_recorder(mocker, event):
1910
+ """Any event may be repeated once, unless disabled by default."""
1911
+ if event.path.root_mock.__mocker_count__:
1912
+ # Rather than appending the task, we prepend it so that the
1913
+ # issue is raised before any other side-effects happen.
1914
+ event.prepend_task(ImplicitRunCounter(1))
1915
+
1916
+
1917
+ Mocker.add_recorder(run_counter_recorder)
1918
+
1919
+
1920
+ def run_counter_removal_recorder(mocker, event):
1921
+ """
1922
+ Events created by getattr actions which lead to other events
1923
+ may be repeated any number of times. For that, we remove implicit
1924
+ run counters of any getattr actions leading to the current one.
1925
+ """
1926
+ parent_path = event.path.parent_path
1927
+ for event in mocker.get_events()[::-1]:
1928
+ if (event.path is parent_path and
1929
+ event.path.actions[-1].kind == "getattr"):
1930
+ for task in event.get_tasks():
1931
+ if type(task) is ImplicitRunCounter:
1932
+ event.remove_task(task)
1933
+
1934
+
1935
+ Mocker.add_recorder(run_counter_removal_recorder)
1936
+
1937
+
1938
+ class MockReturner(Task):
1939
+ """Return a mock based on the action path."""
1940
+
1941
+ def __init__(self, mocker):
1942
+ self.mocker = mocker
1943
+
1944
+ def run(self, path):
1945
+ return Mock(self.mocker, path)
1946
+
1947
+
1948
+ def mock_returner_recorder(mocker, event):
1949
+ """Events that lead to other events must return mock objects."""
1950
+ parent_path = event.path.parent_path
1951
+ for event in mocker.get_events():
1952
+ if event.path is parent_path:
1953
+ for task in event.get_tasks():
1954
+ if isinstance(task, MockReturner):
1955
+ break
1956
+ else:
1957
+ event.add_task(MockReturner(mocker))
1958
+ break
1959
+
1960
+
1961
+ Mocker.add_recorder(mock_returner_recorder)
1962
+
1963
+
1964
+ class FunctionRunner(Task):
1965
+ """Task that runs a function everything it's run.
1966
+
1967
+ Arguments of the last action in the path are passed to the function,
1968
+ and the function result is also returned.
1969
+ """
1970
+
1971
+ def __init__(self, func, with_root_object=False):
1972
+ self._func = func
1973
+ self._with_root_object = with_root_object
1974
+
1975
+ def may_run_user_code(self):
1976
+ return True
1977
+
1978
+ def run(self, path):
1979
+ action = path.actions[-1]
1980
+ if self._with_root_object:
1981
+ return self._func(path.root_object, *action.args, **action.kwargs)
1982
+ else:
1983
+ return self._func(*action.args, **action.kwargs)
1984
+
1985
+
1986
+ class PathExecuter(Task):
1987
+ """Task that executes a path in the real object, and returns the result."""
1988
+
1989
+ def __init__(self, result_callback=None):
1990
+ self._result_callback = result_callback
1991
+
1992
+ def get_result_callback(self):
1993
+ return self._result_callback
1994
+
1995
+ def run(self, path):
1996
+ result = path.execute(path.root_object)
1997
+ if self._result_callback is not None:
1998
+ self._result_callback(result)
1999
+ return result
2000
+
2001
+
2002
+ class Orderer(Task):
2003
+ """Task to establish an order relation between two events.
2004
+
2005
+ An orderer task will only match once all its dependencies have
2006
+ been run.
2007
+ """
2008
+
2009
+ def __init__(self, path):
2010
+ self.path = path
2011
+ self._run = False
2012
+ self._dependencies = []
2013
+
2014
+ def replay(self):
2015
+ self._run = False
2016
+
2017
+ def has_run(self):
2018
+ return self._run
2019
+
2020
+ def may_run(self, path):
2021
+ for dependency in self._dependencies:
2022
+ if not dependency.has_run():
2023
+ return False
2024
+ return True
2025
+
2026
+ def run(self, path):
2027
+ for dependency in self._dependencies:
2028
+ if not dependency.has_run():
2029
+ raise AssertionError("Should be after: %s" % dependency.path)
2030
+ self._run = True
2031
+
2032
+ def add_dependency(self, orderer):
2033
+ self._dependencies.append(orderer)
2034
+
2035
+ def get_dependencies(self):
2036
+ return self._dependencies
2037
+
2038
+
2039
+ class SpecChecker(Task):
2040
+ """Task to check if arguments of the last action conform to a real method.
2041
+ """
2042
+
2043
+ def __init__(self, method):
2044
+ self._method = method
2045
+ self._unsupported = False
2046
+
2047
+ if method:
2048
+ try:
2049
+ self._args, self._varargs, self._varkwargs, self._defaults = \
2050
+ inspect.getargspec(method)
2051
+ except TypeError:
2052
+ self._unsupported = True
2053
+ else:
2054
+ if self._defaults is None:
2055
+ self._defaults = ()
2056
+ if type(method) is type(self.run):
2057
+ self._args = self._args[1:]
2058
+
2059
+ def get_method(self):
2060
+ return self._method
2061
+
2062
+ def _raise(self, message):
2063
+ spec = inspect.formatargspec(self._args, self._varargs,
2064
+ self._varkwargs, self._defaults)
2065
+ raise AssertionError("Specification is %s%s: %s" %
2066
+ (self._method.__name__, spec, message))
2067
+
2068
+ def verify(self):
2069
+ if not self._method:
2070
+ raise AssertionError("Method not found in real specification")
2071
+
2072
+ def may_run(self, path):
2073
+ try:
2074
+ self.run(path)
2075
+ except AssertionError:
2076
+ return False
2077
+ return True
2078
+
2079
+ def run(self, path):
2080
+ if not self._method:
2081
+ raise AssertionError("Method not found in real specification")
2082
+ if self._unsupported:
2083
+ return # Can't check it. Happens with builtin functions. :-(
2084
+ action = path.actions[-1]
2085
+ obtained_len = len(action.args)
2086
+ obtained_kwargs = action.kwargs.copy()
2087
+ nodefaults_len = len(self._args) - len(self._defaults)
2088
+ for i, name in enumerate(self._args):
2089
+ if i < obtained_len and name in action.kwargs:
2090
+ self._raise("%r provided twice" % name)
2091
+ if (i >= obtained_len and i < nodefaults_len and
2092
+ name not in action.kwargs):
2093
+ self._raise("%r not provided" % name)
2094
+ obtained_kwargs.pop(name, None)
2095
+ if obtained_len > len(self._args) and not self._varargs:
2096
+ self._raise("too many args provided")
2097
+ if obtained_kwargs and not self._varkwargs:
2098
+ self._raise("unknown kwargs: %s" % ", ".join(obtained_kwargs))
2099
+
2100
+
2101
+ def spec_checker_recorder(mocker, event):
2102
+ spec = event.path.root_mock.__mocker_spec__
2103
+ if spec:
2104
+ actions = event.path.actions
2105
+ if len(actions) == 1:
2106
+ if actions[0].kind == "call":
2107
+ method = getattr(spec, "__call__", None)
2108
+ event.add_task(SpecChecker(method))
2109
+ elif len(actions) == 2:
2110
+ if actions[0].kind == "getattr" and actions[1].kind == "call":
2111
+ method = getattr(spec, actions[0].args[0], None)
2112
+ event.add_task(SpecChecker(method))
2113
+
2114
+
2115
+ Mocker.add_recorder(spec_checker_recorder)
2116
+
2117
+
2118
+ class ProxyReplacer(Task):
2119
+ """Task which installs and deinstalls proxy mocks.
2120
+
2121
+ This task will replace a real object by a mock in all dictionaries
2122
+ found in the running interpreter via the garbage collecting system.
2123
+ """
2124
+
2125
+ def __init__(self, mock):
2126
+ self.mock = mock
2127
+ self.__mocker_replace__ = False
2128
+
2129
+ def replay(self):
2130
+ global_replace(self.mock.__mocker_object__, self.mock)
2131
+
2132
+ def restore(self):
2133
+ global_replace(self.mock, self.mock.__mocker_object__)
2134
+
2135
+
2136
+ def global_replace(remove, install):
2137
+ """Replace object 'remove' with object 'install' on all dictionaries."""
2138
+ for referrer in gc.get_referrers(remove):
2139
+ if (type(referrer) is dict and
2140
+ referrer.get("__mocker_replace__", True)):
2141
+ for key, value in list(referrer.items()):
2142
+ if value is remove:
2143
+ referrer[key] = install
2144
+
2145
+
2146
+ class Undefined(object):
2147
+
2148
+ def __repr__(self):
2149
+ return "Undefined"
2150
+
2151
+
2152
+ Undefined = Undefined()
2153
+
2154
+
2155
+ class Patcher(Task):
2156
+
2157
+ def __init__(self):
2158
+ super(Patcher, self).__init__()
2159
+ self._monitored = {} # {kind: {id(object): object}}
2160
+ self._patched = {}
2161
+
2162
+ def is_monitoring(self, obj, kind):
2163
+ monitored = self._monitored.get(kind)
2164
+ if monitored:
2165
+ if id(obj) in monitored:
2166
+ return True
2167
+ cls = type(obj)
2168
+ if issubclass(cls, type):
2169
+ cls = obj
2170
+ bases = set([id(base) for base in cls.__mro__])
2171
+ bases.intersection_update(monitored)
2172
+ return bool(bases)
2173
+ return False
2174
+
2175
+ def monitor(self, obj, kind):
2176
+ if kind not in self._monitored:
2177
+ self._monitored[kind] = {}
2178
+ self._monitored[kind][id(obj)] = obj
2179
+
2180
+ def patch_attr(self, obj, attr, value):
2181
+ original = obj.__dict__.get(attr, Undefined)
2182
+ self._patched[id(obj), attr] = obj, attr, original
2183
+ setattr(obj, attr, value)
2184
+
2185
+ def get_unpatched_attr(self, obj, attr):
2186
+ cls = type(obj)
2187
+ if issubclass(cls, type):
2188
+ cls = obj
2189
+ result = Undefined
2190
+ for mro_cls in cls.__mro__:
2191
+ key = (id(mro_cls), attr)
2192
+ if key in self._patched:
2193
+ result = self._patched[key][2]
2194
+ if result is not Undefined:
2195
+ break
2196
+ elif attr in mro_cls.__dict__:
2197
+ result = mro_cls.__dict__.get(attr, Undefined)
2198
+ break
2199
+ if isinstance(result, object) and hasattr(type(result), "__get__"):
2200
+ if cls is obj:
2201
+ obj = None
2202
+ return result.__get__(obj, cls)
2203
+ return result
2204
+
2205
+ def _get_kind_attr(self, kind):
2206
+ if kind == "getattr":
2207
+ return "__getattribute__"
2208
+ return "__%s__" % kind
2209
+
2210
+ def replay(self):
2211
+ for kind in self._monitored:
2212
+ attr = self._get_kind_attr(kind)
2213
+ seen = set()
2214
+ for obj in self._monitored[kind].itervalues():
2215
+ cls = type(obj)
2216
+ if issubclass(cls, type):
2217
+ cls = obj
2218
+ if cls not in seen:
2219
+ seen.add(cls)
2220
+ unpatched = getattr(cls, attr, Undefined)
2221
+ self.patch_attr(cls, attr,
2222
+ PatchedMethod(kind, unpatched,
2223
+ self.is_monitoring))
2224
+ self.patch_attr(cls, "__mocker_execute__",
2225
+ self.execute)
2226
+
2227
+ def restore(self):
2228
+ for obj, attr, original in self._patched.itervalues():
2229
+ if original is Undefined:
2230
+ delattr(obj, attr)
2231
+ else:
2232
+ setattr(obj, attr, original)
2233
+ self._patched.clear()
2234
+
2235
+ def execute(self, action, object):
2236
+ attr = self._get_kind_attr(action.kind)
2237
+ unpatched = self.get_unpatched_attr(object, attr)
2238
+ try:
2239
+ return unpatched(*action.args, **action.kwargs)
2240
+ except AttributeError:
2241
+ type, value, traceback = sys.exc_info()
2242
+ if action.kind == "getattr":
2243
+ # The normal behavior of Python is to try __getattribute__,
2244
+ # and if it raises AttributeError, try __getattr__. We've
2245
+ # tried the unpatched __getattribute__ above, and we'll now
2246
+ # try __getattr__.
2247
+ try:
2248
+ __getattr__ = unpatched("__getattr__")
2249
+ except AttributeError:
2250
+ pass
2251
+ else:
2252
+ return __getattr__(*action.args, **action.kwargs)
2253
+ raise (type, value, traceback)
2254
+
2255
+
2256
+ class PatchedMethod(object):
2257
+
2258
+ def __init__(self, kind, unpatched, is_monitoring):
2259
+ self._kind = kind
2260
+ self._unpatched = unpatched
2261
+ self._is_monitoring = is_monitoring
2262
+
2263
+ def __get__(self, obj, cls=None):
2264
+ object = obj or cls
2265
+ if not self._is_monitoring(object, self._kind):
2266
+ return self._unpatched.__get__(obj, cls)
2267
+
2268
+ def method(*args, **kwargs):
2269
+ if self._kind == "getattr" and args[0].startswith("__mocker_"):
2270
+ return self._unpatched.__get__(obj, cls)(args[0])
2271
+ mock = object.__mocker_mock__
2272
+ return mock.__mocker_act__(self._kind, args, kwargs, object)
2273
+ return method
2274
+
2275
+ def __call__(self, obj, *args, **kwargs):
2276
+ # At least with __getattribute__, Python seems to use *both* the
2277
+ # descriptor API and also call the class attribute directly. It
2278
+ # looks like an interpreter bug, or at least an undocumented
2279
+ # inconsistency. Coverage tests may show this uncovered, because
2280
+ # it depends on the Python version.
2281
+ return self.__get__(obj)(*args, **kwargs)
2282
+
2283
+
2284
+ def patcher_recorder(mocker, event):
2285
+ mock = event.path.root_mock
2286
+ if mock.__mocker_patcher__ and len(event.path.actions) == 1:
2287
+ patcher = mock.__mocker_patcher__
2288
+ patcher.monitor(mock.__mocker_object__, event.path.actions[0].kind)
2289
+
2290
+
2291
+ Mocker.add_recorder(patcher_recorder)