首页 > 解决方案 > 使用 selenium / pytest 测试 Django 激活电子邮件。EMAIL_BACKEND="django.core.mail.backends.filebased.EmailBackend"

问题描述

我正在尝试编写一个函数来测试 selenium Firefox 客户端发送的激活电子邮件。激活电子邮件已成功写入“tests/test_selenium/outbox”目录下的文件,但我无法在 test_activation_mail() 方法中处理电子邮件。

Django==2.2 pytest-django==3.8.0

设置.py

EMAIL_BACKEND = 'django.core.mail.backends.filebased.EmailBackend'
EMAIL_FILE_PATH = os.path.join(BASE_DIR, "tests", "test_selenium", "outbox")

test_registration.py

import pytest, time, os
from django.core import mail
from src import settings
from yaml import safe_load
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
# firefox driver
from selenium.webdriver.firefox.options import Options
from selenium.webdriver.firefox.firefox_profile import FirefoxProfile
from selenium.webdriver.firefox.firefox_binary import FirefoxBinary

@pytest.mark.django_db(transaction=True)
class TestCreateAccount():

    t_username      = "Pesho"
    t_password      = "alabala"
    t_perm_email_1  = "pesho@example.com"
    t_perm_email_2  = "pesho@example.com"
    t_denied_email  = "pesho@gmail.com"

    def setup_method(self, method):
        # Load config and check/download browser driver
        config_file = 'tests/test_selenium/selenium_config.yml'
        with open(config_file) as ymlfile:
                cfg = safe_load(ymlfile)
        # Firefox headless option 
        options = Options()

        if cfg['HEADLESS_BROWSER']: 
            options.headless=True

        if cfg['BROWSER'].lower() == 'firefox':
            # check if driver is downloaded
            try:
                if os.path.isfile(cfg['SELENIUM_DRIVER_FF_BIN']):
                    print(f"Driver {cfg['SELENIUM_DRIVER_FF_BIN']} found")
            except Exception as e:
                raise(f'Driver not found: {e} run selenium_downloader.py first')


            self.driver = webdriver.Firefox(
                        options=options,
                        # firefox_profile = ff_profile,
                        # capabilities=firefox_capabilities,
                        # firefox_binary=binary,
                        executable_path=cfg['SELENIUM_DRIVER_FF_BIN'])
        elif cfg['BROWSER'].lower() == 'chrome':
            raise NotImplementedError


    def teardown_method(self, method):
        # time.sleep(120)
        self.driver.quit()

    def test_activation_mail(self):
        mail.outbox = []
        m = mail.get_connection(backend=settings.EMAIL_BACKEND)
        self.driver.get("http://127.0.0.1:8000/accounts/login/?next=/")
        self.driver.set_window_size(1024, 768)
        self.driver.find_element(By.LINK_TEXT, "Register").click()
        self.driver.find_element(By.ID, "id_username").click()
        self.driver.find_element(By.ID, "id_username").send_keys(self.t_username)
        self.driver.find_element(By.ID, "id_email").send_keys(self.t_perm_email_1)
        self.driver.find_element(By.ID, "id_password1").send_keys(self.t_password)
        self.driver.find_element(By.ID, "id_password2").send_keys(self.t_password)
        self.driver.find_element(By.ID, "id_password2").send_keys(Keys.ENTER)
        alert_success = WebDriverWait(self.driver, 4).until(
                EC.presence_of_element_located((By.CSS_SELECTOR, ".alert")))
        if alert_success.text == f"New account created for {self.t_username}, Please check your email and confirm registration.":
            # print(f'File name: {m._fname}')
            email = mail.outbox[0]
            assert len(mail.outbox) == 1


运行该测试:

pkill -f geckodriver ; sleep 3 ; pytest -v --ds=src.settings --pdb --pdbcls=IPython.terminal.debugger:Pdb tests/tests_selenium/test_registration.py::TestCreateAccount::test_activation_mail

以错误结尾: E IndexError: list index out of range 因为空的 mail.outbox

我在这里想念什么?

标签: djangoseleniumemailpytest

解决方案


推荐阅读