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
0
votes
1 answer

How to add a relative reference to a global variable in __init__.py in parent package from patch.object()?

I have the file structure as follow: In /packageA/__init__.py: from my_mako_stuff import mako_lookup ... def func_in_package(): ... template = mako_lookup(...) In /packageA/mas.py: from . import func_in_package ...# do some stuff with…
0
votes
1 answer

How to unittest file containing assert __name__ == "__main__"

I want to unit test a piece of code from a module using the Mock testing library. # File_name: do.py assert __name__ == "__main__", "This module should NOT be imported." from disk import Disk def bool_fun(args): res = Disk.disks() …
0
votes
1 answer

How to employ a MagicMock spec_set or spec on a method?

I am trying to use a method as a spec_set on a MagicMock. https://stackoverflow.com/a/25323517/11163122 provides a nice example of an unexpected call signature resulting in an Exception. Unfortunately, I can't get it to work out for a method. How…
Intrastellar Explorer
  • 3,005
  • 9
  • 52
  • 119
0
votes
0 answers

python unittest function expected called but the result is none called

This is my function : #File lambda_function.py from calculate import addition def lambda_handler(event, context): try: v = addition(2) return { "statusCode": 200, "body": { "message": v, …
0
votes
1 answer

Unittest - mock os.listdir is not used in testfunction / returns wrong value

I want to test the following function, but still struggle with a best practice with testing I/O operations. def get_weight_file(path: Union[Path, str]) -> str: """Finds weights (.model) file in a directory Parameters ---------- …
Data Mastery
  • 1,555
  • 4
  • 18
  • 60
0
votes
1 answer

ModuleNotFoundError when using mock.patch()

I want to mock a response from the Python Kubernetes client. Below code of my Kubernetes service: import os from kubernetes.client.rest import ApiException from kubernetes import client from kubernetes.config import load_config from…
0
votes
1 answer

How to write python unittest case for except block which just uses a logger statement

Code for celery task: import logging from celery_once import QueueOnce from celery import shared_task, current_task from test.set_data import set_data_in_db logger = logging.getLogger("celery") @shared_task(base=QueueOnce, once={"graceful":…
0
votes
1 answer

Get patch'd object with use of unittest.mock's patch decorator and new

I have the below Python==3.8 code, where I: Use unittest.mock.patch as a decorator Preform a patch(..., new=...): from unittest.mock import patch class Foo: pass class Bar: pass @patch(__name__ + f".Foo", new=Bar) def…
Intrastellar Explorer
  • 3,005
  • 9
  • 52
  • 119
0
votes
1 answer

unittest mock replace/reset mocked function when patching an object

I need to use unittest.mock.patch.object to mock an external method that may fail sometimes. In the test, the method shall raise some errors and then return to the original behaviour. Note that the behaviour I want to reproduce is by far more…
ronkov
  • 1,263
  • 9
  • 14
0
votes
1 answer

How to mock mongodb with unites Flask

I want to mock mongo in order to make some unit test with unittest for Flask. The doc about this is so huge and I don't really understand how to make it. I want to test a POST method with the following data: from unittest import TestCase, main as…
0
votes
1 answer

How to get PropertyMock for assertions without original PropertyMock object?

I have a unittest.mock.PropertyMock (docs) object created for unit testing purposes, on an attribute within an object. I no longer have the reference to the PropertyMock made, as the PropertyMock was monkeypatched in during test setup. How can I get…
Intrastellar Explorer
  • 3,005
  • 9
  • 52
  • 119
0
votes
0 answers

How to mock a function which is called several times within a parent function, Python3?

I'm having a function which makes 3 get request to fetch file from S3 bucket. So i need to mock them correctly to return an expected result. Below is the code structure # src.py def parent(bucket, file): json_object = get_object(bucket, file) ##…
ahkam
  • 607
  • 7
  • 24
0
votes
1 answer

How to mock a variable from another module in python3?

Below is my source code #src.py from common.configs import MANDATORY_FIELDS def check_mf(): if set(MANDATORY_FIELDS).issubset(['a','b','c']): return True else: raise Exception("Error in mandatory fields") And here is my test…
ahkam
  • 607
  • 7
  • 24
0
votes
1 answer

How to mock a s3 object in python?

In my code there is a method which get csv files from s3 bucket. i need to mock that object in my test file. Below is the source function s3 = boto3.client('s3') def method(): ... obj = s3.get_object(bucket, key) csv_content =…
ahkam
  • 607
  • 7
  • 24
0
votes
0 answers

Mocking a class method in Python

Say I have the following: # maincode.py from othermodule import do_something class Myclass(): @staticmethod def return_array(): array_result = do_something() return array_result @classmethod def main(): array_result…
Allen Wu
  • 165
  • 1
  • 2
  • 10