Capture arguments to a callback in google mock - c++

I have an object which has a method like this:
mockObj.foo(cb);
where cb is a function of the following signature:
void cb(vector<A> &, vector<B> &);
Is there any way to capture the 2 arguments passed to cb to see if the function did what I wanted it to do? I expect cb to be called N number of times.

If you want to test what Obj class is doing - unit test Obj class in separation, like (of course I know real Obj::cb is not clearing input - this is just an example):
TEST(ObjTest, shouldResetInput)
{
vector<A> aa(1);
vector<B> bb(1);
Obj objUnderTest;
objUnderTest.cb(aa, bb);
ASSERT_TRUE(aa.empty());
ASSERT_TRUE(bb.empty());
}
In other objects, where Obj is used, inject it as ObjMock and just check only that this cb function is called with input as you expect - check input by Container Matchers. If you want in this clients of Obj change the input after the function is called - use Side Effect Actions.

Related

Convert data type a of class object (C++)

I am writing a game in which one Object has an ability to turn into an object of another class (e.g. Clark Kent -> Superman). I would like to know what is the most efficient way to implement this.
The logic of my current code:
I have created a turnInto() function inside the ClarkKent class. The turnInto function calls the constructor of Superman class, passing all needed infos to it. The next step is to assign the address of Superman object to the current ClarkKent object.
void ClarkKent::turnInto() {
Superman sMan(getName(), getMaxHP(), getDamage());
&(*this) = &w; // <- error here
this->ClarkKent::~ClarkKent();
}
As you might have guessed, the compiler gives an error that the expression is not assignable. Not sure how to find a correct solution to this.
Keep it simple and don't play tricks you don't understand with your objects.
Superman ClartkKent::turnInto() {
return {getName(), getMaxHP(), getDamage()};
}
At the callee:
ClartkKent some_guy{...};
auto some_other_guy = some_guy.tunInto();
Or if you need something fancy:
using NotBatman = std::variant<ClartkKent, Superman>;
NotBatman some_guy = ClartkKent{...};
using std::swap;
swap(some_guy, some_guy.tunInto());
IDK

How do I use operators in LuaBridge

I'm trying to export my vectors class
.beginClass<Vector>("Vector")
.addConstructor<void(*)()>()
.addConstructor<void(*)(float, float, float)>()
.addFunction("__eq", &Vector::operator==)
.addFunction("__add", &Vector::operator+)
.addData("x", &Vector::x)
.addData("y", &Vector::y)
.addData("z", &Vector::z)
.addFunction("Length", &Vector::Length)
.addFunction("Angle", &Vector::Angle)
.addFunction("Distance", &Vector::DistTo)
.endClass()
but when i try and do the other 3 operators, I have multiple overloads for them. How can I specify which one I want to use and is this even possible?
If you have a function overloads int MyClass::Func(int) and MyClass* MyClass::Func(MyClass) then you can define the overload to use in the following manner. In this example I chose to use MyClass* MyClass::Func(MyClass) as overload.
.addFunction("Func", (MyClass*(MyClass::*)(MyClass)) &MyClass::Func)
So what happens here is that the function signature is provided with the pointer to the function.
So I just made an add/subtract/multiply/divide function and called that instead. Guess operators just don't want to comply.
infect luabridge can implement this in this way,
if you define a class A
.addFunction("__eq", &A::equal )
'equal' should be declared like:
bool A::equal( const A & )
then :
if obj1 == obj2 then
end
'equal' will work!
but if you implement a sub class of A
class B : public A
it's will takes you a lot of time!
first you have to Specialization the template class or the template method
luabridge::UserdataValue
luabridge::UserdataPtr::push(lua_State* const L, T* const p)
the specify which class's (meta)table you need to regist the object or the pointer
you should read luabridge's sourcecode to accomplish this!
Then!
you should regist this function to B again!
.addFunction("__eq", &B::equal )
lua code :
local inst_a = app.new_class_A();
local inst_b = app.new_class_B();
-- this will call the '__eq' in B's metatable
if( inst_b == inst_a )then
end
-- this will call the '__eq' in A's metatable
if( inst_a == inst_b )then
end
while calling __eq, luabridge will not search the class's parent's metadata table, so you should regist again to A's subclass!
hope it will help you!
sorry for my poor english!

How to register member function with lua-function parameter using luabind?

I need to register a member function using luabind which is supposed to take a lua-function as parameter. For any normal function I would usually just do this:
int SomeLuaFunction(lua_State *l)
{
luaL_checkfunction(l,1);
int fc = luaL_ref(l,LUA_REGISTRYINDEX);
[...]
}
Luabind however uses the parameter list, so I'm unsure how to tell it I'm expecting a function:
void Lua_ALSound_CallOnStateChanged(lua_State *l,boost::shared_ptr<ALSound> pAl,<function-parameter?>)
{
[...]
}
lua_bind(luabind::class_<ALSound COMMA boost::shared_ptr<ALSound>>("ALSound")
.def("CallOnStateChanged",&Lua_ALSound_CallOnStateChanged)
);
(Only the relevant part of the code is shown here, lua_bind is using luabind::module)
lua-example of what I'm trying to accomplish:
local al = ALSound() -- I'm aware this wouldn't work since I haven't defined a constructor
al:CallOnStateChanged(function()
[...]
end)
Perhaps there is a way to add additional functions to an already registered class without luabind? Any suggestions would be appreciated.
If you want to be able to have a function that takes Lua objects as parameters, you should have the function take a luabind::object as a parameter. Then you can check to see if it's a function and call it if it is.

Using functions from classes

I am learning C++ and very new at using classes, and I am getting very confused in trying to use them. I am trying to convert my existing code (which used structs) so that it uses classes - so while I know what I am trying to do I don't know if I'm doing it correctly.
I was told that when using functions from the class, I first need to instantiate an object of the class. So what I have tried (a snippet) in my main function is:
int main()// line 1
{
string message_fr_client = "test"; //line2
msgInfo message_processed; //line 3
message_processed.incMsgClass(message_fr_client); //line 4
if (!message_processed.priority_check(qos_levels, message_processed)) //line 5
cout << "failure: priority level out of bounds\n"; //line 6
return 0; //line 7
}
Could you help me clarify if my following assumptions are correct? The compiler is not showing any error and so I don't know if it is error-free, or if there are ones lurking beneath.
At line 4, is the function incMsgClass being performed on the string message_fr_client and returning the resultant (and modified) message_processed?
At line 5, the function priority_check is being performed on the message_processed and returning a boolean?
In my class definition, I have a function getPath that is meant to modify the value of nodePath - is it just a matter of using message_processed.getPath(/*arguments*/)?
I haven't included the body of the functions because I know they work - I would just like to find out how the class functions interact. Please let me know if I can be clearer - just trying to clear up some confusion here.
Here is my class:
#ifndef clientMsgHandling_H
#define clientMsgHandling_H
#include <list>
#include <map>
#include <queue>
class msgInfo
{
public:
msgInfo();
msgInfo(int, int, int, std::string, std::list<int>);
/*classifying message*/
msgInfo incMsgClass(std::string original_msg);
/*message error checks*/
bool priority_check(int syst_priority, msgInfo msg); //check that message is within qos levels
bool route_check(std::map<std::pair<int, int>, int> route_table, msgInfo msg); //check that route exists
void getPath(msgInfo msg, std::map<std::pair<int, int>, int> route_info, int max_hop);
private:
int source_id;
int dest_id;
int priority;
std::string payload;
std::list<int> nodePath;
};
#endif
While it may compile (and even run), there are a few oddities with the code as shown:-
First off, class methods know which object they are operating on - so your priority_check and route_check methods probably don't need msgInfo as a parameter.,
for example, your old non-class function might be like this
bool priority_check(int p, msgInfo msg)
{
return msg.priority < p;
}
But the new one should look like this:
bool msgInfo::priority_check(int p)
{
return priority < p;
}
Also, incMsgClass is a bit odd, as it's a non-static class method that returns a msgInfo object. It's difficult to tell without understanding what it's supposed to do, but it seems possible that this function should actually be a constructor, rather than a regular method.
One other thing is that you're currently passing a msgInfo by value to those methods. So if the method needed to modify the passed msgInfo, it would not have any effect. It's generally better to pass objects by reference or const reference to other methods. So, back to the previous non-method example, it should really be this.
bool priority_check(int p, const msgInfo &msg)
...
But, as I said, you probably don't need the msgInfo parameters anyway.
At line 4, is the function incMsgClass being performed on the string message_fr_client
Yes
and returning the resultant (and modified) message_processed?
Whatever it's returning, you're ignoring the return value. It can modify the object itself, yes, because the function is not const.
At line 5, the function priority_check is being performed on the message_processed and returning a boolean?
Yes
In my class definition, I have a function getPath that is meant to modify the value of nodePath - is it just a matter of using message_processed.getPath(/arguments/)?
If a member function is intended to modify one of the class members, it's just a matter of not marking that function const
Hard to tell without implementation-details, but here we go:
I. You are passing a std::string as value (C++ is call-by-value by default), so you get a copy of the std::string in your method. If you want to work on the object you passed and manipulate it, use a reference on the object, like
msgInfo incMsgClass(std::string& original_msg); // notice the ampersand
then you can change your signature to
void incMsgClass(std::string& original_msg);
as you don't need to return the std::string you passed.
II. Yes, at least according to your signature
III. Can see a node_path only as a member.
For all your questions, see C++-FAQ.
Your basic assumptions are correct.
message_processed.incMsgClass(message_fr_client); //line 4
This line is not correct. The function you call returns msgInfo which is simply dropped. You should assign it to something. But it is not as it is usually done. You should make it a constructor of msgInfo, like
class msgInfo
{
public:
msgInfo(std::string original_msg);
...
}
Then you could call it like this
msgInfo message_processed(message_fr_client);
That line would create a msgInfo that is already properly initialized.
There is another pattern for creating class instances - static creating function. In your case you could mark incMsgClass static and then call it like
msgInfo message_processed = msgInfo.incMsgClass(message_fr_client);
I seriously doubt you need this pattern here, so I'd advise to move to constructor.
As of other functions, I see no problems there. Just note that all member functions not marked as const can modify the object they are called on. So, you don't need to pass this object explicitly. For functions a pointer to the object they are called on is available by name this. Also the functions can access all class variables as if these variables are global for normal (non-member) functions.

Specific actionscript functions for a c++ progammer

I am coming from the C++ world and i want to do some simple stuff with Actionscript 3.0.
Have search around this site and google and haven't found a universally accepted way to do so. I will give you the C++ code of the analogous of what I am trying to do in Actionscript 3.0.
Pass by reference:
void somefunction (string &passvariable);
Create instance of, deep copy:
string something;
string somethingelse;
something = "randomtext";
somethingelse = something;
Pass by reference
Every object is passed by reference. As far as I know, there are no explicit & address of or * dereference operators. Actionscript is a higher level language than that.
Primitive types (and Strings are primitive - see link) are Immutable in Actionscript, so pass by value / pass by reference are effectively the same.
Deep Copy / Instance of
ObjectUtil.clone / ObjectUtil.copy will create sometimes-deep copies of Objects, if you're working in Flex. I usually don't rely on it for anything deep, however. In most cases you will want to create your own clone style method to create a deep copy.
A generic, flexible clone method can be found here
The rules for pass as reference are different for simple data types like string and number than they are for objects and complex data types.
If you are passing a string to a function, it creates a copy, leaving the original untouched.
So to pass by reference, try creating an object:
var str:Object = {string:"foo"};
passByref(str);
trace(str.string);
private function passByref(str:Object):void
{
str.string = str.string + "bar";
trace("inside", str);
}
As for deep object cloning, this works great:
package
{
import flash.utils.ByteArray;
public class DeepCopyUtil
{
public static function clone (source : Object) : *
{
var array : ByteArray = new ByteArray ();
array.writeObject (source);
array.position = 0;
return array.readObject ();
}
}
}
Credit where credit is due:
http://cookbooks.adobe.com/post_How_to_create_deep_copies_of_objects_and_arrays-19261.html
In Actionscript you have to define all things with function, var or const.
You should define the (return type) after the variable name, like var:String
Creating a function
function someFunction (var:String):void
{
}
Copy a string
var something:String;
var somethingElse:String;
something = "randomtext";
somethingelse = something;