I am new to python unit testing framework and lot of confusion in mocking dependency.
I am trying to write unit tests for below member function of a class, (check_something()
):
class Validations:
def check_something(self):
abc = os.environ['PLATFORM']
xyz = Node()
no_of_nodes = len(xyz.some_type_var)
if abc != "X_PLATFORM" or no_of_nodes != 1:
raise someException()
How do we eliminate dependency ?
- Need to mock
Node()
? - How do we make sure
abc
is assigned withX_PLATFORM
? How to assign value
1
to variableno_of_nodes
? which is in turn derived fromNode()
object.class Node(object): def __init__(self): self.nodes = DEF() self.some_type_var = someclass().getType() self.localnode = os.environ['HOSTNAME'] self.peertype = self.get_peer_type() def get_peer_type(self): return node
I tried writing below unit test. I am unable to check for fail and pass condition. I am not sure whether it is correct or not.
class TestValidation(unittest.TestCase):
@mock.patch.object(Node, "get_peer_type")
@mock.patch('somefile.Node', spec=True)
def test_1(self, mock_object1, mock_object2):
os.environ['PLATFORM'] = 'X_PLATFORM'
obj = Validations()
self.assertRaises(someException, obj.check_something)
Validation class uses Node()
Class object and Node class uses some other class.
- How to make sure exception is raised or not depending on the condition?