Python Forum
Unittest et patch - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Unittest et patch (/thread-28894.html)



Unittest et patch - mad31 - Aug-08-2020

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 ...


RE: Unittest et patch - mad31 - Aug-08-2020

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



RE: Unittest et patch - mad31 - Aug-09-2020

No response Cry

My solution in fact is here :

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