app/tests/utils.py
Adrià Casajús 44e0dd8635
Break using an alias as a mailbox loop in the email_handler.py (#1624)
* Do not allow to use email alias as account email when linking

* Add missing status

* Remove TODO

* Also break contact as email loop

* Better test names

* Allow a reverse alias to send an email to an alias

* Ident fix

* Removed invalid test

---------

Co-authored-by: Adrià Casajús <adria.casajus@proton.ch>
2023-03-13 13:01:00 +01:00

78 lines
1.8 KiB
Python

import email
import json
import os
import random
import string
from email.message import EmailMessage
from typing import Optional, Dict
import jinja2
from flask import url_for
from app.models import User
from app.utils import random_string
def create_new_user(email: Optional[str] = None, name: Optional[str] = None) -> User:
if not email:
email = f"user_{random_token(10)}@mailbox.test"
if not name:
name = "Test User"
# new user has a different email address
user = User.create(
email=email,
password="password",
name=name,
activated=True,
flush=True,
)
return user
def login(flask_client, user: Optional[User] = None) -> User:
if not user:
user = create_new_user()
r = flask_client.post(
url_for("auth.login"),
data={"email": user.email, "password": "password"},
follow_redirects=True,
)
assert r.status_code == 200
assert b"/auth/logout" in r.data
return user
def random_domain() -> str:
return random_token() + ".test"
def random_token(length: int = 10) -> str:
return "".join(random.choices(string.ascii_lowercase + string.digits, k=length))
def pretty(d):
"""pretty print as json"""
print(json.dumps(d, indent=2))
def load_eml_file(
filename: str, template_values: Optional[Dict[str, str]] = None
) -> EmailMessage:
emails_dir = os.path.join(
os.path.dirname(os.path.realpath(__file__)), "example_emls"
)
fullpath = os.path.join(emails_dir, filename)
with open(fullpath) as fd:
template = jinja2.Template(fd.read())
if not template_values:
template_values = {}
rendered = template.render(**template_values)
return email.message_from_string(rendered)
def random_email() -> str:
return "{rand}@{rand}.com".format(rand=random_string(20))