Is it possible to modify a method without altering its functionality?

I am currently attempting to verify that a pandas method is being called with specific values.

However, I have encountered an issue where applying a @patch decorator results in the patched method throwing a ValueError within pandas, even though the original method does not. My goal is simply to confirm that Stock.calc_sma is indeed invoking the underlying pandas.rolling_mean function.

My understanding is that the @patch decorator adds certain "magic" methods to the object being patched, allowing me to verify if the function was called. That said, why does the behavior of the pandas.rolling_mean function differ when it is patched versus when it is not?

app/models.py

import pandas as pd
class Stock:  
    def calc_sma(self, num_days)
        if self.data.shape[0] > num_days:
                column_title = 'sma' + str(num_days)
                self.data[column_title] = pd.rolling_mean(self.data['Adj Close'], num_days)

app/tests/TestStockModel.py

def setUp(self):
    self.stock = MagicMock(Stock)
    self.stock.ticker = "AAPL"
    self.stock.data = DataFrame(aapl_test_data.data)

@patch('app.models.pd.rolling_mean')
def test_calc_sma(self, patched_rolling_mean):
    Stock.calc_sma(self.stock, 3)
    assert(isinstance(self.stock.data['sma3'], Series))
    patched_rolling_mean.assert_any_call()

ERROR: test_calc_sma (TestStockModel.TestStockModel)

Traceback (most recent call last):
  File "/Users/grant/Code/python/chartflux/env/lib/python2.7/site-packages/mock.py", line 1201, in patched
    return func(*args, **keywargs)
  File "/Users/grant/Code/python/chartflux/app/tests/TestStockModel.py", line 26, in test_calc_sma
    Stock.calc_sma(self.stock, 3)
  File "/Users/grant/Code/python/chartflux/app/models.py", line 27, in calc_sma
    self.data[column_title] = pd.rolling_mean(self.data['Adj Close'], num_days)
  File "/Users/grant/Code/python/chartflux/env/lib/python2.7/site-packages/pandas/core/frame.py", line 1887, in __setitem__
    self._set_item(key, value)
  File "/Users/grant/Code/python/chartflux/env/lib/python2.7/site-packages/pandas/core/frame.py", line 1967, in _set_item
    value = self._sanitize_column(key, value)
  File "/Users/grant/Code/python/chartflux/env/lib/python2.7/site-packages/pandas/core/frame.py", line 2017, in _sanitize_column
    raise ValueError('Length of values does not match length of '
ValueError: Length of values does not match length of index

Answer №1

>>> import os
>>> os.getcwd()
'/'
>>> from unittest.mock import patch
>>> with patch('os.getcwd'):
...     print(os.getcwd)
...     print(os.getcwd())
...     print(len(os.getcwd()))
...
<MagicMock name='getcwd' id='4472112296'>
<MagicMock name='getcwd()' id='4472136928'>
0

Typically, patch replaces objects with generic mock objects. The example demonstrates that calling the mock object returns another mock, displaying a length of 0 even if the original object wouldn't have a length attribute. Moreover, its attributes are also mock objects.

To replicate actual behavior, additional arguments are needed:

>>> with patch('os.getcwd', return_value='/a/wonderful/place'):
...     os.getcwd()
...
'/a/wonderful/place'

Alternatively, to "pass through":

>>> _cwd = os.getcwd
>>> with patch('os.getcwd') as p:
...     p.side_effect = lambda: _cwd()
...     print(os.getcwd())
...
/

A comparable example is available at https://docs.python.org/3.5/library/unittest.mock-examples.html

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Removing partial duplicates in pandas

Two dataframes are available: Dataframe 1 (df1): x y z 0 1 2 r 1 a c 2 2 22 g d Dataframe 2 (df2): x y z 0 1 2 r 1 a b 2 2 3 g d The goal is to remove rows where columns y and z have duplicate values. Desired output ...

Button click event is not being triggered by Ajax rendering

I am facing an issue with my Django template that showcases scheduled classes for our training department. Each item in the list has a roster button which, when clicked, should display the class roster in a div. This functionality works perfectly. However, ...

The input speed of text using Selenium on the search field is extremely slow with IEDriverServer

Currently, I'm utilizing selenium with Python on a Windows 7 system. This is the code snippet I am using: import os from selenium import webdriver ie_driver_path = "C:\Python36\Scripts\IEDriverServer.exe" driver = webdriver.Ie(ie_dr ...

Converting serial data into columns within a pandas dataframe through row transformation

I'm looking to convert individual rows in a dataframe into columns with their corresponding values. My pandas dataframe has the following structure (imported from a json file): Key Value 0 _id 1 1 type house 2 surface ...

How to Use AngularJS $http Mock Respond to Simulate a Response with a `location` Header?

One interesting scenario I have encountered involves an API that returns a status code of 202 with no data. However, the response includes a header called "Location" which points to a specific URL. After browsing through the $httpBackend respond(...) docu ...

What is the process for starting a Dash App that is contained within a package that has already been installed?

In the process of developing a package, I have structured it with a module containing functions (fed3live.py) and another with a Dash App (fed3_app.py). Here is how the package is organized: fed3live/ ├─__init__.py ├─fed3live/ │ └─fed3live.py ...

Improving the readability and efficiency of nested if statements

Consider the 1D numpy array arrRow provided below. The array consists of 1s and 0s, with a notable characteristic being the presence of exactly two 0-islands. Each island has Edge cells (E) at its right and left ends, while Border cells (B) are located imm ...

What is the best way to name labels for columns and rows in Pandas DataFrames?

I'm currently working on structuring my data frame in a specific format: https://i.stack.imgur.com/0W8rC.png Here's what I have attempted so far: labels = ['Rain', 'No Rain'] pd.DataFrame([[27, 63],[7, 268]], columns=label ...

Selenium is being used to block login automation in Edge modal

Currently, I am working on a Python script to automate logging into Edge using msedge-selenium-tools. However, when running the script, a modal window pops up and I am facing challenges in identifying CSS selectors to use with Selenium. Here is the snippet ...

Create a collection showcasing only the values present in an array based on a specified percentage

An array named "data" consists of the given information. [['amazon', 'phone', 'serious', 'mind', 'blown', 'serious', 'enjoy', 'use', 'applic', &apos ...

What is the best way to transmit a UTF-8 encoded JSON string over TCP using Python?

I've been struggling to send a UTF-8 encoded JSON string over TCP (Python 2.7). Below are some attempts and their results. The 'response' variable contains the JSON string I'm trying to send: response = {"candidates":{"P":[{"mentionnam ...

Python os.system() function yielding incorrect result

In my current project, I am utilizing a Python script that utilizes the os.system() function to repeatedly call a command line program for running test cases. The program in question returns zero for typical operation and a negative value for error situati ...

Python : Enforcing input validation for numerical values including decimals

Is there a way to validate user input to accept only integers or numbers with two decimal places? If the input includes alphabet characters or symbols, I want it to display 'invalid' and prompt the user to enter again. Here is the code snippet: ...

Building a Python Lambda function that connects to an AWS HTTP API

In this resource, you can find a guide on how to create an HTTP API that triggers a Lambda function using a node.js runtime. I recently attempted the same process with a Python lambda using the following handler: def lambda_handler(event, context): r ...

Python is experiencing difficulties with copying xpath elements

I attempted to utilize some Python code to access Twitter and retrieve the "Happening now" text. Unfortunately, it was unsuccessful. import webbrowser print("Visiting Twitter.com...") webbrowser.get('C:/Program Files (x86)/Google/Chrome/Application/c ...

"Setting up the latest version of Selenium along with ChromeDriver and Headless Chrome driver for automated testing

Utilizing Python and Selenium with AWS Lambdas for web crawling has been a part of my workflow. After upgrading Python to version 3.11 and Selenium to version 4.18.0, I encountered issues that caused my crawlers to cease functioning properly. Below is the ...

Adding an image within the body of text in a Django model, where both the text and image coexist

I am currently seeking a method to seamlessly insert an image within the text of my Django-powered blog. My goal is to achieve a layout similar to the one showcased in this example: https://i.stack.imgur.com/cFKgG.png The desired layout consists of two c ...

What is the process of incorporating G-mean into the cross_validate sklearn function?

from sklearn.model_selection import cross_validate scores = cross_validate(LogisticRegression(class_weight='balanced',max_iter=100000), X,y, cv=5, scoring=('roc_auc', 'average_precision','f1', ...

When pandas makes modifications, it fails to preserve the original string format

I've developed a code that processes string-based data like this: 501NA NA 1 3.283 0.011 4.761 502NA NA 2 4.337 1.367 0.160 503NA NA 3 4.795 2.498 4.104 After converting it from txt to csv format for b ...

Webdriver Manager Python installation failed due to site-packages being read-only; defaulting to user installation to satisfy requirements

When I try to import WebDriverManager for Chrome, here's the output I receive: $ pip install webdriver-manager Defaulting to user installation because normal site-packages is not writeable Requirement alrea ...