2022-03-18 02:03:36 +08:00
|
|
|
import email
|
2020-11-16 02:34:13 +08:00
|
|
|
import json
|
2022-03-18 02:03:36 +08:00
|
|
|
import os
|
2022-03-18 22:44:07 +08:00
|
|
|
import random
|
|
|
|
import string
|
2022-03-18 02:03:36 +08:00
|
|
|
from email.message import EmailMessage
|
2022-03-18 22:55:59 +08:00
|
|
|
from typing import Optional, Dict
|
2020-11-16 02:34:13 +08:00
|
|
|
|
2022-03-18 22:44:07 +08:00
|
|
|
import jinja2
|
2019-08-10 23:03:51 +08:00
|
|
|
from flask import url_for
|
|
|
|
|
2022-03-18 22:44:07 +08:00
|
|
|
from app.models import User, Alias
|
2019-08-10 23:03:51 +08:00
|
|
|
|
|
|
|
|
|
|
|
def login(flask_client) -> User:
|
|
|
|
# create user, user is activated
|
|
|
|
user = User.create(
|
2020-12-31 20:59:03 +08:00
|
|
|
email="a@b.c",
|
|
|
|
password="password",
|
|
|
|
name="Test User",
|
|
|
|
activated=True,
|
|
|
|
commit=True,
|
2019-08-10 23:03:51 +08:00
|
|
|
)
|
|
|
|
|
|
|
|
r = flask_client.post(
|
|
|
|
url_for("auth.login"),
|
|
|
|
data={"email": "a@b.c", "password": "password"},
|
|
|
|
follow_redirects=True,
|
|
|
|
)
|
|
|
|
|
|
|
|
assert r.status_code == 200
|
|
|
|
assert b"/auth/logout" in r.data
|
|
|
|
|
|
|
|
return user
|
2020-11-16 02:34:13 +08:00
|
|
|
|
|
|
|
|
2022-03-18 22:44:07 +08:00
|
|
|
def random_token(length: int = 10) -> str:
|
|
|
|
return "".join(random.choices(string.ascii_lowercase + string.digits, k=length))
|
|
|
|
|
|
|
|
|
|
|
|
def create_random_user() -> User:
|
|
|
|
email = "{}@{}.com".format(random_token(), random_token())
|
2021-03-02 01:45:15 +08:00
|
|
|
return User.create(
|
2022-03-18 22:44:07 +08:00
|
|
|
email=email,
|
2021-03-02 01:45:15 +08:00
|
|
|
password="password",
|
|
|
|
name="Test User",
|
|
|
|
activated=True,
|
|
|
|
commit=True,
|
|
|
|
)
|
|
|
|
|
|
|
|
|
2022-03-18 22:44:07 +08:00
|
|
|
def create_random_alias(user: User) -> Alias:
|
|
|
|
alias_email = "{}@{}.com".format(random_token(), random_token())
|
|
|
|
alias = Alias.create(
|
|
|
|
user_id=user.id,
|
|
|
|
email=alias_email,
|
|
|
|
mailbox_id=user.default_mailbox_id,
|
|
|
|
commit=True,
|
|
|
|
)
|
|
|
|
return alias
|
|
|
|
|
|
|
|
|
2020-11-16 02:34:13 +08:00
|
|
|
def pretty(d):
|
|
|
|
"""pretty print as json"""
|
|
|
|
print(json.dumps(d, indent=2))
|
2022-03-18 02:03:36 +08:00
|
|
|
|
|
|
|
|
2022-03-18 22:55:59 +08:00
|
|
|
def load_eml_file(
|
|
|
|
filename: str, template_values: Optional[Dict[str, str]] = None
|
|
|
|
) -> EmailMessage:
|
2022-03-18 04:36:25 +08:00
|
|
|
emails_dir = os.path.join(
|
|
|
|
os.path.dirname(os.path.realpath(__file__)), "example_emls"
|
|
|
|
)
|
2022-03-18 02:03:36 +08:00
|
|
|
fullpath = os.path.join(emails_dir, filename)
|
2022-03-18 22:44:07 +08:00
|
|
|
template = jinja2.Template(open(fullpath).read())
|
2022-03-18 22:55:59 +08:00
|
|
|
if not template_values:
|
|
|
|
template_values = {}
|
2022-03-18 22:44:07 +08:00
|
|
|
rendered = template.render(**template_values)
|
|
|
|
return email.message_from_string(rendered)
|