简体   繁体   中英

testing a function which takes input from user (python)

The function below takes password from user. I need to test this using Unit testing/(mocks).

def create_auth():
    username = '{user}'.format(user=getpass.getuser())
    pwd = getpass.getpass()
    auth_string = '{username}:{pwd}'.format(username=username, pwd=pwd)
    return auth_string

i am new to python, any hint would be helpful

Thanks

Generally speaking, you should always separate user input from program / business logic .

def create_auth_interactive():
    return create_auth(getpass.getuser(), getpass.getpass())

def create_auth(user, pwd):
    username = '{user}'.format(user=user) # do you really need this line??
    auth_string = '{username}:{pwd}'.format(username=username, pwd=pwd)
    return auth_string

class TestCreateAuth(unittest.TestCase):
    def test_create_auth(self):
        self.assertEqual(create_auth('user', 'pass'), 'user:pass')

This separation makes your code more maintainable :

  • your core logic is separate from user input, so you can easily switch where that input comes from in the future (maybe you want to expose your program on a HTTP or a RPC server? Or get input from a GUI instead of a CLI). This follows the loose coupling design principle

  • You can unit test without mocking. Mocking is a very powerful technique but if you find that you're using it a lot, that's a good indication that your code is not following separation of concerns . Take a look on dependency injection

  • It's much easier to construct multiple test cases using a list of input values (but some people prefer to have multiple independent tests, check with your team/project)

Using mock.patch :

class TestCreateAuth(unittest.TestCase):
    @mock.patch('getpass.getpass')
    @mock.patch('getpass.getuser')
    def test_create_auth(self, getuser, getpw):
        getuser.return_value = 'user'
        getpw.return_value = 'pass'
        self.assertEqual(create_auth(), 'user:pass')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM