How to supply a mock class method for python unit test?

2024/11/20 17:26:03

Let's say I have a class like this.

class SomeProductionProcess(CustomCachedSingleTon):@classmethoddef loaddata(cls):"""Uses an iterator over a large file in Production for the Data pipeline."""pass

Now at test time I want to change the logic inside the loaddata() method. It would be a simple custom logic that doesn't process large data.

How do we supply custom implementation of loaddata() at testtime using Python Mock UnitTest framework?

Answer

Here is a simple way to do it using mock

import mockdef new_loaddata(cls, *args, **kwargs):# Your custom testing overridereturn 1def test_SomeProductionProcess():with mock.patch.object(SomeProductionProcess, 'loaddata', new=new_loaddata):obj = SomeProductionProcess()obj.loaddata()  # This will call your mock method

I'd recommend using pytest instead of the unittest module if you're able. It makes your test code a lot cleaner and reduces a lot of the boilerplate you get with unittest.TestCase-style tests.

https://en.xdnf.cn/q/26296.html

Related Q&A

View pdf image in an iPython Notebook

The following code allows me to view a png image in an iPython notebook. Is there a way to view pdf image? I dont need to use IPython.display necessarily. I am looking for a way to print a pdf image i…

Is the use of del bad?

I commonly use del in my code to delete objects:>>> array = [4, 6, 7, hello, 8] >>> del(array[array.index(hello)]) >>> array [4, 6, 7, 8] >>> But I have heard many …

Find how many lines in string

I am creating a python movie player/maker, and I want to find the number of lines in a multiple line string. I was wondering if there was any built in function or function I could code to do this:x = &…

AttributeError: Cant get attribute new_block on module pandas.core.internals.blocks

I was using pyspark on AWS EMR (4 r5.xlarge as 4 workers, each has one executor and 4 cores), and I got AttributeError: Cant get attribute new_block on <module pandas.core.internals.blocks. Below is…

Disable python import sorting in VSCode

I am trying to disable vscode from formatting my python imports when I save my file. I have some code that must run in between various imports so order is important, but every time I save it just shove…

Log-log lmplot with seaborn

Can Seaborns lmplot plot on log-log scale? This is lmplot with linear axes: import numpy as np import pandas as pd import seaborn as sns x = 10**arange(1, 10) y = 10** arange(1,10)*2 df1 = pd.DataFra…

Django on IronPython

I am interested in getting an install of Django running on IronPython, has anyone had any success getting this running with some level of success? If so can you please tell of your experiences, perfo…

How to create a DataFrame while preserving order of the columns?

How can I create a DataFrame from multiple numpy arrays, Pandas Series, or Pandas DataFrames while preserving the order of the columns?For example, I have these two numpy arrays and I want to combine …

Dynamically limiting queryset of related field

Using Django REST Framework, I want to limit which values can be used in a related field in a creation. For example consider this example (based on the filtering example on https://web.archive.org/web/…

How to clear GPU memory after PyTorch model training without restarting kernel

I am training PyTorch deep learning models on a Jupyter-Lab notebook, using CUDA on a Tesla K80 GPU to train. While doing training iterations, the 12 GB of GPU memory are used. I finish training by sav…