Отправить письмо с pytest - PullRequest
0 голосов
/ 15 марта 2020

У меня есть метод, который отправляет электронное письмо, и я хочу сделать параметризованный тест pytest, но когда я запускаю свой тест, он не запускается, и в журналах он показывает no tests ran. Что не так с моим тестом?

сценарий pytest:

import pytest
import new_version


@pytest.mark.parametrize("email", ['my_email@gmail.com'])
def send_email(email):
    new_version.send_mail(email) 

метод, который отправляет электронную почту:

# Imports
import smtplib
import time

# Language
error_title = "ERROR"
send_error = "I'm waiting {idle} and I will try again."
send_error_mail = "Mail invalid"
send_error_char = "Invalid character"
send_error_connection_1_2 = "Connection problem..."
send_error_connection_2_2 = "Gmail server is down or internet connection is instabil."
login_browser = "Please log in via your web browser and then try again."
login_browser_info = "That browser and this software shood have same IP connection first time."

# Gmaild ID fro login
fromMail = "myemail@gmail.com"
fromPass = "pass"

# Some configurations
mailDelay = 15
exceptionDelay = 180


# SEND MAILS
def send_mail(email, thisSubject="Just a subject",
              thisMessage="This is just a simple message..."):
    # To ho to send mails
    mailTo = [
        email
    ]
    # If still have mails to send
    while len(mailTo) != 0:
        sendItTo = mailTo[0]  # Memorise what mail will be send it (debug purpose)
        try:
            # Connect to the server
            server = smtplib.SMTP("smtp.gmail.com:587")
            server.ehlo()
            server.starttls()

            # Sign In
            server.login(fromMail, fromPass)

            # Set the message
            message = f"Subject: {thisSubject}\n{thisMessage}"

            # Send one mail
            server.sendmail(fromMail, mailTo.pop(0), message)

            # Sign Out
            server.quit()

        # If is a problem
        except Exception as e:
            # Convert error in a string for som checks
            e = str(e)

            # Show me if...
            if "The recipient address" in e and "is not a valid" in e:
                print(f"\n>>> {send_error_mail} [//> {sendItTo}\n")
            elif "'ascii'" in e and "code can't encode characters" in e:
                print(f"\n>>> {send_error_char} [//> {sendItTo}\n")
            elif "Please" in e and "log in via your web browser" in e:
                print(f"\n>>> {login_browser}\n>>>  - {login_browser_info}")
                break
            elif "[WinError 10060]" in e:
                if "{idle}" in send_error:
                    se = send_error.split("{idle}");
                    seMsg = f"{se[0]}{exceptionDelay} sec.{se[1]}"
                else:
                    seMsg = send_error
                print(f"\n>>> {send_error_connection_1_2}\n>>> {send_error_connection_2_2}")
                print(f">>> {seMsg}\n")
                # Wait 5 minutes
                waitTime = exceptionDelay - mailDelay
                if waitTime <= 0:
                    waitTime = exceptionDelay
                time.sleep(waitTime)
            else:
                if "{idle}" in send_error:
                    se = send_error.split("{idle}");
                    seMsg = f"{se[0]}{exceptionDelay} sec.{se[1]}"
                else:
                    seMsg = send_error
                print(f">>> {error_title} <<<", e)
                print(f">>> {seMsg}\n")
                # Wait 5 minutes
                time.sleep(exceptionDelay)

        # If are still mails wait before to send another one
        if len(mailTo) != 0:
            time.sleep(mailDelay)

logs:

платформа darwin - Python 3.7.5, pytest-5.3.5, py-1.8.1, pluggy-0.13.1 - / Users / nikolai / Documents / Python / gmail / venv / bin / python cachedir: .pytest_cache rootdir: / Users / nikolai / Documents / Python / gmail собрал 0 вещей

1 Ответ

0 голосов
/ 15 марта 2020

Если вы не измените префиксы обнаружения для Pytest, тестовые функции должны иметь имя test_*:

import pytest
import new_version

@pytest.mark.parametrize("email", ['my_email@gmail.com'])
def test_send_email(email):
    new_version.send_mail(email) 
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...