Advertisement
Guest User

Untitled

a guest
Aug 11th, 2017
466
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 11.79 KB | None | 0 0
  1. import time
  2. import pytest
  3. import threading
  4. import base64
  5.  
  6. from redis import Redis
  7. from rq import SimpleWorker, Queue
  8. from dependency_injector.providers import Object, Factory
  9.  
  10. from microrpc.exc import RPCError
  11.  
  12. from seagull.shared.config import Config
  13. from seagull.shared.uri_parser import URIParser
  14. from seagull.tools.rpc_ext.rpc_runners.run_rpc_client import create_client
  15.  
  16. from seagull.email_sender.app.domains.email.send_message import EmailSender
  17. from seagull.email_sender.app.domains.email.email_domain import EmailDomain
  18. from seagull.email_sender.app.rpc_server import start_server as rpc_start_server
  19. from seagull.email_sender import default_config
  20.  
  21.  
  22. class EmailSenderFixtures:
  23. """Create email sender fixtures."""
  24.  
  25. @pytest.fixture(scope='module')
  26. def server_config(self):
  27. """Create server config."""
  28.  
  29. config = Config().from_object(default_config)
  30. config.from_py_file("./test_config.py")
  31. config.VERBOSITY = True
  32.  
  33. # rq and scheduler config
  34. rq_config = URIParser.parse_uri(config.get("RQ"))
  35. prefix = rq_config.special_params.get("queries_prefix")
  36. config.QUEUE_PREFIX = prefix
  37. config.REDIS_URL = rq_config.transport_path
  38. config.WORKER_NAME = rq_config.special_params.get("worker_name", "default")
  39. config.DEFAULT_RESULT_TTL = rq_config.special_params.get("result_ttl", 10)
  40. config.SCHEDULE_INTERVAL = rq_config.special_params.get("scheduler_interval", 5)
  41. config.QUERIES_NAME = [("{}_{}".format(prefix, lev) if prefix else lev)
  42. for lev in ("low", "medium", "high")]
  43.  
  44. # rpc config
  45. rpc_config = URIParser.parse_uri(config.get("RPC"))
  46. config.RPC_URL = rpc_config.transport_path
  47. config.REDIS_SEND_CHANNEL = rpc_config.special_params.get("send",
  48. "email_sender_send")
  49. config.REDIS_RECEIVE_CHANNEL = rpc_config.special_params.get("receive",
  50. "email_sender_receive")
  51.  
  52. return config
  53.  
  54. @pytest.fixture(scope='module')
  55. def rpc_server(self, server_config):
  56. """Start RPC server."""
  57.  
  58. worker = threading.Thread(target=rpc_start_server, args=[server_config])
  59. worker.daemon = True
  60. worker.start()
  61. time.sleep(1.5)
  62.  
  63. yield True
  64.  
  65. @pytest.fixture(scope='module')
  66. def rpc_server_testing(self, server_config):
  67. """Start RPC server."""
  68.  
  69. server_config.TESTING = True
  70. worker = threading.Thread(target=rpc_start_server, args=[server_config])
  71. worker.daemon = True
  72. worker.start()
  73. time.sleep(1.5)
  74.  
  75. yield True
  76.  
  77. @pytest.fixture(scope='module')
  78. def client_config(self):
  79. """Create client config."""
  80.  
  81. config = Config().from_object(default_config)
  82. config.from_py_file("./test_config.py")
  83.  
  84. rpc_config = URIParser.parse_uri(config.get("RPC"))
  85. config.RPC_URL = rpc_config.transport_path
  86. config.REDIS_SEND_CHANNEL = rpc_config.special_params.get("receive",
  87. "email_sender_receive")
  88. config.REDIS_RECEIVE_CHANNEL = rpc_config.special_params.get("send",
  89. "email_sender_send")
  90.  
  91. return config
  92.  
  93. @pytest.fixture(scope="module")
  94. def rq_server(self, server_config):
  95. """Start RQ server."""
  96.  
  97. connection = Redis.from_url(server_config.REDIS_URL)
  98. queues_dict = {level: Queue(connection=connection) for level in ("high", "medium", "low")}
  99. EmailDomain.DIService.rq_queues.override(Object(queues_dict))
  100. worker = SimpleWorker(queues_dict.values(), connection=connection)
  101. failed_queue = Queue('failed', connection=connection)
  102.  
  103. return worker, failed_queue
  104.  
  105. @pytest.fixture(scope="function")
  106. def mock_smtp(self, server_config):
  107. """Create mock of send_email function."""
  108.  
  109. mock_result = []
  110.  
  111. def mock_send_email(email_obj, receives, server_config):
  112. """Mock of smtp send_email function."""
  113.  
  114. mock_result.append(email_obj)
  115.  
  116. return email_obj, receives
  117.  
  118. EmailSender.send_email = staticmethod(mock_send_email)
  119. mock_smtp_factory = Factory(EmailSender, config=Object(server_config))
  120. EmailDomain.DIService.email_sender.override(mock_smtp_factory)
  121.  
  122. yield mock_result
  123.  
  124.  
  125. class TestEmailSenderClient(EmailSenderFixtures):
  126. """Test email sender method."""
  127.  
  128. without_body_and_html = {
  129. "importance": "high",
  130. "body": None,
  131. "html": None,
  132. "sender": "manager@zakolka.net.ua",
  133. "receives": ["admin@zakolka.net.ua"],
  134. "subject": "subject",
  135. "send_separately": False,
  136. "send_at": None,
  137. "attachments": None
  138. }
  139.  
  140. without_body = {
  141. "importance": "high",
  142. "body": None,
  143. "html": "<h1>Title</h1>",
  144. "sender": "manager@zakolka.net.ua",
  145. "receives": ["admin@zakolka.net.ua"],
  146. "subject": "subject",
  147. "send_separately": False,
  148. "send_at": None,
  149. "attachments": None
  150. }
  151.  
  152. with_body_and_html = {
  153. "importance": "high",
  154. "body": "body",
  155. "html": "html",
  156. "sender": "manager@zakolka.net.ua",
  157. "receives": ["admin@zakolka.net.ua"],
  158. "subject": "subject",
  159. "send_separately": False,
  160. "send_at": None,
  161. "attachments": None
  162. }
  163.  
  164. with_attachments = {
  165. "importance": "high",
  166. "body": "body",
  167. "html": "html",
  168. "sender": "manager@zakolka.net.ua",
  169. "receives": ["admin@zakolka.net.ua"],
  170. "subject": "subject",
  171. "send_separately": False,
  172. "send_at": None,
  173. "attachments": [{"name": "name", "body": "body"}]
  174. }
  175.  
  176. with_bad_attachments = {
  177. "importance": "high",
  178. "body": "body",
  179. "html": "html",
  180. "sender": "manager@zakolka.net.ua",
  181. "receives": ["admin@zakolka.net.ua"],
  182. "subject": "subject",
  183. "send_separately": False,
  184. "send_at": None,
  185. "attachments": [{"bad_name": "name", "body": "body"}]
  186. }
  187.  
  188. with_send_separately = {
  189. "importance": "high",
  190. "body": "body",
  191. "html": "html",
  192. "sender": "manager@zakolka.net.ua",
  193. "receives": ["admin@zakolka.net.ua"],
  194. "subject": "subject",
  195. "send_separately": True,
  196. "send_at": None,
  197. "attachments": None
  198. }
  199.  
  200. with_bad_importance = {
  201. "importance": "very high",
  202. "body": None,
  203. "html": None,
  204. "sender": "manager@zakolka.net.ua",
  205. "receives": ["admin@zakolka.net.ua"],
  206. "subject": "subject",
  207. "send_separately": False,
  208. "send_at": None,
  209. "attachments": None
  210. }
  211.  
  212. without_receives = {
  213. "importance": "high",
  214. "body": None,
  215. "html": None,
  216. "sender": "manager@zakolka.net.ua",
  217. "receives": None,
  218. "subject": "subject",
  219. "send_separately": False,
  220. "send_at": None,
  221. "attachments": None
  222. }
  223.  
  224. with_cc = {
  225. "importance": "high",
  226. "body": None,
  227. "html": "<h1>Title</h1>",
  228. "sender": "manager@zakolka.net.ua",
  229. "cc": ["manager@zakolka.net.ua"],
  230. "receives": ["admin@zakolka.net.ua"],
  231. "subject": "subject",
  232. "send_separately": False,
  233. "send_at": None,
  234. "attachments": None
  235.  
  236. }
  237.  
  238. without_sender = {
  239. "importance": "high",
  240. "body": None,
  241. "html": "<h1>Title</h1>",
  242. "sender": None,
  243. "receives": ["admin@zakolka.net.ua"],
  244. "subject": "subject",
  245. "send_separately": False,
  246. "send_at": None,
  247. "attachments": None
  248.  
  249. }
  250.  
  251. @pytest.fixture()
  252. def rpc_client(self, client_config):
  253. """Create RPC Client."""
  254.  
  255. return create_client(client_config, prefix="email")
  256.  
  257. @pytest.fixture(autouse=True)
  258. def _mock_smtp(self, mock_smtp):
  259. """"""
  260.  
  261. yield mock_smtp
  262.  
  263. @pytest.mark.usefixtures("rpc_server")
  264. @pytest.mark.parametrize("message_attributes, failed", [
  265. (without_body_and_html, False),
  266. (without_body, False),
  267. (with_body_and_html, False),
  268. (with_attachments, False),
  269. (with_send_separately, False),
  270. (with_bad_attachments, True),
  271. ])
  272. def test_send_email(self, message_attributes, failed, rpc_client, rq_server):
  273. """Test normal email sending."""
  274.  
  275. worker, failed_queue = rq_server
  276. failed_queue.empty()
  277.  
  278. result = rpc_client.send_message(**message_attributes)
  279. worker.work(burst=True)
  280.  
  281. if failed:
  282. assert failed_queue.count > 0
  283. assert all(job in failed_queue.job_ids for job in result.values())
  284. else:
  285. assert failed_queue.count == 0
  286. assert all(receiver in message_attributes['receives'] for receiver in result.keys())
  287.  
  288. @pytest.mark.usefixtures("rpc_server")
  289. @pytest.mark.parametrize("message_attributes, error, traceback", [
  290. (with_bad_importance, RPCError, "Expected importance"),
  291. (without_receives, RPCError, "Expected receives to send message, but get empty value."),
  292. ])
  293. def test_error_raising(self, message_attributes, error, traceback, rpc_client, rq_server):
  294. """Test errors raising."""
  295.  
  296. worker, _ = rq_server
  297. with pytest.raises(error) as excinfo:
  298. rpc_client.send_message(**message_attributes)
  299. assert traceback in excinfo.value
  300.  
  301. worker.work(burst=True)
  302.  
  303. @pytest.mark.usefixtures("rpc_server")
  304. @pytest.mark.parametrize("message_attributes", [
  305. with_cc
  306. ])
  307. def test_check_email_obj(self, message_attributes, _mock_smtp, rpc_client, rq_server, server_config):
  308. """Test email object."""
  309.  
  310. rpc_client.send_message(**message_attributes)
  311.  
  312. rq_server[0].work(burst=True)
  313.  
  314. assert _mock_smtp[0]["To"] == message_attributes['receives'][0]
  315. assert _mock_smtp[0]["Cc"] == ", ".join(message_attributes["cc"] or
  316. server_config.CC_MAILS or
  317. message_attributes["receives"][1:])
  318. assert _mock_smtp[0]["From"] == message_attributes["sender"]
  319. assert _mock_smtp[0]["Subject"] == message_attributes["subject"]
  320.  
  321. @pytest.mark.usefixtures("rpc_server_testing")
  322. @pytest.mark.parametrize("message_attributes", [
  323. without_sender
  324. ])
  325. def test_with_testing_config(self, message_attributes, _mock_smtp, rpc_client, rq_server, server_config):
  326. """Test email sending with TESTING mode."""
  327.  
  328. rpc_client.send_message(**message_attributes)
  329.  
  330. rq_server[0].work(burst=True)
  331.  
  332. assert _mock_smtp[0]["To"] == server_config.TESTING_MAILS[0]
  333. assert _mock_smtp[0]["Cc"] == ", ".join(server_config.TESTING_MAILS[1:])
  334. assert _mock_smtp[0]["From"] == server_config.MAIL_DEFAULT_SENDER
  335.  
  336. @pytest.mark.usefixtures("rpc_server")
  337. @pytest.mark.parametrize("message_attributes", [
  338. with_body_and_html
  339. ])
  340. def test_message_info(self, message_attributes, rpc_client, rq_server):
  341. """Test message info method."""
  342.  
  343. result = rpc_client.send_message(**message_attributes)
  344.  
  345. task_status_queue = rpc_client.message_info(task_code=list(result.values())[0])
  346.  
  347. rq_server[0].work(burst=True)
  348.  
  349. task_status_done = rpc_client.message_info(task_code=list(result.values())[0])
  350.  
  351. assert task_status_queue == "queued"
  352. assert task_status_done == "unknown"
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement