this testwritten using py test syntaxasserts that the correct exception is raised when an inappropriate argument is passed in in additionit creates mock object for the set method and makes sure that it is never called if it wasit would mean there was bug in our exception handling code simply replacing the method worked fine in this casesince the object being replaced was destroyed in the end howeverwe often want to replace function or method only for the duration of test for exampleif we want to test the timestamp formatting in the mock methodwe need to know exactly what datetime datetime now(is going to return howeverthis value changes from run to run we need some way to pin it to specific value so we can test it deterministically remember monkey-patchingtemporarily setting library function to specific value is an excellent use of it the mock library provides patch context manager that allows us to replace attributes on existing libraries with mock objects when the context manager exitsthe original attribute is automatically restored so as not to impact other test cases here' an examplefrom unittest mock import patch def test_patch(tracker)tracker redis set mock(fake_now datetime datetime( with patch('datetime datetime'as dtdt now return_value fake_now tracker change_status("ac ""on time"dt now assert_called_once_with(tracker redis set assert_called_once_with"flightno:ac "" : : |on time"in this examplewe first construct value called fake_nowwhich we will set as the return value of the datetime datetime now function we have to construct this object before we patch datetime datetime because otherwise we' be calling the patched now function before we constructed itthe with statement invites the patch to replace the datetime datetime module with mock objectwhich is returned as the value dt the neat thing about mock objects is that any time you access an attribute or method on that objectit returns another mock object thus when we access dt nowit gives us new mock object we set the return_value of that object to our fake_now objectthat waywhenever the datetime datetime now function is calledit will return our object instead of new mock object