Questions tagged [python-unittest.mock]

mock object library (part of the Python Standard Library)

unittest.mock allows you to replace parts of your system under test with mock objects and make assertions about how they have been used.

It provides a core Mock class removing the need to create a host of stubs throughout your test suite.

330 questions
1
vote
0 answers

How to prevent the class variable initialization code from running in the unit test code?

I have the following class A to be tested. aaa.py def get_c(): print('call external modules to get c from some expensive I/O') return 'something' @dataclass class A: c: ClassVar[C] = get_c() # get_c() shouldn't be run in the test…
ca9163d9
  • 27,283
  • 64
  • 210
  • 413
1
vote
1 answer

how to mock lambda cache ssm getattr

I am using lambda_cache library in python to implement caching for coupld of parameters stored in ssm. The following code is working as expected. from lambda_cache import ssm @ssm.cache(parameter=['applicationId', 'sharedSecret'],…
ChinnaR
  • 797
  • 3
  • 9
  • 24
1
vote
1 answer

StopIteration when mocking base class of own class

In a rather complex test scenario I need to mock the base class of one of my own classes and instantiate the latter several times. When I do that my test errors with a StopIteration exception. Here's what my scenario boils down to in this…
1
vote
0 answers

Python Unittest for a PyTorch Model

I have got the following function where I struggle with: def load_trained_bert( num_classes: int, path_to_model: Union[Path, str] ) -> Tuple[BertForSequenceClassification, device]: """Returns a bert model and device from four required model…
Data Mastery
  • 1,555
  • 4
  • 18
  • 60
1
vote
1 answer

Test a function in Python which merges files and returns nothing

I have the task to write a Test for the following function: def merge_files(cwd: Path, source: str, target: str): """[Merges the content of two files of the same data type] Parameters ---------- cwd : Path [Path of the the…
Data Mastery
  • 1,555
  • 4
  • 18
  • 60
1
vote
1 answer

Unittest simulate reading a yaml file with a mock

I try test a function which reads a file and returns the content of the file or returns none if the file is not found. def read_yaml_from_cwd(file: str) -> Dict: """[reads a yaml file from current working directory] Args: file…
Data Mastery
  • 1,555
  • 4
  • 18
  • 60
1
vote
0 answers

Testing in Python with unittest: Mock subfolders

I have the following function I want to test: def rmdir_and_files_with_exceptions(folder: str, exceptions: "list[str]") -> None: """[removes subfolders and files of a given folder with a list as parameter to prevent deletion] Args: …
Data Mastery
  • 1,555
  • 4
  • 18
  • 60
1
vote
1 answer

How to write python unittest cases to mock redis connection (redis.StrictRedis) in Django

How can I mock the following function for connecting to Redis? import redis class RedisCache: redis_instance = None @classmethod def set_connect(cls): redis_instance = redis.StrictRedis(host='0.0.0.0', port=6379,…
1
vote
2 answers

setUp function for python unittest doesn't use mocks declared over the class

so I'm writing unit tests and I'm having trouble with the setUp function. From what I've seen, it's supposed to just execute code before your function and thus I could put anything that's repetitive in there. However, this function doesn't seem to…
1
vote
1 answer

Mock the return value of a function derived from an input parameter

I want to mock the return value of a function that derives from an input parameter (a). Here is the my code looks like. def load_data(a, b, c): data_source = a.get_function(b, c) ... return r_1, r_2, r_3 This is what I tried and…
Shashika
  • 1,606
  • 6
  • 28
  • 47
1
vote
1 answer

python: assert_has_calls taking last value in loop

I have a function similar to foo and I am trying to test it using following code from unittest.mock import call, patch def foo(): x = {} for i in range(3): x["val"] = i print(x) @patch('builtins.print') def…
1
vote
1 answer

How to mock a class in one script from another test script running the first

I have a class SQLES in a separate script, sqles.py, which is imported in main.py and comprises methods to read SQL data and set the results in the class instance. I am now writing a test script, test_main.py, in which I want to define a mock SQLES…
1
vote
1 answer

Unit-testing datetime

Can someone help me to unit test this line of code? from datetime import datetime, timedelta, timezone def get_timestamp_plus_100_year(): return int((datetime.now(timezone.utc) + timedelta(days=100 * 365)).timestamp()) I try this, but I don't…
1
vote
0 answers

ValueError: not enough values to unpack (expected 2, got 0) when mocking

I have a function for my database connection that returns both cursor and connection. def database_connection(): resp_dict = json.loads(get_secret()) endpoint = resp_dict.get('host') username = resp_dict.get('username') password =…
L44TXF
  • 65
  • 3
  • 10
1
vote
0 answers

How can I mock `subprocess.check_output`?

I'm trying to mock subprocess.check_output for some tests, but it doesn't seem to work. Consider this code: from unittest.mock import patch from subprocess import check_output @patch('subprocess.check_output', return_value="not a date") def…
Eddie Aftandilian
  • 219
  • 1
  • 2
  • 4