python - mocking a function within a class method -



python - mocking a function within a class method -

i want mock function called within class method while testing class method in django project. consider next structure:

app/utils.py def func(): ... homecoming resp # outcome httpresponse object app/models.py from app.utils import func class mymodel(models.model): # fields def call_func(self): ... func() ... app/tests/test_my_model.py from django.test import testcase import mock app.models import mymodel class mymodeltestcase(testcase): fixtures = ['my_model_fixtures.json'] def setup(self): my_model = mymodel.objects.get(id=1) @mock.patch('app.utils.func') def fake_mock(self): homecoming mock.magicmock(headers={'content-type': 'text/html'}, status_code=2000, content="fake 200 response")) def test_my_model(self): my_model.call_func() ... # , asserting parameters returned func

when run test mock function fake_func avoided , real func called instead. guess scope in mock.patch decorator might wrong, couldn't find way create work. should do?

there 3 problems code:

1) daniel roseman mentioned, need patch module function called, not defined.

2) in addition, need decorate test method executing code calls mocked function.

3) finally, need pass mocked version in parameter test method, this:

fake_response = mock.magicmock(headers={'content-type': 'text/html'}, status_code=2000, content="fake 200 response")) class mymodeltestcase(testcase): fixtures = ['my_model_fixtures.json'] def setup(self): my_model = mymodel.objects.get(id=1) @mock.patch('app.models.func', return_value=fake_response) def test_my_model(self, fake_response): # mock goes in param or else number of arguments error! my_model.call_func() self.asserttrue(fake_response.called)

python django unit-testing mocking

Comments

Popular posts from this blog

java - How to set log4j.defaultInitOverride property to false in jboss server 6 -

c - GStreamer 1.0 1.4.5 RTSP Example Server sends 503 Service unavailable -

Using ajax with sonata admin list view pagination -