1

I am new to Python and writing a unit test for the already existing code.

I have the following Python code structure:

root_project:
-- src 
 -- signUp 
 -- __init__.py 
 -- abc.py 
 -- xyz.py

abc.py contains the following code:

from . import xyz
class Abc: 
 def __init__(self):
 pass 
 
 def start_process(self):
 xyz.start_timer()

I want to mock xyz.start_timer() inside method start_process of class Abc so that start_timer() mock version can be used.

How can I achieve this?

khelwood
59.7k14 gold badges91 silver badges116 bronze badges
asked Aug 1, 2022 at 13:20
1
  • 1
    This would be much easier if you inverted the dependency - if xyz was a parameter to the __init__ of Abc rather than an import, you could trivially inject a test double when instantiating Abc in the tests. Commented Aug 1, 2022 at 13:25

2 Answers 2

1

You can simply patch the start_timer function using mock.patch().

abc.py

import xyz
class Abc: 
 def __init__(self):
 pass 
 
 def start_process(self):
 xyz.start_timer()

test_abc.py

from unittest import mock, TestCase
from abc import Abc
class Test_Abc(TestCase):
 @mock.patch("abc.start_timer")
 def test_start_process(self, mock_start_timer):
 # your test code

Notice that I have patched abc.start_timer and not xyz.start_timer.

answered Aug 1, 2022 at 13:48
Sign up to request clarification or add additional context in comments.

Comments

0

You just need to patchxyz.start_timer(), I just added return to start_process to show that the patching really does what it should:

import xyz
import unittest
from unittest import mock
class Abc:
 def __init__(self):
 pass
 def start_process(self):
 return xyz.start_timer()
class Test_Abc(unittest.TestCase):
 @mock.patch('xyz.start_timer', return_value=True)
 def test_start_process(self, start_process):
 a = Abc()
 self.assertTrue(a.start_process())
if __name__ == '__main__':
 unittest.main()

Out:

.
----------------------------------------------------------------------
Ran 1 test in 0.000s
OK
answered Aug 1, 2022 at 13:31

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.