Home > Enterprise >  Is it possible to unit test the parameters that I pass to the function in python?
Is it possible to unit test the parameters that I pass to the function in python?

Time:07-19

In this scenario:

In FileA:

from FileB import BJob

class EasyJob
    def __init__():
        self.job = BJob()
    
    def launch_job_in_A():
        self.job.launch_job_in_B(cpu=100, memory=200)

In FileB:

class BJob():
    def __init__():
        pass

    def launch_job_in_B(cpu=0, memory=0):
        do_some_thing(cpu, memory)
        ...

Is there a way to write a unit test for launch_job_in_A() function and also verify whether we do pass cpu=100 and memory=200 to launch_job_in_B() function successfully?

Broadly question is like, is it possible to check the parameter we passed to the function?

CodePudding user response:

You can create a Mock via unittest.mock.patch and then use the assert_called_once_with method to verify the function call:

import unittest
from unittest import TestCase
from unittest.mock import patch

from FileA import EasyJob


class TestEasyJob(TestCase):
    def test_launch_job_in_A(self):
        with patch('FileB.BJob.launch_job_in_B') as mock:
            job = EasyJob()
            job.launch_job_in_A()
        mock.assert_called_once_with(cpu=100, memory=200)


unittest.main()

CodePudding user response:

Yes, you would replace self.job with a mock object and its launch_job_in_B with a mock method.

This would be easier if there was an option to pass in the BJob, rather than hard coding it. This avoids having to mock every call to launch_job_in_B which might have unexpected side effects. This also makes the class more flexible.

from FileB import BJob

class EasyJob
    def __init__(bjob=BJob()):
        self.job = bjob
    
    def launch_job_in_A():
        self.job.launch_job_in_B(cpu=100, memory=200)

Now we can mock the method just for a single object.

from FileA import EasyJob
from FileB import BJob
from unittest.mock import MagicMock

# Set up the mocked object and method.
mock_bjob = BJob()
# If it needs to return something, configure that.
mock_bjob.launch_job_in_B() = MagicMock()

# Make the EasyJob with the mocked BJob
ejob = EasyJob(bjob=mock_bjob)

# Call the method in question.
ejob.launch_job_in_A()

# Check if the method was called with the correct arguments.
mock_bjob.method.assert_called_once_with(cpu=100, memory=200)

BJob.launch_job_in_B would be tested in its own unit test.

  • Related