Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Unittest et patch
#1
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 ...
Reply
#2
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
Reply
#3
No response Cry

My solution in fact is here :

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


Possibly Related Threads…
Thread Author Replies Views Last Post
  problem in using unittest akbarza 2 258 Feb-25-2024, 12:51 PM
Last Post: deanhystad
Question Unwanted execution of unittest ThomasFab 9 1,948 Nov-15-2022, 05:33 PM
Last Post: snippsat
  unittest.mock for an api key silver 3 1,336 Aug-29-2022, 03:52 PM
Last Post: ndc85430
  Ran 0 tests in 0.000s - unittest Peaches 8 4,929 Dec-31-2021, 08:58 AM
Last Post: Peaches
Sad Problem with Unittest mhanusek 1 3,680 Nov-12-2020, 04:58 PM
Last Post: Gribouillis
  Unusual things to do with unittest/HTMLTestRunner AndyHolyer 0 2,103 Jul-29-2020, 02:43 PM
Last Post: AndyHolyer
  Test a class function via "unittest " Penguin827 1 1,577 Jul-10-2020, 08:31 AM
Last Post: Gribouillis
  How to use unittest module ? binhduonggttn 1 2,007 Feb-17-2020, 03:28 AM
Last Post: Larz60+
  unittest mock and patch piscvau 1 2,071 Nov-08-2019, 03:23 PM
Last Post: ichabod801
  Optimize unittest loading Nazz 3 2,487 Mar-05-2019, 11:59 AM
Last Post: Nazz

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020