mercredi 26 août 2015

Unit tests and mock objects for telnet

I would like to write unit tests for my A class. A class is utilizes telnet class (standard) and I substitute the telnet module with MockTelnet. Class A may work with various telnet hosts and outputs of these hosts are different, that's why I use different ('command':'output') dictionaries to emulate different hosts.

QUESTIONS:

  • Is my approach to mocking telnet for different hosts viable or there is a better approach?
  • How is it possible to substitute dictionaries (let's say from dictFirst to dictSecond) within a single unit test testTelnetConnection?

    import unittest
    from mock import patch
    import telnetlib
    
    
    class A:
    
        def __init__(self, ip):
            telnet = telnetlib.Telnet(ip)
            telnet.write('admin\n')
            out1 = telnet.read_until('something')
            telnet.write('password\n')
            out2 = telnet.read_until('something')
            #Do something with out1 and out2
    
        def SomeMethod(self):
            pass
    
    class MockTelnet:
    
        command = None
        dictTelnet = None
    
        def __init__(self, ip, dictTelnet):
            print 'MockTelnet.__init__: ' + ip
            self.dictTelnet = dictTelnet
    
        def write(self, text):
            print 'MockTelnet.write: ' + text
            self.command = text
    
        def read_until(self, until): 
            return self.dictTelnet[self.command]
    
    
    class ATests(unittest.TestCase):
    
        dictFirst = {'admin\n':'Asomething', 'password\n':'Bsomething'}
        dictSecond = {'admin\n':'Csomething', 'password\n':'Dsomething'}
    
        @patch('telnetlib.Telnet', return_value = MockTelnet('192.168.0.1',dictFirst))    
        def testTelnetConnection(self,telnetlib_init):
            telnet = A('192.168.0.1')
            #Need to select dictSecond for MockTelnet here
            telnet = A('192.168.0.2')
    
    if __name__ == '__main__':
        unittest.main()
    
    

Aucun commentaire:

Enregistrer un commentaire