Python Forum

Full Version: Unittest et patch
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi,
I'm working with Notebooks Jupyter with my students, and i want to forbid them to use some fonction like len() in their scripts. I use the unittest package and have a test cell for the focntion longueur for example :

from unittest.mock import patch
with patch('__main__.len') as mock_len:
    longueur("aaa")
mock_len.assert_not_called()
In this case all works and the test cell fail if the student use len() in his fonction longeur()

But impossible to test the use of method like .count(), impossible to patch it;

I managed to do this:

from unittest.mock import MagicMock
L = MagicMock()
L.return_value=("")
compte(L,"b")
assert L.count.assert_not_called()
and it's works if the student use .count() in the fonction compte(L,a) :

AssertionError: Expected 'count' to not have been called. Called 1 times.
but if it doesn't... crash of , certainly beacause the fonction compte(L,a) is recursive.

Someone has a solution to test if .count() is use or not even the fonction is recursive ?


Thnk's for help ...
I have tried something like that too :
L = "aaa"
L.count = MagicMock()
but i get an error :
Error:
AttributeError: 'str' object attribute 'count' is read-only
No response Cry

My solution in fact is here :

Is it possible to patch a string method like
.count()
?