Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import time
- import pytest
- import threading
- import base64
- from redis import Redis
- from rq import SimpleWorker, Queue
- from dependency_injector.providers import Object, Factory
- from microrpc.exc import RPCError
- from seagull.shared.config import Config
- from seagull.shared.uri_parser import URIParser
- from seagull.tools.rpc_ext.rpc_runners.run_rpc_client import create_client
- from seagull.email_sender.app.domains.email.send_message import EmailSender
- from seagull.email_sender.app.domains.email.email_domain import EmailDomain
- from seagull.email_sender.app.rpc_server import start_server as rpc_start_server
- from seagull.email_sender import default_config
- class EmailSenderFixtures:
- """Create email sender fixtures."""
- @pytest.fixture(scope='module')
- def server_config(self):
- """Create server config."""
- config = Config().from_object(default_config)
- config.from_py_file("./test_config.py")
- config.VERBOSITY = True
- # rq and scheduler config
- rq_config = URIParser.parse_uri(config.get("RQ"))
- prefix = rq_config.special_params.get("queries_prefix")
- config.QUEUE_PREFIX = prefix
- config.REDIS_URL = rq_config.transport_path
- config.WORKER_NAME = rq_config.special_params.get("worker_name", "default")
- config.DEFAULT_RESULT_TTL = rq_config.special_params.get("result_ttl", 10)
- config.SCHEDULE_INTERVAL = rq_config.special_params.get("scheduler_interval", 5)
- config.QUERIES_NAME = [("{}_{}".format(prefix, lev) if prefix else lev)
- for lev in ("low", "medium", "high")]
- # rpc config
- rpc_config = URIParser.parse_uri(config.get("RPC"))
- config.RPC_URL = rpc_config.transport_path
- config.REDIS_SEND_CHANNEL = rpc_config.special_params.get("send",
- "email_sender_send")
- config.REDIS_RECEIVE_CHANNEL = rpc_config.special_params.get("receive",
- "email_sender_receive")
- return config
- @pytest.fixture(scope='module')
- def rpc_server(self, server_config):
- """Start RPC server."""
- worker = threading.Thread(target=rpc_start_server, args=[server_config])
- worker.daemon = True
- worker.start()
- time.sleep(1.5)
- yield True
- @pytest.fixture(scope='module')
- def rpc_server_testing(self, server_config):
- """Start RPC server."""
- server_config.TESTING = True
- worker = threading.Thread(target=rpc_start_server, args=[server_config])
- worker.daemon = True
- worker.start()
- time.sleep(1.5)
- yield True
- @pytest.fixture(scope='module')
- def client_config(self):
- """Create client config."""
- config = Config().from_object(default_config)
- config.from_py_file("./test_config.py")
- rpc_config = URIParser.parse_uri(config.get("RPC"))
- config.RPC_URL = rpc_config.transport_path
- config.REDIS_SEND_CHANNEL = rpc_config.special_params.get("receive",
- "email_sender_receive")
- config.REDIS_RECEIVE_CHANNEL = rpc_config.special_params.get("send",
- "email_sender_send")
- return config
- @pytest.fixture(scope="module")
- def rq_server(self, server_config):
- """Start RQ server."""
- connection = Redis.from_url(server_config.REDIS_URL)
- queues_dict = {level: Queue(connection=connection) for level in ("high", "medium", "low")}
- EmailDomain.DIService.rq_queues.override(Object(queues_dict))
- worker = SimpleWorker(queues_dict.values(), connection=connection)
- failed_queue = Queue('failed', connection=connection)
- return worker, failed_queue
- @pytest.fixture(scope="function")
- def mock_smtp(self, server_config):
- """Create mock of send_email function."""
- mock_result = []
- def mock_send_email(email_obj, receives, server_config):
- """Mock of smtp send_email function."""
- mock_result.append(email_obj)
- return email_obj, receives
- EmailSender.send_email = staticmethod(mock_send_email)
- mock_smtp_factory = Factory(EmailSender, config=Object(server_config))
- EmailDomain.DIService.email_sender.override(mock_smtp_factory)
- yield mock_result
- class TestEmailSenderClient(EmailSenderFixtures):
- """Test email sender method."""
- without_body_and_html = {
- "importance": "high",
- "body": None,
- "html": None,
- "sender": "manager@zakolka.net.ua",
- "receives": ["admin@zakolka.net.ua"],
- "subject": "subject",
- "send_separately": False,
- "send_at": None,
- "attachments": None
- }
- without_body = {
- "importance": "high",
- "body": None,
- "html": "<h1>Title</h1>",
- "sender": "manager@zakolka.net.ua",
- "receives": ["admin@zakolka.net.ua"],
- "subject": "subject",
- "send_separately": False,
- "send_at": None,
- "attachments": None
- }
- with_body_and_html = {
- "importance": "high",
- "body": "body",
- "html": "html",
- "sender": "manager@zakolka.net.ua",
- "receives": ["admin@zakolka.net.ua"],
- "subject": "subject",
- "send_separately": False,
- "send_at": None,
- "attachments": None
- }
- with_attachments = {
- "importance": "high",
- "body": "body",
- "html": "html",
- "sender": "manager@zakolka.net.ua",
- "receives": ["admin@zakolka.net.ua"],
- "subject": "subject",
- "send_separately": False,
- "send_at": None,
- "attachments": [{"name": "name", "body": "body"}]
- }
- with_bad_attachments = {
- "importance": "high",
- "body": "body",
- "html": "html",
- "sender": "manager@zakolka.net.ua",
- "receives": ["admin@zakolka.net.ua"],
- "subject": "subject",
- "send_separately": False,
- "send_at": None,
- "attachments": [{"bad_name": "name", "body": "body"}]
- }
- with_send_separately = {
- "importance": "high",
- "body": "body",
- "html": "html",
- "sender": "manager@zakolka.net.ua",
- "receives": ["admin@zakolka.net.ua"],
- "subject": "subject",
- "send_separately": True,
- "send_at": None,
- "attachments": None
- }
- with_bad_importance = {
- "importance": "very high",
- "body": None,
- "html": None,
- "sender": "manager@zakolka.net.ua",
- "receives": ["admin@zakolka.net.ua"],
- "subject": "subject",
- "send_separately": False,
- "send_at": None,
- "attachments": None
- }
- without_receives = {
- "importance": "high",
- "body": None,
- "html": None,
- "sender": "manager@zakolka.net.ua",
- "receives": None,
- "subject": "subject",
- "send_separately": False,
- "send_at": None,
- "attachments": None
- }
- with_cc = {
- "importance": "high",
- "body": None,
- "html": "<h1>Title</h1>",
- "sender": "manager@zakolka.net.ua",
- "cc": ["manager@zakolka.net.ua"],
- "receives": ["admin@zakolka.net.ua"],
- "subject": "subject",
- "send_separately": False,
- "send_at": None,
- "attachments": None
- }
- without_sender = {
- "importance": "high",
- "body": None,
- "html": "<h1>Title</h1>",
- "sender": None,
- "receives": ["admin@zakolka.net.ua"],
- "subject": "subject",
- "send_separately": False,
- "send_at": None,
- "attachments": None
- }
- @pytest.fixture()
- def rpc_client(self, client_config):
- """Create RPC Client."""
- return create_client(client_config, prefix="email")
- @pytest.fixture(autouse=True)
- def _mock_smtp(self, mock_smtp):
- """"""
- yield mock_smtp
- @pytest.mark.usefixtures("rpc_server")
- @pytest.mark.parametrize("message_attributes, failed", [
- (without_body_and_html, False),
- (without_body, False),
- (with_body_and_html, False),
- (with_attachments, False),
- (with_send_separately, False),
- (with_bad_attachments, True),
- ])
- def test_send_email(self, message_attributes, failed, rpc_client, rq_server):
- """Test normal email sending."""
- worker, failed_queue = rq_server
- failed_queue.empty()
- result = rpc_client.send_message(**message_attributes)
- worker.work(burst=True)
- if failed:
- assert failed_queue.count > 0
- assert all(job in failed_queue.job_ids for job in result.values())
- else:
- assert failed_queue.count == 0
- assert all(receiver in message_attributes['receives'] for receiver in result.keys())
- @pytest.mark.usefixtures("rpc_server")
- @pytest.mark.parametrize("message_attributes, error, traceback", [
- (with_bad_importance, RPCError, "Expected importance"),
- (without_receives, RPCError, "Expected receives to send message, but get empty value."),
- ])
- def test_error_raising(self, message_attributes, error, traceback, rpc_client, rq_server):
- """Test errors raising."""
- worker, _ = rq_server
- with pytest.raises(error) as excinfo:
- rpc_client.send_message(**message_attributes)
- assert traceback in excinfo.value
- worker.work(burst=True)
- @pytest.mark.usefixtures("rpc_server")
- @pytest.mark.parametrize("message_attributes", [
- with_cc
- ])
- def test_check_email_obj(self, message_attributes, _mock_smtp, rpc_client, rq_server, server_config):
- """Test email object."""
- rpc_client.send_message(**message_attributes)
- rq_server[0].work(burst=True)
- assert _mock_smtp[0]["To"] == message_attributes['receives'][0]
- assert _mock_smtp[0]["Cc"] == ", ".join(message_attributes["cc"] or
- server_config.CC_MAILS or
- message_attributes["receives"][1:])
- assert _mock_smtp[0]["From"] == message_attributes["sender"]
- assert _mock_smtp[0]["Subject"] == message_attributes["subject"]
- @pytest.mark.usefixtures("rpc_server_testing")
- @pytest.mark.parametrize("message_attributes", [
- without_sender
- ])
- def test_with_testing_config(self, message_attributes, _mock_smtp, rpc_client, rq_server, server_config):
- """Test email sending with TESTING mode."""
- rpc_client.send_message(**message_attributes)
- rq_server[0].work(burst=True)
- assert _mock_smtp[0]["To"] == server_config.TESTING_MAILS[0]
- assert _mock_smtp[0]["Cc"] == ", ".join(server_config.TESTING_MAILS[1:])
- assert _mock_smtp[0]["From"] == server_config.MAIL_DEFAULT_SENDER
- @pytest.mark.usefixtures("rpc_server")
- @pytest.mark.parametrize("message_attributes", [
- with_body_and_html
- ])
- def test_message_info(self, message_attributes, rpc_client, rq_server):
- """Test message info method."""
- result = rpc_client.send_message(**message_attributes)
- task_status_queue = rpc_client.message_info(task_code=list(result.values())[0])
- rq_server[0].work(burst=True)
- task_status_done = rpc_client.message_info(task_code=list(result.values())[0])
- assert task_status_queue == "queued"
- assert task_status_done == "unknown"
Add Comment
Please, Sign In to add comment