Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to mock a free function in python?

Tags:

python

mocking

I have a python program with a global function that is painful to test (it needs a large dataset to work properly). What is the best way to get around this while testing functions that call it?

I've found that the following works (but it make me feel dirty to use it).

module foo:

def PainLiesHere():
  return 4; #guaranteed to be random

module test

import foo

def BlissLiesHere():
  return 5

foo.PainLiesHere = BlissLiesHere

# test stuff
like image 249
BCS Avatar asked Jul 01 '10 00:07

BCS


People also ask

Does Pytest have mocking?

Advanced: Mocking in Unit TestIn pytest , mocking can replace the return value of a function within a function. This is useful for testing the desired function and replacing the return value of a nested function within that desired function we are testing.

What is Mocker in Python?

mock is a library for testing in Python. It allows you to replace parts of your system under test with mock objects and make assertions about how they have been used. unittest. mock provides a core Mock class removing the need to create a host of stubs throughout your test suite.


1 Answers

This is a perfectly fine way to do it. As long as you know that BlissLiesHere does not change the overall behavior of the unit you are testing...

EDIT:

This is what is being done, under all the nice extras they provide, by different kinds of mocking libraries, such as Mock, Mox, etc.

like image 156
Arkady Avatar answered Oct 11 '22 21:10

Arkady