首页 > 解决方案 > 来自无“GMAIL_PASSWORD”的 Django/Selenium KeyError

问题描述

    ERROR: test_can_get_email_link_to_log_in (functional_tests.test_login.LoginTest)
----------------------------------------------------------------------
Traceback (most recent call last):
  File ".../Django/python-tdd-book/functional_tests/test_login.py", line 36, in test_can_get_email_link_to_log_in
    body = self.wait_for_email(test_email, SUBJECT)
  File ".../Django/python-tdd-book/functional_tests/test_login.py", line 72, in wait_for_email
    inbox.pass_(os.environ['GMAIL_PASSWORD'])
  File "/opt/homebrew/Cellar/python@3.9/3.9.6/Frameworks/Python.framework/Versions/3.9/lib/python3.9/os.py", line 679, in __getitem__
    raise KeyError(key) from None
KeyError: 'GMAIL_PASSWORD'

我正在关注observerthetestinggoat这本书,这本书很棒,但我无法通过这个错误,我在这里发现另一个未解决的问题完全相同,但没有解决,我尝试深入研究gmail访问文档,例如。'允许不安全的应用程序',三重检查我已经加载了环境变量,系统实际上正在工作,即发送带有正确信息的电子邮件并在单击时允许该用户登录,除了测试之外,所有的都在工作,环境变量是加载在外壳中,我正在从 ie 执行测试。echo $GMAIL_PASSWORD,我确实注意到这个状态的 python 版本是系统 python3 但是当我从我的 virtualenv 运行 which python3 它显示 virtualenv 版本时,我什至尝试重新创建我的 virtualenv,任何帮助都会很棒我已经花了一天时间解决这个错误。

from django.core import mail 
from selenium.webdriver.common.keys import Keys 
import re
import os 
import time 
import poplib 


def wait_for_email(self, test_email, subject):
    if not self.staging_server:
        email = mail.outbox[0]
        self.assertIn(test_email, email.to)
        self.assertEqual(email.subject, subject)
        return email.body

    email_id = None
    start = time.time()
    inbox = poplib.POP3_SSL('pop.gmail.com')
    try:
        inbox.user(test_email)
        inbox.pass_(os.environ['GMAIL_PASSWORD'])
        while time.time() - start < 60:
            # get 10 newest messages
            count, _ = inbox.stat()
            for i in reversed(range(max(1, count - 10), count + 1)):
                print('getting msg', i)
                _, lines, __ = inbox.retr(i)
                lines = [l.decode('utf8') for l in lines]
                print(lines)
                if f'Subject: {subject}' in lines:
                    email_id = i
                    body = '\n'.join(lines)
                    return body
            time.sleep(10)
    finally:
        if email_id:
            inbox.dele(email_id)
        inbox.quit()

标签: djangoseleniumtesting

解决方案


if os.environ['GMAIL_PASSWORD']is raise aKeyError表示GMAIL_PASSWORD当前环境中未设置环境变量。

  • 仔细检查您的 shell 环境变量。该env命令列出所有环境变量。检查拼写错误、大写/小写等。

  • 不太可能,但你也可以检查你的 python 脚本——有什么东西会从环境中删除东西del os.environ[...]吗?


推荐阅读