conftest.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624
  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, BankCard, WechatMiniApp, \
  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, Merchant
  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_mini_app():
  118. yield WechatMiniApp(
  119. appid = DEFAULT_WECHAT_CONFIG.appid,
  120. secret = DEFAULT_WECHAT_CONFIG.secret,
  121. mchid = DEFAULT_WECHAT_CONFIG.mchid,
  122. apikey = DEFAULT_WECHAT_CONFIG.apikey,
  123. sslCert = DEFAULT_WECHAT_CONFIG.sslCert,
  124. sslKey = DEFAULT_WECHAT_CONFIG.sslKey,
  125. manual_withdraw = DEFAULT_WECHAT_CONFIG.manual_withdraw)
  126. @pytest.fixture(scope = 'session', autouse = True)
  127. def default_wechat_payment_app():
  128. WechatPayApp.objects(appid = DEFAULT_WECHAT_CONFIG.appid, mchid = DEFAULT_WECHAT_CONFIG.mchid).delete()
  129. app = WechatPayApp(
  130. appid = DEFAULT_WECHAT_CONFIG.appid,
  131. secret = DEFAULT_WECHAT_CONFIG.secret,
  132. mchid = DEFAULT_WECHAT_CONFIG.mchid,
  133. apikey = DEFAULT_WECHAT_CONFIG.apikey,
  134. sslCert = DEFAULT_WECHAT_CONFIG.sslCert,
  135. sslKey = DEFAULT_WECHAT_CONFIG.sslKey,
  136. manual_withdraw = DEFAULT_WECHAT_CONFIG.manual_withdraw)
  137. app.save()
  138. yield app
  139. @pytest.fixture(scope = 'session', autouse = True)
  140. def default_wechat_managerial_app():
  141. yield WechatManagerApp.create(appid = DEFAULT_WECHAT_CONFIG.appid, secret = DEFAULT_WECHAT_CONFIG.secret)
  142. @pytest.fixture(scope = 'session', autouse = True)
  143. def default_wechat_user_managerial_app():
  144. yield WechatUserManagerApp.create(appid = DEFAULT_WECHAT_CONFIG.appid, secret = DEFAULT_WECHAT_CONFIG.secret)
  145. ## alipay related
  146. @pytest.fixture(scope = 'session', autouse = True)
  147. def default_alipay_payment_app():
  148. AliApp.objects(appid = DEFAULT_ALIPAY_CONFIG.appid).delete()
  149. app = AliApp(appid = DEFAULT_ALIPAY_CONFIG.appid,
  150. public_key_path = DEFAULT_ALIPAY_CONFIG.public_key_path,
  151. app_private_key_path = DEFAULT_ALIPAY_CONFIG.app_private_key_path)
  152. app.save()
  153. yield app
  154. ## Sensible Defaults
  155. @pytest.fixture(scope = 'session', autouse = True)
  156. def default_agent(default_wechat_auth_app, default_wechat_managerial_app, default_wechat_user_managerial_app,
  157. default_wechat_payment_app, default_alipay_payment_app, default_wechat_mini_app):
  158. """
  159. 需要设置一个默认的支持所有功能的代理商
  160. :return:
  161. """
  162. Agent.objects(id = DEFAULT_AGENT_ID).delete()
  163. agent = Agent(**DEFAULT_AGENT_FIXTURE) # type: Agent
  164. agent.payAppWechat = default_wechat_payment_app
  165. agent.wechatMiniApp = default_wechat_mini_app
  166. agent.wechatLoginAuthApp = default_wechat_auth_app
  167. agent.wechatUserManagerialApp = default_wechat_user_managerial_app
  168. agent.wechatDealerManagerialApp = default_wechat_managerial_app
  169. agent.payAppAli = default_alipay_payment_app
  170. agent.save()
  171. agent.payAppWechat.occupant = agent
  172. agent.payAppAli.occupant = agent
  173. agent.wechatLoginAuthApp.occupant = agent
  174. agent.wechatUserManagerialApp.occupant = agent
  175. agent.wechatDealerManagerialApp.occupant = agent
  176. yield agent
  177. @pytest.fixture(scope = 'session', autouse = True)
  178. def default_manager():
  179. # type: ()->Manager
  180. """
  181. :return:
  182. """
  183. _ = Manager.objects(id = DEFAULT_MANAGER_ID).update(upsert = True, **DEFAULT_MANAGER_FIXTURE)
  184. if _:
  185. doc = Manager.objects(id = DEFAULT_MANAGER_ID).get() # type: Manager
  186. doc.set_password(DEFAULT_MANAGER_FIXTURE['password'])
  187. yield doc
  188. else:
  189. raise FixtureCreationError('cannot create default Manager fixture, id=%s' % (str(DEFAULT_MANAGER_ID)))
  190. ### Data models
  191. @pytest.fixture(scope = 'function')
  192. def device(dealer):
  193. # type: (Any)->Device
  194. """
  195. a device dict
  196. :return:
  197. """
  198. Device.objects(id = DEVICE_ID).delete()
  199. Device.invalid_device_cache(DEVICE_FIXTURE['devNo'])
  200. _ = Device(**DEVICE_FIXTURE).save() # .cached
  201. yield _
  202. @pytest.fixture()
  203. def multiple_devices():
  204. # type: ()->List[Device]
  205. yield []
  206. @pytest.fixture(scope = 'session', autouse = True)
  207. def device_type():
  208. # type: ()->DeviceType
  209. """
  210. :return:
  211. """
  212. DeviceType.objects(id = DEVICE_TYPE_ID).delete()
  213. _ = DeviceType(**DEVICE_TYPE_FIXTURE).save()
  214. yield _
  215. @pytest.fixture(scope = 'session', autouse = True)
  216. def bankcard():
  217. # type: (*Any)->Merchant
  218. """
  219. a Dealer object
  220. :return:
  221. """
  222. BankCard.objects(id = MERCHANT_ID).delete()
  223. _ = BankCard(**BANK_CARD_FIXTURE).save()
  224. yield _
  225. @pytest.fixture(scope = 'session', autouse = True)
  226. def merchant():
  227. # type: ()->Merchant
  228. """
  229. a Dealer object
  230. :return:
  231. """
  232. Merchant.objects(id = MERCHANT_ID).delete()
  233. _ = Merchant(**MERCHANT_FIXTURE).save()
  234. yield _
  235. @pytest.fixture(scope = 'function')
  236. def source_key():
  237. # type: ()->str
  238. yield 'ledger-wechat-{}-1510834731'.format(AGENT_ID)
  239. @pytest.fixture(scope = 'function')
  240. def dealer(agent_no_customized):
  241. # type: ()->Dealer
  242. """
  243. a Dealer object
  244. :return:
  245. """
  246. Dealer.objects(id = DEALER_ID).delete()
  247. Dealer.invalid_cache(DEALER_ID)
  248. _ = Dealer(**DEALER_FIXTURE).save()
  249. _.set_password(DEALER_FIXTURE['password'])
  250. _._raw_password = DEALER_FIXTURE['raw_password']
  251. yield _
  252. @pytest.fixture(scope = 'session', autouse = True)
  253. def partner():
  254. # type: ()->Dealer
  255. """
  256. :return:
  257. """
  258. Dealer.objects(id = PARTNER_ID).delete()
  259. Dealer.invalid_cache(PARTNER_ID)
  260. _ = Dealer(**PARTNER_FIXTURE).save()
  261. _.set_password(PARTNER_FIXTURE['password'])
  262. yield _
  263. @pytest.fixture(scope = 'session', autouse = True)
  264. def sole_group():
  265. # type: ()->Group
  266. _ = Group.objects(id = GROUP_ID).update(upsert = True, **SOLE_GROUP_FIXTURE)
  267. if _:
  268. doc = Group.objects(id = GROUP_ID).get()
  269. yield doc
  270. else:
  271. raise FixtureCreationError('cannot create GROUP_ID fixture, id=%s' % (str(GROUP_ID)))
  272. @pytest.fixture(scope = 'session', autouse = True)
  273. def partner_group():
  274. # type: ()->Group
  275. _ = Group.objects(id = PARTNER_GROUP_ID).update(upsert = True, **PARTNER_GROUP_FIXTURE)
  276. if _:
  277. doc = Group.objects(id = PARTNER_GROUP_ID).get()
  278. yield doc
  279. else:
  280. raise FixtureCreationError('cannot create PARTNER_GROUP_ID fixture, id=%s' % (str(PARTNER_GROUP_ID)))
  281. @pytest.fixture(scope = 'function')
  282. def agent(wechat_auth_app, wechat_payment_app, wechat_managerial_app, wechat_user_managerial_app, alipay_payment_app, manager):
  283. # type: (WechatAuthApp, WechatPayApp, WechatManagerApp, WechatUserManagerApp, AliApp, Manager)->Agent
  284. """
  285. :return:
  286. """
  287. Agent.objects(id = AGENT_ID).delete()
  288. agent = Agent(**AGENT_FIXTURE) # type: Agent
  289. agent.payAppWechat = wechat_payment_app
  290. agent.wechatLoginAuthApp = wechat_auth_app
  291. agent.wechatUserManagerialApp = wechat_user_managerial_app
  292. agent.wechatDealerManagerialApp = wechat_managerial_app
  293. agent.payAppAli = alipay_payment_app
  294. agent.save()
  295. agent.payAppWechat.occupant = agent
  296. agent.payAppAli.occupant = agent
  297. agent.wechatLoginAuthApp.occupant = agent
  298. agent.wechatUserManagerialApp.occupant = agent
  299. agent.wechatDealerManagerialApp.occupant = agent
  300. yield agent
  301. @pytest.fixture(scope = 'function')
  302. def agent_no_customized(bankcard):
  303. # type: (*Any)->Agent
  304. """
  305. :return:
  306. """
  307. Agent.objects(id = AGENT_ID).delete()
  308. agent = Agent(**AGENT_NO_CUSTOMIZED_FIXTURE) # type: Agent
  309. agent.bankcards = [bankcard.id]
  310. agent.save()
  311. yield agent
  312. @pytest.fixture(scope = 'function')
  313. def manager():
  314. # type: ()->Manager
  315. """
  316. :return:
  317. """
  318. _ = Manager.objects(id = MANAGER_ID).update(upsert = True, **MANAGER_FIXTURE)
  319. if _:
  320. doc = Manager.objects(id = MANAGER_ID).get() # type: Manager
  321. doc.set_password(MANAGER_FIXTURE['password'])
  322. yield doc
  323. else:
  324. raise FixtureCreationError('cannot create Manager fixture, id=%s' % (str(MANAGER_ID)))
  325. @pytest.fixture(scope = 'function')
  326. def super_manager():
  327. # type: ()->SuperManager
  328. """
  329. :return:
  330. """
  331. SuperManager.objects(id = SUPER_MANAGER_ID).delete()
  332. doc = SuperManager(id = SUPER_MANAGER_ID, username = SUPER_MANAGER_FIXTURE['username']).save()
  333. doc.set_password(SUPER_MANAGER_FIXTURE['password'])
  334. yield doc
  335. @pytest.fixture(scope = 'function')
  336. def user():
  337. # type: ()->MyUser
  338. """
  339. :return:
  340. """
  341. _ = MyUser.objects(id = MY_USER_ID).update(upsert = True, **MY_USER_FIXTURE)
  342. if _:
  343. return MyUser.objects(id = MY_USER_ID).get()
  344. else:
  345. raise FixtureCreationError('cannot create MyUser fixture, id=%s' % (str(MY_USER_ID)))
  346. ### Clients
  347. @pytest.fixture(scope = 'function')
  348. def client():
  349. """A Django test client instance.
  350. :return:
  351. """
  352. skip_if_no_django()
  353. client = RequestTestClient()
  354. yield client
  355. client.logout()
  356. @pytest.fixture(scope = 'function')
  357. def wechat_client():
  358. client = WechatRequestTestClient()
  359. yield client
  360. @pytest.fixture(scope = 'function')
  361. def alipay_client():
  362. client = AlipayRequestTestClient()
  363. yield client
  364. @pytest.fixture(scope = 'function')
  365. def manager_client():
  366. """
  367. a client with manager role
  368. :return:
  369. """
  370. client = RequestTestClient()
  371. client.login_as_manager(username = MANAGER_FIXTURE['username'], password = MANAGER_FIXTURE['password'])
  372. yield client
  373. client.logout()
  374. @pytest.fixture()
  375. def super_manager_client():
  376. """
  377. :return:
  378. """
  379. client = RequestTestClient()
  380. client.login_as_super_manager(username = SUPER_MANAGER_FIXTURE['username'],
  381. password = SUPER_MANAGER_FIXTURE['password'])
  382. yield client
  383. client.logout()
  384. @pytest.fixture(scope = 'function')
  385. def dealer_client(dealer):
  386. """
  387. a client with dealer role
  388. :return:
  389. """
  390. client = RequestTestClient()
  391. client._re_login = lambda: client.login_as_dealer(username = DEALER_FIXTURE['username'],
  392. password = DEALER_FIXTURE['password'],
  393. agentId = DEALER_FIXTURE['agentId'])
  394. client._re_login()
  395. yield client
  396. client.logout()
  397. @pytest.fixture(scope = 'function')
  398. def agent_client():
  399. """
  400. a client with agent role
  401. :return:
  402. """
  403. client = RequestTestClient()
  404. client.login_as_agent(username = AGENT_FIXTURE['username'], password = AGENT_FIXTURE['password'])
  405. yield client
  406. client.logout()
  407. @pytest.fixture(scope = 'session')
  408. def default_agent_client(default_agent):
  409. """
  410. a client with agent role
  411. :return:
  412. """
  413. client = RequestTestClient()
  414. client.login_as_agent(username = DEFAULT_AGENT_FIXTURE['username'], password = DEFAULT_AGENT_FIXTURE['password'])
  415. yield client
  416. client.logout()
  417. @pytest.fixture(scope = 'function')
  418. def agent_no_customized_client(agent_no_customized):
  419. """
  420. a client with agent role
  421. :return:
  422. """
  423. client = RequestTestClient()
  424. client.login_as_agent(username = AGENT_NO_CUSTOMIZED_FIXTURE['username'],
  425. password = AGENT_NO_CUSTOMIZED_FIXTURE['password'])
  426. yield client
  427. client.logout()
  428. @pytest.fixture
  429. def wechat_user_client(user, wechat_managerial_app, wechat_payment_app, wechat_auth_app):
  430. """
  431. a client with end user model
  432. :return:
  433. """
  434. client = WechatRequestTestClient()
  435. client.login_as_endUser(openId = user.openId, groupId = user.groupId)
  436. yield client
  437. client.logout()
  438. @pytest.fixture
  439. def alipay_user_client(user):
  440. """
  441. :return:
  442. """
  443. client = AlipayRequestTestClient()
  444. client.login_as_endUser(openId = user.openId, groupId = user.groupId)
  445. yield client
  446. client.logout()
  447. # Others
  448. @pytest.fixture()
  449. def pay_after_ad():
  450. yield Advertisement(**PAY_AFTER_AD_FIXTURE)
  451. @pytest.fixture()
  452. def banner_ad():
  453. yield Advertisement(**BANNER_AD_FIXTURE)
  454. @pytest.fixture()
  455. def onsale():
  456. OnSaleRecord.objects().delete()
  457. _ = OnSale(**ON_SALE_FIXTURE).save()
  458. yield _
  459. _.delete()
  460. @pytest.fixture()
  461. def dealerWithdrawRecord():
  462. payload = generate_dict(WithdrawRecord)
  463. payload['phone'] = DEALER_FIXTURE['username']
  464. payload['name'] = DEALER_FIXTURE['nickname']
  465. payload['ownerId'] = DEALER_FIXTURE['id']
  466. payload['role'] = ROLE.dealer
  467. payload['incomeType'] = DEALER_INCOME_TYPE.DEVICE_INCOME
  468. payload['serviceFee'] = RMB('0.08')
  469. payload['amount'] = RMB('10')
  470. payload['status'] = WithdrawStatus.SUCCEEDED
  471. payload['order'] = WithdrawRecord.make_no(ROLE.dealer, DEALER_FIXTURE['id'])
  472. payload['withdrawFeeRatio'] = 8
  473. _ = WithdrawRecord(**payload).save()
  474. yield _
  475. _.delete()
  476. @pytest.fixture()
  477. def gateway_key(default_agent):
  478. return WechatPaymentGateway(default_agent.payAppWechat).gateway_key
  479. @pytest.fixture()
  480. def gateway(default_agent):
  481. return WechatPaymentGateway(default_agent.payAppWechat)