how to set expect_call on a function in while loop? - unit-testing

I am using gmock, gtest framework to test a function in my code. And I mocked the function which is called in side the main function which is being tested. The mock function is in a infinite while loop and exits only in case of success and keep prints an error message in case of failure. The mocked function looks like this,
while((fd = (socket(_,_,_)) < 0)
{
print("error")
}
return fd;
now I want to make the socket function fails and prints the error. I managed to print the error but since it's int he while loop it keeps printing the error message. How do I put an expectation so that the gtest stops printing after 1 or 2 times. I put the expectation like this
EXPECT_CALL(object, socket(_,_,_)).WillRepeatedly(return (error));
I tried with putting .Times(2), but it didn't work.

You'll need to have socket return a value >= 0 if you want the while loop to exit:
int error(-1), success(0);
EXPECT_CALL(object, socket(_,_,_))
.WillOnce(Return(error))
.WillOnce(Return(error))
.WillOnce(Return(success));

Related

Is there OutOfSequence?

In Google Mock, is there any inverse of InSequence? E.g. OutOfSequence
E.g. the assertion only works if the correct sequence does NOT occur.
AFAIK, there is not a feature like that which you can use directly, however, it's not hard to get to what you want.
Say you want the test fail if the following sequence of calls happen:
Disconnect() -> Connect()
You ask EXPECT_CALL to register the call sequences in a vector and then you can check to see if the sequence vector is what you expected. You can do this using Invoke, by using WillOnce and a lambda function that gets invoked when the function is called.
Here is an example that checks if Disconnect() -> Connect() sequence does not happen.
using ::testing::ElementsAre;
using ::testing::Not;
// Test if two functions are called out of sequence.
TEST(AtmMachine, OutOfSequence) {
std::vector<std::string> sequenceVector;
// Arrange
MockBankServer mock_bankserver;
// Assuming we want the test fail if Disconnect happens before Connect.
// We store their sequence in sequenceVector.
EXPECT_CALL(mock_bankserver, Disconnect())
.Times(1)
.WillOnce(
[&sequenceVector]() { sequenceVector.push_back("Disconnect"); });
EXPECT_CALL(mock_bankserver, Connect())
.Times(1)
.WillOnce([&sequenceVector]() { sequenceVector.push_back("Connect"); });
// Act
AtmMachine atm_machine(&mock_bankserver);
atm_machine.Withdraw(1234, 1000);
// Assert that the Disconnect() -> Connect() does not happen
EXPECT_THAT(sequenceVector, Not(ElementsAre("Disconnect", "Connect")));
}

can we clear errono after function call

I have some function call like below, and want to print success after success call, but got failure, even the function actually behave correctly.
int myfunction() {
// does some linux sys call for example
int error = run_cmd ("ifconfig usb10 up");
int syserrorno = errno;
strerror(syserrorno);
return error;
}
int main(){
int error =1;
int retry = 0;
do {
error = myfunction();
retry++;
}
while ( error !=-1 && retry <3);
return 0;
}
Basically I tried to:
Run a syscal via myFunction, return error = 1 if fail or 0 if success.
The return error in myFunction is the same as in syscal.
The syscal is a posix spawn command that I reuse from library.
If there is error, print error, redo 3 times.
So I have 1st run of syscall unsuccessfully; it returns error and print out "unavailabe resources". It is expected.
The second time is successful as I check the usb10 and it is up. But it still prints out the same error instead of success.
Is there a way to print it correctly ?
When using errno, always set errno=0; before calling the function(s) whose status you want to check. C library and POSIX functions will set errno to a non-zero value if they encounter an error, but they do not reset it to zero if they succeed.
(The reason they work this way: When a function reporting via errno is actually implemented in terms of other functions, you don't want a later success to make errno forget about an earlier failure. This also makes it possible for user code to set errno=0;, call a number of closely-related library functions, and just check for overall success or failure after all of those calls.)

NSubstitute conditions for throwing exception other than parameters

I'm using NSubstitute to mock a class that my method under test uses. This mocked class may throw a particular exception under certain conditions.
The method that I'm testing has some "retry" logic that it executes when it catches this exception. I'm trying to test this retry logic. So, I need a particular method of this mocked class to throw the exception sometimes, but not other times. Unfortunately, the method that throws this exception has no parameters, so I can't base the throw logic on parameters.
How can I make the mocked object's method throw the exception either:
A) ...the first N times it's called
or
B) ...based on the parameters some other method that's called before it
or
C) ...under any other condition other than the parameters passed in
To give you a clearer picture of what I'm trying to do, my code is something like:
IDataSender myDataSender = GetDataSender();
int ID = GetNextAvailableID();
myDataSender.ClearData();
myDataSender.Add(ID,"DataToSend");
bool sendSuccess = false;
while (!sendSuccess)
{
try
{
myDataSender.SendData();
sendSuccess = true;
}
catch (IDCollisionException)
{
ID++;
MyDataSender.ClearData();
myDataSender.Add(ID,"DataToSend");
}
}
So, I need to test my retry logic, and I need to simulate that IDCollisionException. However, I can't have the SendData() throwing the exception every single time, or the retry loop will never succeed.
What can I do here?
If I understand the question correctly, you can use When..Do and close over a local variable to get this behaviour.
const int throwUntil = 3;
var callsToSendData = 0;
var dataSender = Substitute.For<IDataSender>();
dataSender
.When(x => x.SendData())
.Do(x =>
{
callsToSendData++;
if (callsToSendData < throwUntil)
{
throw new DbCollisionException();
}
});
Similarly, you can also use callbacks to locally capture parameters passed to other methods, and access them within the Do block (rather than just using a counter).

C++ Return to command input function

I'm trying to make a simple program that takes a user command, executes a function, then returns to the original function so the user can enter another command, much like windows command prompt. Upon browsing the similar questions I read that returning to main is not good programming so I want to ask:
How can I make a function that has access to the other functions but the other functions can return to once they finish their process?
After a function returns, control is returned to the calling function.
Example:
#include <iostream>
int other_function(){
std::cout << "In other_function...\n";
return 0;
}
int main(){
std::cout << "Calling other_function()...\n";
int ret_value = other_function();
std::cout << "Back in main. other_function returned "
<< ret_value << ".\n";
return 0;
}
This little program starts in main, calls other_function and then returns back to main. It prints, out the messages with std::cout as well. Try the program if you don't understand the concept.
Also, I personally see no problem with doing all of this in main, perhaps in a while-loop. What people mean (generally) when they say you shouldn't always return control to main is that you want to keep all of your functions short, preferably about as large as your screen. However, the main function is there for a reason, so use it (with care).
Just make sure that the functions have been declared (or #included), and your function should be able to call them all.
Good luck!
There's absolutely NO problems in returning to main() function.
In your case, you can do an algorithm in a way like this:
Step 1: Start Main() function
Step 2: Read the command from the user
Step 3: Compare the command by using if() and strcmp() function.
Step 3.a: Call the function for the command.
Step 4: Repeat through step 2.

would return 0 using C++ in a class outside of main close the application?

I'm currently working on implementing patch files in some code, and apparently one of the patch files uses return 0 in a class outside of the main. I know return 0 would close the application if it was in the main function, however I'm not sure about how it would function in a class outside of the main function. Basically the code could be summed up like this in pseudocode:
boost::uint64_t
namespace::class(etc. etc.)
{
if (method.isValid)
{
//do stuff
}
return 0;
}
Normally when I think of return 0 in C++, I think of exiting the application by calling it in main, however in this case, I'm not sure if this would exit the application, or just the class's functionality/the class it self. Could someone please explain what the return 0 would actually be doing in this situation?
Thanks,
Flyboy
No.
Think of what would happen if this was the case:
int add(int a, int b) { return a + b; }
// somewhere:
int zero = add(2, -2); // would this exit the program?
It isn't the zero that is important in the return from main, it's the return. You can return any value from main and doing so will cause the program to exit (after all global variables are cleaned up, streams are closed, and other cleanup tasks are completed).
No, returning 0 (or anything else) from a function won't exit the application. Returning from main -- regardless of the value returned -- exits from a (single-threaded) application. But other functions come and go all the time.
return 0 is only relative to the scope of the current function so it will not close the application if it is outside of main.
Returning from main exits the application (regardless of the value being returned -- though the standard only defines meanings for 0, EXIT_SUCCESS, and EXIT_FAILURE). Returning from some other function just returns the designated value (if any) to the caller. The control flow doesn't change just because the value being returned happens to be zero.