conftest.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585
  1. # -*- coding: utf-8 -*-
  2. # !/usr/bin/env python
  3. import atexit
  4. import os
  5. import shutil
  6. import tempfile
  7. import pytest
  8. from django.http import HttpRequest
  9. from mockredis import MockRedis
  10. from typing import List, Any
  11. from apilib.utils_json import JsonResponse
  12. from apps.web.ad.models import Advertisement
  13. from apps.web.agent.models import Agent
  14. from apps.web.common.models import WithdrawRecord, Banks
  15. from apps.web.common.transaction import WithdrawStatus
  16. from apps.web.core import ROLE
  17. from apps.web.core.models import WechatAuthApp, WechatPayApp, AliApp, WechatManagerApp, \
  18. WechatUserManagerApp
  19. from apps.web.core.payment.wechat import WechatPaymentGateway
  20. from apps.web.dealer.define import DEALER_INCOME_TYPE
  21. from apps.web.dealer.models import Dealer, OnSale, OnSaleRecord
  22. from apps.web.device.models import Device, Group, DeviceType
  23. from apps.web.management.models import Manager
  24. from apps.web.superadmin.models import SuperManager
  25. from apps.web.user.models import MyUser
  26. from testcase.providers import generate_dict
  27. from .base import skip_if_no_django, RequestTestClient, WechatRequestTestClient, AlipayRequestTestClient
  28. from .common import *
  29. HOME_URL = 'http://127.0.0.1:8080/'
  30. URLS = {
  31. "dealer": {
  32. "login": "app/service/dealerLogin"
  33. }
  34. }
  35. ### Exceptions
  36. class FixtureCreationError(Exception):
  37. pass
  38. ### Resources
  39. @atexit.register
  40. def delete_all_data():
  41. pass
  42. @pytest.fixture
  43. def temp_dir():
  44. dir_path = tempfile.mkdtemp()
  45. yield dir_path
  46. shutil.rmtree(dir_path)
  47. @pytest.fixture(scope = 'session')
  48. def celery_config():
  49. return {
  50. 'broker_url': 'amqp://',
  51. 'result_backend': 'redis://'
  52. }
  53. @pytest.fixture(scope = 'function')
  54. def credentials(request):
  55. import simplejson as json
  56. path = os.path.join(request.node.fspath.dirpath().join('..').strpath, 'data', 'credentials.json')
  57. with open(path, 'r') as f:
  58. return json.load(f)
  59. @pytest.fixture(scope = 'session')
  60. def mocked_redis():
  61. """
  62. mocked redis-py client
  63. :return:
  64. """
  65. return MockRedis()
  66. @pytest.fixture
  67. def http_request():
  68. """
  69. mocked django HttpRequest
  70. :return:
  71. """
  72. return HttpRequest()
  73. @pytest.fixture(scope = 'session')
  74. def http_json_response(dict_):
  75. """
  76. mocked django JsonResponse
  77. :param dict_:
  78. :return:
  79. """
  80. return JsonResponse(dict_)
  81. ## wechat related
  82. @pytest.fixture(scope = 'function')
  83. def wechat_auth_app():
  84. yield WechatAuthApp(appid = WECHAT_CONFIG.appid, secret = WECHAT_CONFIG.secret)
  85. @pytest.fixture(scope = 'function')
  86. def wechat_payment_app():
  87. WechatPayApp.objects(appid = WECHAT_CONFIG.appid, mchid = WECHAT_CONFIG.mchid).delete()
  88. app = WechatPayApp(
  89. appid = WECHAT_CONFIG.appid,
  90. secret = WECHAT_CONFIG.secret,
  91. mchid = WECHAT_CONFIG.mchid,
  92. apikey = WECHAT_CONFIG.apikey,
  93. sslCert = WECHAT_CONFIG.sslCert,
  94. sslKey = WECHAT_CONFIG.sslKey,
  95. manual_withdraw = WECHAT_CONFIG.manual_withdraw)
  96. app.save()
  97. yield app
  98. @pytest.fixture(scope = 'function')
  99. def wechat_managerial_app():
  100. yield WechatManagerApp.create(appid = WECHAT_CONFIG.appid, secret = WECHAT_CONFIG.secret)
  101. @pytest.fixture(scope = 'function')
  102. def wechat_user_managerial_app():
  103. yield WechatUserManagerApp.create(appid = WECHAT_CONFIG.appid, secret = WECHAT_CONFIG.secret)
  104. ## alipay related
  105. @pytest.fixture(scope = 'function')
  106. def alipay_payment_app():
  107. AliApp.objects(appid = ALIPAY_CONFIG.appid).delete()
  108. app = AliApp(appid = ALIPAY_CONFIG.appid,
  109. public_key_path = ALIPAY_CONFIG.alipayPublicKey,
  110. app_private_key_path = ALIPAY_CONFIG.appPrivateKey)
  111. app.save()
  112. yield app
  113. @pytest.fixture(scope = 'session', autouse = True)
  114. def default_wechat_auth_app():
  115. yield WechatAuthApp(appid = DEFAULT_WECHAT_CONFIG.appid, secret = DEFAULT_WECHAT_CONFIG.secret)
  116. @pytest.fixture(scope = 'session', autouse = True)
  117. def default_wechat_payment_app():
  118. WechatPayApp.objects(appid = DEFAULT_WECHAT_CONFIG.appid, mchid = DEFAULT_WECHAT_CONFIG.mchid).delete()
  119. app = WechatPayApp(
  120. appid = DEFAULT_WECHAT_CONFIG.appid,
  121. secret = DEFAULT_WECHAT_CONFIG.secret,
  122. mchid = DEFAULT_WECHAT_CONFIG.mchid,
  123. apikey = DEFAULT_WECHAT_CONFIG.apikey,
  124. sslCert = DEFAULT_WECHAT_CONFIG.sslCert,
  125. sslKey = DEFAULT_WECHAT_CONFIG.sslKey,
  126. manual_withdraw = DEFAULT_WECHAT_CONFIG.manual_withdraw)
  127. app.save()
  128. yield app
  129. @pytest.fixture(scope = 'session', autouse = True)
  130. def default_wechat_managerial_app():
  131. yield WechatManagerApp.create(appid = DEFAULT_WECHAT_CONFIG.appid, secret = DEFAULT_WECHAT_CONFIG.secret)
  132. @pytest.fixture(scope = 'session', autouse = True)
  133. def default_wechat_user_managerial_app():
  134. yield WechatUserManagerApp.create(appid = DEFAULT_WECHAT_CONFIG.appid, secret = DEFAULT_WECHAT_CONFIG.secret)
  135. ## alipay related
  136. @pytest.fixture(scope = 'session', autouse = True)
  137. def default_alipay_payment_app():
  138. AliApp.objects(appid = DEFAULT_ALIPAY_CONFIG.appid).delete()
  139. app = AliApp(appid = DEFAULT_ALIPAY_CONFIG.appid,
  140. public_key_path = DEFAULT_ALIPAY_CONFIG.public_key_path,
  141. app_private_key_path = DEFAULT_ALIPAY_CONFIG.app_private_key_path)
  142. app.save()
  143. yield app
  144. ## Sensible Defaults
  145. @pytest.fixture(scope = 'session', autouse = True)
  146. def default_agent(default_wechat_auth_app, default_wechat_managerial_app, default_wechat_user_managerial_app,
  147. default_wechat_payment_app, default_alipay_payment_app, default_wechat_mini_app):
  148. """
  149. 需要设置一个默认的支持所有功能的代理商
  150. :return:
  151. """
  152. Agent.objects(id = DEFAULT_AGENT_ID).delete()
  153. agent = Agent(**DEFAULT_AGENT_FIXTURE) # type: Agent
  154. agent.payAppWechat = default_wechat_payment_app
  155. agent.wechatLoginAuthApp = default_wechat_auth_app
  156. agent.wechatUserManagerialApp = default_wechat_user_managerial_app
  157. agent.wechatDealerManagerialApp = default_wechat_managerial_app
  158. agent.payAppAli = default_alipay_payment_app
  159. agent.save()
  160. agent.payAppWechat.occupant = agent
  161. agent.payAppAli.occupant = agent
  162. agent.wechatLoginAuthApp.occupant = agent
  163. agent.wechatUserManagerialApp.occupant = agent
  164. agent.wechatDealerManagerialApp.occupant = agent
  165. yield agent
  166. @pytest.fixture(scope = 'session', autouse = True)
  167. def default_manager():
  168. # type: ()->Manager
  169. """
  170. :return:
  171. """
  172. _ = Manager.objects(id = DEFAULT_MANAGER_ID).update(upsert = True, **DEFAULT_MANAGER_FIXTURE)
  173. if _:
  174. doc = Manager.objects(id = DEFAULT_MANAGER_ID).get() # type: Manager
  175. doc.set_password(DEFAULT_MANAGER_FIXTURE['password'])
  176. yield doc
  177. else:
  178. raise FixtureCreationError('cannot create default Manager fixture, id=%s' % (str(DEFAULT_MANAGER_ID)))
  179. ### Data models
  180. @pytest.fixture(scope = 'function')
  181. def device(dealer):
  182. # type: (Any)->Device
  183. """
  184. a device dict
  185. :return:
  186. """
  187. Device.objects(id = DEVICE_ID).delete()
  188. Device.invalid_device_cache(DEVICE_FIXTURE['devNo'])
  189. _ = Device(**DEVICE_FIXTURE).save() # .cached
  190. yield _
  191. @pytest.fixture()
  192. def multiple_devices():
  193. # type: ()->List[Device]
  194. yield []
  195. @pytest.fixture(scope = 'session', autouse = True)
  196. def device_type():
  197. # type: ()->DeviceType
  198. """
  199. :return:
  200. """
  201. DeviceType.objects(id = DEVICE_TYPE_ID).delete()
  202. _ = DeviceType(**DEVICE_TYPE_FIXTURE).save()
  203. yield _
  204. @pytest.fixture(scope = 'function')
  205. def source_key():
  206. # type: ()->str
  207. yield 'ledger-wechat-{}-1510834731'.format(AGENT_ID)
  208. @pytest.fixture(scope = 'function')
  209. def dealer(agent_no_customized):
  210. # type: ()->Dealer
  211. """
  212. a Dealer object
  213. :return:
  214. """
  215. Dealer.objects(id = DEALER_ID).delete()
  216. Dealer.invalid_cache(DEALER_ID)
  217. _ = Dealer(**DEALER_FIXTURE).save()
  218. _.set_password(DEALER_FIXTURE['password'])
  219. _._raw_password = DEALER_FIXTURE['raw_password']
  220. yield _
  221. @pytest.fixture(scope = 'session', autouse = True)
  222. def partner():
  223. # type: ()->Dealer
  224. """
  225. :return:
  226. """
  227. Dealer.objects(id = PARTNER_ID).delete()
  228. Dealer.invalid_cache(PARTNER_ID)
  229. _ = Dealer(**PARTNER_FIXTURE).save()
  230. _.set_password(PARTNER_FIXTURE['password'])
  231. yield _
  232. @pytest.fixture(scope = 'session', autouse = True)
  233. def sole_group():
  234. # type: ()->Group
  235. _ = Group.objects(id = GROUP_ID).update(upsert = True, **SOLE_GROUP_FIXTURE)
  236. if _:
  237. doc = Group.objects(id = GROUP_ID).get()
  238. yield doc
  239. else:
  240. raise FixtureCreationError('cannot create GROUP_ID fixture, id=%s' % (str(GROUP_ID)))
  241. @pytest.fixture(scope = 'session', autouse = True)
  242. def partner_group():
  243. # type: ()->Group
  244. _ = Group.objects(id = PARTNER_GROUP_ID).update(upsert = True, **PARTNER_GROUP_FIXTURE)
  245. if _:
  246. doc = Group.objects(id = PARTNER_GROUP_ID).get()
  247. yield doc
  248. else:
  249. raise FixtureCreationError('cannot create PARTNER_GROUP_ID fixture, id=%s' % (str(PARTNER_GROUP_ID)))
  250. @pytest.fixture(scope = 'function')
  251. def agent(wechat_auth_app, wechat_payment_app, wechat_managerial_app, wechat_user_managerial_app, alipay_payment_app, manager):
  252. # type: (WechatAuthApp, WechatPayApp, WechatManagerApp, WechatUserManagerApp, AliApp, Manager)->Agent
  253. """
  254. :return:
  255. """
  256. Agent.objects(id = AGENT_ID).delete()
  257. agent = Agent(**AGENT_FIXTURE) # type: Agent
  258. agent.payAppWechat = wechat_payment_app
  259. agent.wechatLoginAuthApp = wechat_auth_app
  260. agent.wechatUserManagerialApp = wechat_user_managerial_app
  261. agent.wechatDealerManagerialApp = wechat_managerial_app
  262. agent.payAppAli = alipay_payment_app
  263. agent.save()
  264. agent.payAppWechat.occupant = agent
  265. agent.payAppAli.occupant = agent
  266. agent.wechatLoginAuthApp.occupant = agent
  267. agent.wechatUserManagerialApp.occupant = agent
  268. agent.wechatDealerManagerialApp.occupant = agent
  269. yield agent
  270. @pytest.fixture(scope = 'function')
  271. def agent_no_customized(bankcard):
  272. # type: (*Any)->Agent
  273. """
  274. :return:
  275. """
  276. Agent.objects(id = AGENT_ID).delete()
  277. agent = Agent(**AGENT_NO_CUSTOMIZED_FIXTURE) # type: Agent
  278. agent.save()
  279. yield agent
  280. @pytest.fixture(scope = 'function')
  281. def manager():
  282. # type: ()->Manager
  283. """
  284. :return:
  285. """
  286. _ = Manager.objects(id = MANAGER_ID).update(upsert = True, **MANAGER_FIXTURE)
  287. if _:
  288. doc = Manager.objects(id = MANAGER_ID).get() # type: Manager
  289. doc.set_password(MANAGER_FIXTURE['password'])
  290. yield doc
  291. else:
  292. raise FixtureCreationError('cannot create Manager fixture, id=%s' % (str(MANAGER_ID)))
  293. @pytest.fixture(scope = 'function')
  294. def super_manager():
  295. # type: ()->SuperManager
  296. """
  297. :return:
  298. """
  299. SuperManager.objects(id = SUPER_MANAGER_ID).delete()
  300. doc = SuperManager(id = SUPER_MANAGER_ID, username = SUPER_MANAGER_FIXTURE['username']).save()
  301. doc.set_password(SUPER_MANAGER_FIXTURE['password'])
  302. yield doc
  303. @pytest.fixture(scope = 'function')
  304. def user():
  305. # type: ()->MyUser
  306. """
  307. :return:
  308. """
  309. _ = MyUser.objects(id = MY_USER_ID).update(upsert = True, **MY_USER_FIXTURE)
  310. if _:
  311. return MyUser.objects(id = MY_USER_ID).get()
  312. else:
  313. raise FixtureCreationError('cannot create MyUser fixture, id=%s' % (str(MY_USER_ID)))
  314. ### Clients
  315. @pytest.fixture(scope = 'function')
  316. def client():
  317. """A Django test client instance.
  318. :return:
  319. """
  320. skip_if_no_django()
  321. client = RequestTestClient()
  322. yield client
  323. client.logout()
  324. @pytest.fixture(scope = 'function')
  325. def wechat_client():
  326. client = WechatRequestTestClient()
  327. yield client
  328. @pytest.fixture(scope = 'function')
  329. def alipay_client():
  330. client = AlipayRequestTestClient()
  331. yield client
  332. @pytest.fixture(scope = 'function')
  333. def manager_client():
  334. """
  335. a client with manager role
  336. :return:
  337. """
  338. client = RequestTestClient()
  339. client.login_as_manager(username = MANAGER_FIXTURE['username'], password = MANAGER_FIXTURE['password'])
  340. yield client
  341. client.logout()
  342. @pytest.fixture()
  343. def super_manager_client():
  344. """
  345. :return:
  346. """
  347. client = RequestTestClient()
  348. client.login_as_super_manager(username = SUPER_MANAGER_FIXTURE['username'],
  349. password = SUPER_MANAGER_FIXTURE['password'])
  350. yield client
  351. client.logout()
  352. @pytest.fixture(scope = 'function')
  353. def dealer_client(dealer):
  354. """
  355. a client with dealer role
  356. :return:
  357. """
  358. client = RequestTestClient()
  359. client._re_login = lambda: client.login_as_dealer(username = DEALER_FIXTURE['username'],
  360. password = DEALER_FIXTURE['password'],
  361. agentId = DEALER_FIXTURE['agentId'])
  362. client._re_login()
  363. yield client
  364. client.logout()
  365. @pytest.fixture(scope = 'function')
  366. def agent_client():
  367. """
  368. a client with agent role
  369. :return:
  370. """
  371. client = RequestTestClient()
  372. client.login_as_agent(username = AGENT_FIXTURE['username'], password = AGENT_FIXTURE['password'])
  373. yield client
  374. client.logout()
  375. @pytest.fixture(scope = 'session')
  376. def default_agent_client(default_agent):
  377. """
  378. a client with agent role
  379. :return:
  380. """
  381. client = RequestTestClient()
  382. client.login_as_agent(username = DEFAULT_AGENT_FIXTURE['username'], password = DEFAULT_AGENT_FIXTURE['password'])
  383. yield client
  384. client.logout()
  385. @pytest.fixture(scope = 'function')
  386. def agent_no_customized_client(agent_no_customized):
  387. """
  388. a client with agent role
  389. :return:
  390. """
  391. client = RequestTestClient()
  392. client.login_as_agent(username = AGENT_NO_CUSTOMIZED_FIXTURE['username'],
  393. password = AGENT_NO_CUSTOMIZED_FIXTURE['password'])
  394. yield client
  395. client.logout()
  396. @pytest.fixture
  397. def wechat_user_client(user, wechat_managerial_app, wechat_payment_app, wechat_auth_app):
  398. """
  399. a client with end user model
  400. :return:
  401. """
  402. client = WechatRequestTestClient()
  403. client.login_as_endUser(openId = user.openId, groupId = user.groupId)
  404. yield client
  405. client.logout()
  406. @pytest.fixture
  407. def alipay_user_client(user):
  408. """
  409. :return:
  410. """
  411. client = AlipayRequestTestClient()
  412. client.login_as_endUser(openId = user.openId, groupId = user.groupId)
  413. yield client
  414. client.logout()
  415. # Others
  416. @pytest.fixture()
  417. def pay_after_ad():
  418. yield Advertisement(**PAY_AFTER_AD_FIXTURE)
  419. @pytest.fixture()
  420. def banner_ad():
  421. yield Advertisement(**BANNER_AD_FIXTURE)
  422. @pytest.fixture()
  423. def onsale():
  424. OnSaleRecord.objects().delete()
  425. _ = OnSale(**ON_SALE_FIXTURE).save()
  426. yield _
  427. _.delete()
  428. @pytest.fixture()
  429. def dealerWithdrawRecord():
  430. payload = generate_dict(WithdrawRecord)
  431. payload['phone'] = DEALER_FIXTURE['username']
  432. payload['name'] = DEALER_FIXTURE['nickname']
  433. payload['ownerId'] = DEALER_FIXTURE['id']
  434. payload['role'] = ROLE.dealer
  435. payload['incomeType'] = DEALER_INCOME_TYPE.DEVICE_INCOME
  436. payload['serviceFee'] = RMB('0.08')
  437. payload['amount'] = RMB('10')
  438. payload['status'] = WithdrawStatus.SUCCEEDED
  439. payload['order'] = WithdrawRecord.make_no(ROLE.dealer, DEALER_FIXTURE['id'])
  440. payload['withdrawFeeRatio'] = 8
  441. _ = WithdrawRecord(**payload).save()
  442. yield _
  443. _.delete()
  444. @pytest.fixture()
  445. def gateway_key(default_agent):
  446. return WechatPaymentGateway(default_agent.payAppWechat).gateway_key
  447. @pytest.fixture()
  448. def gateway(default_agent):
  449. return WechatPaymentGateway(default_agent.payAppWechat)