Why python unittest fails to mock some static methods - python-3.6

I have some static methods written in util files. When I try to patch them and add a side_effect to return a specific value, they just execute the original method content. It is not getting mocked. Why is this happening? Is there any way to overcome this issue, rather than trying to mock the internal methods of that method?
I am trying to mock below method which is in date_utils.py file.
def get_sys_date_in_sap_format():
today = datetime.now()
date = today.strftime("%d.%m.%Y")
logger.info("Date: {}", date)
return date
It is patched using below approach;
#patch("src.util.date_utils.get_sys_date_in_sap_format", side_effect=mock_sap_date)
This method is invoked inside the method which I am trying to test. Some help is really appreciated, as I am confused as why it is happening. Is there a way to resolve this?

#MrBean Bremen, it worked when I changed the import to b.my_method instead of a.my_method. I have always been wondering about this issue. Thank you so much.
#patch("src.sap.file_upload_service.get_sys_date_in_sap_format", return_value="11.10.2019")

Related

How to mock an inlined InitiatingFlow return value during another flow

I have SomeBigFlow that calls multiple subflows inside it i.e ValidateFlowA, ValidateFlowB. Assuming it is mandatory for A and B to be initiating flows not functions.
How do I mock a return value for ValidateFlowA when I run the SomeBigFlow in Junit?
I've seen some references to using registerAnswer to mock flows' return value here. I am also curious why this function is only available for InternalMockNetwork.MockNode but not MockNetwork.StartedMockNode which is typically used during junit testing)
I thought I could replicate it by having node[1].registerAnswer(ValidateFlowA.class, 20). But when I ran node[1].startFlow(SomeBigFlow).resultFuture.getOrThrow(), the ValidateFlowA is still using its default call implementation instead of returning the mocked 20 integer value. Maybe I'm using it wrong.
Any pointers on how to make this work or is there a solution to achieve mocking inlined subflows returned values? The only other way I can think of is have a rule of thumb that whenever calling an inlined subflow, put them in an open fun that can be overridden during mocknetwork testing - this makes inlined subflow tedious, hoping for a neater way.
For now, you'd have to use a similar approach to the one outlined here: Corda with mockito_kotlin for unit test.
In summary:
Make the FlowLogic class you are testing open, and move the call to the subflow into an open method
For testing, create a subclass of the open FlowLogic class where you override the open method to return a dummy result
Use this subclass in testing

Spying on a method parameters in phpunit, while calling the original method

I am trying to understand is it possible with phpunit to create spy on a method, while calling the original method.
I have done it in java, but I don't see a way to do it in phpunit. I only find that if I spy on the invocations of the method, I also need to mock it.
Example code:
$this->spy = $this->getMockBuilder('\ClassUnderTest')
->setMethods(['methodToSpy'])
->getMock();
$this->spy->expects($this->any())
->method('methodToSpy')
->will($this->returnCallback(array($this, 'stubMethodToSpy')));
So in the test, I want to "spy" on the call to the real method 'methodToSpy()', so I can make on-the-fly analysis on the parameters passed to it (I need to use them in the test later on).
Any idea if this is possible? (or maybe it is not possible in phpunit because it is not multithreaded like java)
You are looking for test proxies.

in Flex 3.2 Having troubles converting remote object result to specific object on client side in modules

in Flex 3.2 Having troubles converting remote object result to specific object on client side in modules.
For example I have VIPSAdmin module.
it has function
private function doResult(event:ResultEvent):void {
var data_:Array = ArrayUtil.toArray(event.result);
var result:ResultDTO = data_[0] as ResultDTO;
if(!result.isError()) {
trace(result.result);
vipsAdminDTO = result.result as VIPSAdmin;
compId= vipsAdminDTO.compId; // second time dying here
}
}
Function invoked when I get data from remote objet.
First time all great,when I unload this modeule and load it again:
data_[0] as ResultDTO;
Performs fine, but
vipsAdminDTO = result.result as VIPSAdmin;
vipsAdminDTO always null!
Even when
trace(result.result);
produces [object VIPSAdmin]
What a heck I missing here!? Looks like it just cannot do
result.result as VIPSAdmin;
even when trace and debug says it is instance of VIPSAdmin
I've figured out what is the problem, problem is that when I first instantiate something in module then in main app, somehow classes are not alined even that they are identical !
So solution is to make a fake instance in application class first, then if you use that same class to make an instance in module it will work!
I do it very simple in my main application class I just added:
VIPSAdmin;
This seems to create some sort of ghost instance, which I belie will be pickup by GC later, but will build tables of instances properly! Which solved my problem.
Not sure if this is appropriate solution ! but it sure works.

How do I make one of a stub's method call the real method in ASMock?

In flex I want to do something similar to the following
var audioPlayerMock:AudioPlayer = AudioPlayer(mockRepository.createStub(mockRepository.createStub(AudioPlayer));
SetupResult.forCall(audioPlayerMock.play).(CALL_ACTUAL_PLAY_METHOD(WITH_ARGUMENT));
AudioPlayer has a lot of methods that I want stubbed, (so I use mockRepository.creatStub()). But there is one method, play(), that I want to call the actual actual method (super.play(argument) if my thinking is right). I'm not sure how to do this?
I know I can use createDynamic(AudioPlayer) then stub out every other method, but that is a bit tedious.
Cheers
You can use IMethodOptions.callOriginalMethod() to call the actual implementation on a stubbed class:
SetupResult.forCall(authatoPlayerMock.play(null))
.ignoreArguments()
.callOriginalMethod();

Simple Moq ? - Problem with .Verify

just a simple question here. I've used Moq for awhile but, as of yet, have only used it for stubbing and not for mocking. I am trying to introduce our developers to unit testing. I set up a simple example to explain the concepts but i can't seem to get it working. Probably something simple so i thought i would just ask you all to see what i'm doing wrong:
<Test()> _
Public Sub Divide_DivideByZero_LogsError()
Dim mock = New Mock(Of ILogger)
With mock
Dim calc = New MyCalculator(New CalculatorData, .Object)
calc.Divide(55, 0)
.Verify(Function(x) CType(x,ILogger).WriteError(it.IsAny(of String),It.IsAny(Of String))))
End With
End Sub
I'm using Moq version 3.2.416.3. I get an error on the .verify telling me that i'm calling it with incorrect arguments. I'm just trying to verify that .WriteError was called. any help would be appreciated.
Edit:
Ok everyone, if i change ".WriteError" from a sub (void return) to a function that returns a boolean it works. WriteError doesn't really need to be a function. Does anyone know why a sub wouldn't work?
Edit: Ok everyone, if i change ".WriteError" from a sub (void return) to a function that returns a boolean it works. WriteError doesn't really need to be a function. Does anyone know why a sub wouldn't work?
As far, as I remember, VB9 does not support anonymous Subs (only Functions) and it's a serious show-stopper for Moq usage in VB.net.
So, as soon, as you have changed WriteError signature from Sub to Function, compiler have successfully resolved return type for anonymous function in Verify parametrer.
I think you need to make it Verifiable() before actually calling Verify(). I'm not sure if it can do automatic verifiability though.
And IMHO I find using VerifyAll() much easier than verifying individual methods. i.e.:
mock.Setup(Function(x) CType(x, ILogger).WriteError(It.IsAny(Of String), It.IsAny(Of String))) _
.Verifiable()
mock.Object.WriteError("test", "Test")
mock.VerifyAll()
Not sure if I get all the method names/signature right though but you should get the idea.

Resources