Search code examples
pythonmockingpytestgetpass

Pytest mock hide expected password


I am testing a function that gets a login and a password from the command line. The code below works as expected:

# ---------- Function part ----------
import getpass

def my_function():
    login = input('Login: ')
    password = getpass.getpass()

    # example to simulate connection to a identification server
    if login+password == 'foobar':
        return True
    else:
        return False

# ---------- Test part ----------
from unittest.mock import patch

@patch("getpass.getpass")
@patch("builtins.input")
def test_my_function(input, getpass):
    input.return_value = 'foo'
    getpass.return_value = 'bar'
    assert my_function()

Now I would like to hide the expected password (bar) so as to publish the tests to a public repository.

I have thought about coding the getpass input, but that would lead in a connection fail. And all the other solutions I can think of expose the password more or less clearly to anyone that can read the code.

Is there a solution to store the password so that it is usable by the connection function, and it is not readable to anyone that read the sources?


Solution

  • How about make it a shell environment?

    When you want to run your test, use export PASSWORD=bar first.

    In your code, read password from os.environ['PASSWORD'].