[英]PyCharm pytest and environment variables not working
I', using Pycharm in Ubuntu using python 3.7 and 3.8, and I'm facing two problems:我,在 Ubuntu 中使用 Pycharm 使用 python 3.7 和 3.8,我面临两个问题:
If I run the test with pytest filename.py it works just fine.如果我使用 pytest filename.py 运行测试,它工作得很好。
What could be missing?可能缺少什么? From File -> Settings -> Tools -> Python Integrated Tools -> Default test runner is already set to pytest
从文件 -> 设置 -> 工具 -> Python 集成工具 -> 默认测试运行器已设置为 pytest
import os
print(os.environ.get('SECRET_KEY'))
First problem - you have a "pure Python" run configuration for api_test.py
so when you try to run this file PyCharm reuses the configuration instead of creating a new one.第一个问题 - 您有一个
api_test.py
的“纯 Python”运行配置,因此当您尝试运行此文件时 PyCharm 会重用配置而不是创建新配置。
To resolve this issue either use Run |要解决此问题,请使用Run | Run... menu and select "pytest" there - PyCharm will create a new "test" run configuration.
运行...菜单和 select “pytest” 那里 - PyCharm 将创建一个新的“测试”运行配置。
Or remove api_test
configuration from Run |或者从Run |中删除
api_test
配置Edit Configurations... so there will be nothing no re-use for PyCharm.编辑配置...因此 PyCharm 不会再使用任何东西。
The corresponding ticket in PyCharm's bug tracker https://youtrack.jetbrains.com/issue/PY-30052 Please vote for it. PyCharm 的 bug tracker https://youtrack.jetbrains.com/issue/PY-30052中对应的票请投票。
Second problem - this is the right direction but a wrong menu.第二个问题 - 这是正确的方向,但菜单错误。 You are setting the environment variable for PyCharm built-in Python Console while you need to set it for a specific run configuration.
您正在为 PyCharm 内置 Python 控制台设置环境变量,而您需要为特定的运行配置设置它。
Run |运行 | Edit Configurations... -> select the configuration used to run a script which checks the environment variable and define it there.
编辑配置... -> select 用于运行脚本的配置,该脚本检查环境变量并在那里定义它。
You can install the plugin pytest-env您可以安装插件pytest-env
(this package was last updated 4 years ago, but still gets the job done - I am using python 3.8.5 and pipenv 2020.8.13 and it works well). (这个 package 最后一次更新是在 4 年前,但仍然可以完成工作 - 我正在使用 python 3.8.5 和 pipenv 2020.8.13,它运行良好)。
and then add to your pytet.ini file the environment variables you would like to set:然后将您要设置的环境变量添加到您的pytet.ini文件中:
[pytest]
addopts = -s -v
env =
SECRET_KEY = 12345
BTW, This plugin is intended to env vars and I thing using it with secret keys is a bit of abuse, but it will get the job done.顺便说一句,这个插件旨在环境变量,我用密钥使用它有点滥用,但它会完成工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.