user3759055
user3759055

Reputation: 39

How to replace default argument in __init__ method in a unittest

I have a class under test that exposes an argument in __init__ just for testing. It looks like this

class MyClass(object):
  def __init__(self, start_time=None):
    if start_time is None:
      start_time = time.time()

In my test, I want to pass in start_time using a fake time, so I get a time in setUp() first and then pass it to every test method.

class MyclassTest(TestCase):
  def setUp(self):
    self.fake_start_time = time.time()

  def test_one(self):
    x = MyClass(start_time=self.fake_start_time)
    ...

  def test_two(self):
    x = MyClass(start_time=self.fake_start_time)
    ...

All this works, but I'm wondering if there's a way for me to avoid having to write start_time=self.fake_start_time in every single test. Can I somehow replace the __init__ method's default argument in setUp()?

I figured out an ugly way to do it, but was wondering if there's a more standard approach, possibly based on mock.patch?

Upvotes: 1

Views: 378

Answers (2)

ShadowRanger
ShadowRanger

Reputation: 155363

functools.partial can be used to pre-bind arguments. So in this case, you can bind the time to the class constructor and then use the bound constructor without passing additional arguments:

from functools import partial

class MyclassTest(TestCase):
  def setUp(self):
    # Feel free to use a shorter name
    self.FakeTimeMyClass = partial(MyClass, time.time())

  def test_one(self):
    x = self.FakeTimeMyClass()
    ...

  def test_two(self):
    x = self.FakeTimeMyClass()
    ...

Upvotes: 1

ErlVolton
ErlVolton

Reputation: 6784

Create an instance of the class in setUp:

def setUp(self)
    self.fake_start_time = time.time()
    self.x = MyClass(start_time=self.fake_start_time)

Upvotes: 1

Related Questions