Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Unit Test with User-Entered Password

I'm trying to unit test python code which accesses a remote service. I'm using PyUnit with python 2.7.

In the setUpClass method, the code prompts the user to enter the password for the service. I want to keep everything modular, so I've created separate unit test classes for each class being tested. These classes all access the same remote service, and they all use a single definition of the setUpClass method fom a super class.

My problem is that I have to re-enter the password multiple times (once for every test class). I'm lazy. I only want to enter the password once for all unit tests. I could avoid the issue by hard-coding the password in the unit test, but that's a terrible idea. The other option is to shove everything into one massive class derived from unittest.TestCase, but I want to avoid that route because I like modularization.

Here's how the code is structured:

import unittest
from getpass import getpass

class TestCommon(unittest.TestCase):
    @classmethod
    def setUpClass(cls):
        pwd = getpass()

class test_A(TestCommon):
    # ...individual unit tests for class A

class test_B(TestCommon):
    # ...individual unit tests for class B

In this example, I would have to enter the password twice: once for class A and once for class B.

Anyone have advice on a secure way for me to do a one-time password entry right at the beginning of the unit test run? Thanks!

like image 793
RobotNerd Avatar asked Jun 28 '13 23:06

RobotNerd


1 Answers

Class definition is executed once.

import unittest
from getpass import getpass

class TestCommon(unittest.TestCase):
    pwd = getpass()

class test_A(TestCommon):
    def test_a(self):
        self.assertEqual(self.pwd, 'secret')

class test_B(TestCommon):
    def test_b(self):
        reversed_pwd = self.pwd[::-1]
        self.assertEqual(reversed_pwd, 'terces')

The password is accessible via self.pwd or TestCommon.pwd.

like image 104
falsetru Avatar answered Oct 31 '22 13:10

falsetru