Matching certain function declarations from existing context in clang-tidy - c++

I would like to write a custom clang-tidy check to port code from cppunit to googletest.
class SomeTest: public CPPUNIT_NS::TestFixture {
CPPUNIT_TEST_SUITE(SomeTest);
CPPUNIT_TEST(shouldDoSomething);
CPPUNIT_TEST_SUITE_END();
...
protected:
void shouldDoSomething();
void otherFunction(int times = 0);
};
CPPUNITFRAMEWORK_TEST_SUITE_REGISTRATION(SomeTest);
...
void SomeTest::shouldDoSomething() {...}
void SomeTest::otherFunction(int) {}
I would like to be able to replace
void SomeTest::shouldDoSomething() {...}
with
TEST_F(SomeTest, shouldDoSomething) {...}
I can match a function name from CPPUNIT_TEST(...) macro with
stringLiteral(hasAncestor(callExpr(callee(functionDecl(hasName("getTestNameFor"))))))
but I have no idea whether it is possible to reuse this information to match the function declaration so I can actually replace it with googletest.

Related

c++ subclass access functions of parent class

I have the following Class structure:
class WiFiHandler{
public:
void doWiFiStuff();
};
class Machine {
public:
void doSomething();
WiFiHandler _wifiHandler;
};
Now the WiFiHandler::doWiFiStuff() receives a request which should trigger execution of Machine::doSomething().
However the Methods of Machine are not known to WifiHandler
How does this Subclass WiFiHandler execute Methods of its "Motherclass"?
As many design issues, there are many ways to achieve similar result, each with some advatages and disadvatages.
Other answers to your question mention good soultions.
I'd like to propose a different one, that might fit some systems.
This solution might be good if the following 2 conditions (which are related) are met:
Machine has multiple methods that WiFiHandler has to call.
Machine has a close association with WiFiHandler and it's OK from other design constraints that it will be dependent on it (despite the fact that it is contained by it).
In this case, WiFiHandler can hold a pointer to the Machine containing it.
In order to solve the problem of circular #includes, we can use a forward declaration.
Note that WiFiHandler.cpp includes Machine.h and thus can use any public method of Machine for its own implementation.
Code example:
// WiFiHandler.h:
class Machine; // forward declaration
class WiFiHandler {
Machine * m_pMyMachine;
public:
WiFiHandler(Machine * pMyMachine) : m_pMyMachine(pMyMachine) {}
void doWiFiStuff();
};
// Machine.h:
#include "WiFiHandler.h"
class Machine {
public:
Machine() : _wifiHandler(this) {}
void doSomething();
WiFiHandler _wifiHandler;
};
// WiFiHandler.cpp:
#include "WiFiHandler.h"
#include "Machine.h"
void WiFiHandler::doWiFiStuff()
{
m_pMyMachine->doSomething();
// ...
}
// Machine.cpp:
#include "Machine.h"
void Machine::doSomething()
{
// Do the machine stuff ...
}
Neither of those is a subclass or "parent" of the other - there is no inheritance.
The WiFiHandler is just a member of Machine and has no knowledge of any Machine's existence.
You need to give the WiFiHandler something to call in that function, and it's usually useful to make this more general than a specific Machine instance.
For instance, a callback function:
class WiFiHandler{
public:
WiFiHandler(std::function<void()> fun) : doIt(fun) {}
void doWiFiStuff() { doIt(); }
private:
std::function<void()> doIt;
};
class Machine {
public:
Machine() : _wifiHandler([this]() { doSomething(); }) {}
void doSomething() {}
WiFiHandler _wifiHandler;
};
This way, WiFiHandler doesn't need to care about changes to Machine or whether one exists at all.
Change doWiFiStuff() to
template< class R, class... Args >
void doWiFiStuff(std::function<R(Args...)> thing_to_do, Args... args);
so you can pass any function along to be called.

Writing C++ tests with "faking" some methods with an alternative implementation

I'm writing tests in C++ using googleTest and want to improve them.
I try to describe what I have and what I want to achieve:
I have a class A that has an instance of class B as a member like this:
class ClassA
{
public:
//Some functions
protected:
ClassB m_b;
};
class ClassB
{
void Init(const string &sArgument);
};
In my test I create an instance of ClassA and call a function of it. In this function the function Init() of m_b will be called.
Because Init() of ClassB makes something that I don't want to have in my test I want to call an alternate implementation. My first intention was to create an interface with the function Init() that is implemented by ClassB and by a new class that I create only for the test. Unfortunately to do this I have to create a pointer of the interface and to give it to ClassA.
__interface IB
{
void Init(const string &sArgument);
};
class ClassB : public IB
{
void Init(const string &sArgument) override;
};
class ClassA
{
public:
ClassA(IB* b) : m_b(b){}
//Some functions
protected:
*IB m_b;
};
For my test I create a new class:
class ClassBForTest : public IB
{
void Init(const string &sArgument) override;
};
This is not a good solution so I tried to find another way. What I actually found is the library Isolator++ by Typemock which works quite good. I can say that for all future instances of ClassB the method Init should be replaced with another one. And the best is that I don't have to make any changes in my ClassA. I just have to create a new one:
class ClassBForTest
{
void ISOLATOR_TESTABLE Init(const string &sArgument){}
};
In my test I use this:
ClassBForTest c;
ClassB* b = FAKE_ALL<ClassB>();
WHEN_CALLED(b->Init(ANY_VAL(string))).DoMemberFunctionInstead(&c, Init);
Unfortunately this library is not for free when I want to use it on a build server. So I'm searching for an alternative. As we used gMock in our other tests I tried to realize this with gmock but it didn't work yet. I know that this is not a good statement but I don't want code from you. I only want to know if this is possible with gMock (saying that an alternate implementation should be used without having the instance of ClassB at this point).
Alternatively I ask you for other free libraries I can use.
Thanks a lot in advance,
Michaela

How to Skip a Portion of the ”Code” in the source code while doing GoogleTest

I tried using a debug flag addition (GOOGLE_TEST) in the source code and defined it in the TEST/Makefile.am. but the things didn’t work. I am using C++ Language.
Note: I don’t want to change anything in the SRC Directory code which will affect the production code and its Makefile.am
Test Class in SRC Directory
class Common: public Thread {
public:
friend class test_common;
Common {
}
~Common () {
}
virtual void ThreadMain();
protected:
virtual void ProcessData(void);
};
void Common::ProcessData(void) {
#ifndef __GOOGLE_TEST__
while (1) { }
#endif
}
TESTCODE in test Directory
class test_common : public ::testing::Test {
};
TEST_F(test_common, create_common) {
Common commonObj();
commonObj. ProcessData ();
}
OUTPUT
GTest Stuck in the While loop part even after defining the flag in the test/makefile.am
Dont rely on the compilation flags, without affecting the production code use the GMOCK methods to get rid off the while (1) loop , the code can go like below:
TESTCODE:
class test_common : public ::testing::Test {
};
TEST_F(test_common, create_common) {
Common commonObj();
ON_CALL(mock_if, GetBool())
.WillByDefault(Return(true));
EXPECT_CALL(mock_if, GetBool())
.Times(AtLeast(1))
.WillOnce(Return(true))
.WillOnce(Return(false));
commonObj. ProcessData ();
}
ABSTRACT CODE:
class AbstractIf {
public:
AbstractIf (void) = default;
virtual ~AbstractIf (void) = default;
virtual bool GetBool() = 0;
};
MOCK CODE:
class MockIf : public AbstractIf {
public:
MOCK_METHOD0(GetBool,bool());
};
SOURCE CODE:
class Common: public Thread {
public:
friend class test_common;
Common {
}
~Common () {
}
virtual void ThreadMain();
protected:
virtual void ProcessData(void);
AbstractIf *prov_fl_if_;
};
void Common::ProcessData(void) {
while (prov_fl_if_->GetBool()) { }
}
By this way we can skip the part of the code we want without affecting the production code
There is no way to make a #define value from one compilation unit affect the compilation of another, previously compiled units. Given the list of things you have stipulated you don't want to do, you will have to use some form of runtime shenanigans.
You could make ProcessData take an argument that determines whether the loop should iterate:
void ProcessData(bool once=false);
void Common::ProcessData(bool once) {
do {
// ... your loop code
} while (!once);
}
Or you could use a global variable that is defined in the module with your main() in it, lets call it main.cpp.
Production main.cpp:
const bool g_isDebugMode = false;
Unit test main.cpp:
const bool g_isDebugMode = true;
main.h
extern const bool g_isDebugMode;
now you can write runtime tests against this variable.
do {
// your code
} while (g_isDebugMode == false);

Multiple header files in one class C++ (Arduino)

I have an class that includes methods from different header files like this:
#include "ICash.h"
#include "ILock.h"
class control: public ICash, public ILock
{
public:
control();
private:
void doSomething(int value);
};
So now when i make an instance of ICash through control class.
where in control.cpp the methodes are declared.
Is is possible to use the method doSomething from control throug the ICash interface?
thanks.
In control.cpp, for example, you can have this implementation code:
control::control() { /* ctor body */ }
void control::doSomething(int value)
{
// your code here
}
Then, somewhere, you can use a control instance via a pointer to ICash
ICash *cash = new control;
If doSomething was not private, you could use void doSomething(int) from this pointer cash like cash->doSomething(5) only if ICash also has a declaration (virtual or not) for void doSomething(int).
So in a nutshell, to be able to use doSomething from within a ICash, it has to be declared within ICash as well.
Note that when doSomething is declared in ICash and you redefine the method in control(overriding) you would want the declaration in ICash to be virtual.
I guess the methods are declared in their corresponding header classes, but you have to redefine them in your own class if you want them to do something useful.
doSomething in your control class is private method, and as such, won't be available outside its class at all. But you redefine one or more methods from ICash and ILock interfaces, you can call doSomething from within these methods, for example: suppose an interface has a method methodXXX:
class ISomething {
public:
virtual void callMe(int value);
}
class control: public ISomething {
public:
control();
void callMe(int value) {
return doSomething(value);
}
private:
void doSomething(int value);
}
void control::doSomething(int value) {
// do something :)
}
// somewhere later:
ISomething* something = new control();
something.callMe(5);//calls control.doSomething(5) internally

C++ Private Nested Abstract Class

So maybe this is a dumb question and I'm over thinking this, but I have the following situation. I am making a "class Shell" which can run abstract "class Action" objects. It is the only class that should create or use these objects. Action objects need access to the Shell to perform specific actions on it, but I'm trying to avoid adding public interfaces for this (no one else should be allowed to do that).
I originally had a simple (not so elegant)
class Shell
{
public:
bool checkThing();
// etc...
private:
bool _thing;
};
class Action
{
public:
virtual void execute( Shell &s )=0;
};
class ChangeAction : public Action
{
public:
void execute( Shell &s )
{
// requires friendship or public mutator!
s._thing = true;
}
};
So I considered a nested class Action, but I wanted to make it private (why let anyone else make concrete Actions except the Shell, right?)
class Shell
{
public:
bool checkThing();
// etc...
private:
bool _thing;
class Action;
};
class Shell::Action
{
public:
virtual void execute( Shell &s )=0;
};
class ChangeAction : public Shell::Action
{
public:
void execute( Shell &s )
{
// ok now!
s._thing = true;
}
};
But of course I can't inherit from Action any more (that makes sense, it's private). So that doesn't work.
So my question, should I just go with the first method and friendship or a public interface? Can I use something similar to the second method to keep that relationship with Actions and the Shell?
Do you have a better idea?
If the only code that needs to be able to see Action is Shell, one option would be to forward-declare Action in the header file but only define the class in the .cpp file. This would then let you declare as many Action subclasses as you'd like in the implementation file without letting anyone else subclass off of Action because no one else would have a complete class definition for Action. This also avoids any need for public interfaces or friend declarations - all the Action classes are declared in the global scope, but shielded from other files by virtue of being declared in the .cpp file.
Great question, by the way!
You can can use a combination of the methods: Basically just take all your classes from the first method and move them into the private section of the Shell class:
class Shell {
public:
bool checkThing(); // etc...
private:
bool _thing;
class Action {
public:
virtual void execute( Shell &s )=0;
};
class ChangeAction : public Action
{
public:
void execute( Shell &s )
{
// ok now! s._thing = true;
}
};
};