Mocked value at method level not overriding class-level mock in unittest
Nessuno ha ancora preso questa issue.
- Lingua principale
- Python
- Stelle
- 77.2k
- Fork
- 35.9k
- Metriche di merge delle PR
- Metriche PR in attesa
Descrizione
Bug report
Bug description:
Description
I encountered an issue where mocking a value at the method level does not override the class-level mock in unit tests. Even though the method-level mock should take precedence, the value from the class-level mock is still being used.
Steps to Reproduce
Create a test class with a class-level mock using @mock.patch.
Add a method-level mock to one of the test methods to override the class-level mock.
Run the tests and observe that the class-level mock value is still used instead of the method-level mock.
Expected Behavior
The method-level mock should override the class-level mock, and the value set in the method-level mock should be used in the test.
Actual Behavior
The class-level mock value is used, and the method-level mock is ignored.
Sample code
import unittest
from unittest import mock
# Function to be mocked
def get_value():
return "original"
# Class-level mock
@mock.patch('module.get_value', return_value='class-level')
class TestMock(unittest.TestCase):
def test_class_level_mock(self, mock_get_value):
# This should return 'class-level'
result = get_value()
self.assertEqual(result, 'class-level')
@mock.patch('module.get_value', return_value='method-level')
def test_method_level_mock(self, mock_get_value):
# This should return 'method-level', but it returns 'class-level'
result = get_value()
self.assertEqual(result, 'method-level')
if __name__ == '__main__':
unittest.main()
CPython versions tested on:
3.10
Operating systems tested on:
No response
Guida per i contributori
Apri la guida per i contributori
Come iniziare
- Leggi tutta la issue e poi la guida ai contributi del progetto.
- Commenta sulla issue per dire che te ne occupi tu — evita che due persone facciano lo stesso lavoro.
- Fai un fork del repository e lavora su un branch.
- Apri una pull request che faccia riferimento al numero della issue.
Direzione di ricerca
Inizia riproducendo l’esempio con unittest.mock.patch applicato sia a livello di classe sia di metodo, quindi esamina i decoratori unittest.mock.patch e la loro interazione con i metodi di unittest.TestCase. Conferma se il valore restituito a livello di metodo viene ignorato e aggiungi o aggiorna un test di regressione mirato che mostri l’override previsto a livello di metodo.
Scritto dal modello di indicizzazione a partire dal testo della issue.
Valutazione
- Stack tecnologico
- python
- Ambito
- testing-qa
- Tipo di issue
- Bug
- Difficoltà
- 3/5
- Tempo stimato
- 1-2 giorni
- Stato di attività
- Ferma
- Chiarezza
- Abbastanza chiara
- Idoneità per principianti
- 35/100