问题
I have an API wrapper class WfcAPI
written in Python 3 which I want to test using PyUnit.
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)
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.
How can I setup a Python functional test for actions which require a username and password?
回答1:
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.
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.
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
Then in your settings.py
:
PASSWORD = os.environ.get("PASSWORD")
USERNAME = os.environ.get("USERNAME")
来源:https://stackoverflow.com/questions/47143368/writing-a-python-functional-test-which-requires-a-username-and-password