编写需要用户名和密码的Python功能测试 [英] Writing a Python functional test which requires a username and password
问题描述
我有一个用Python 3编写的API包装类WfcAPI
,我想使用
I have an API wrapper class WfcAPI
written in Python 3 which I want to test using PyUnit.
WfcAPI
的setUpClass()
涉及登录到外部API服务器.当前的功能测试实现的密码使用Base64编码进行了模糊处理,但这与出于安全原因的理想解决方案.
The setUpClass()
for WfcAPI
involves logging in to the external API server. The current functional test implementation has the password obfuscated with Base64 encoding, but this is far from an ideal solution for security reasons.
import unittest
import base64
from pykronos import WfcAPI
class Test(unittest.TestCase):
@classmethod
def setUpClass(self):
password = base64.b64decode("U29tZVBhc3N3b3Jk").decode("utf-8")
self.kronos = WfcAPI("SomeUsername", password)
我希望能够为我的API包装程序快速运行功能测试,但是我还想确保代码中不包括我的用户名和密码.
I want to be able to quickly run functional tests for my API wrapper, but I also want to ensure that my username and password aren't included as part of the code.
如何为需要用户名和密码的操作设置Python功能测试?
推荐答案
只需澄清一下:如果它是单元测试,则不应该针对真实的外部API进行测试,而应该伪造其响应.单元测试应仅与被测对象的逻辑(WfcAPI
)有关,而与子从属无关.
Just to clarify: if it's a unit test, you shouldn't be testing against the real external API, you should Fake its response. A unit test should only be concerned with the Subject Under Test's logic (WfcAPI
) and not its sub dependences.
现在,如果您进行功能测试,将真实数据发送到API,则可以通过将凭据存储在.env
文件中来保护您的凭据,而其余代码不会提交.
Now, if you do a functional test where you send real data to the API, you can protect your credentials by storing them in an .env
file which won't be commited with the rest of the code.
此python库提供了该功能,并在其自述文件中为您提供了一个示例.您最终会遇到这样的事情:
This python library offers that functionality and gives you an example in its Readme. You'd end up with something like this:
# .env
PASSWORD=some_password
USERNAME=SomeUsername
然后在您的settings.py
中:
PASSWORD = os.environ.get("PASSWORD")
USERNAME = os.environ.get("USERNAME")
这篇关于编写需要用户名和密码的Python功能测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!