We have a number of CPPUNIT test suites, and each suite of tests will have their own setUp()/tearDown(), what I am looking to do is have a common setUp()/tearDown() across all of the suites. As I understand it for a given suite I have a setUp() and Teardown() that is run prior to each test in the suite
e.g. for suite A we have:
suiteA - setUp();
suiteA - test1();
suiteA - tearDown();
suiteA - setUp();
suiteA - test2();
suiteA - tearDown();
....
and for suite B we would have:
suiteB - setUp();
suiteB - test1();
suiteB - tearDown();
suiteB - setUp();
suiteB - test2();
suiteB - tearDown();
....
What I'd like would be something like is something like
commonSetUp();
suiteA - setUp();
suiteA - test1();
suiteA - tearDown();
commonSetUp();
suiteA - setUp();
suiteA - test2();
suiteA - tearDown();
commonSetUp();
suiteB - setUp();
suiteB - test1();
suiteB - tearDown();
commonSetUp();
suiteB - setUp();
suiteB - test2();
suiteB - tearDown();
We solve the problem by not using cppunit::TestFixture directly. We have several classes inheriting from cppunit::TestFixture that implement setUp and tearDown (and also provide some common test code). Each test class now inherits from one of our own classes doing the setUp and tearDown.
If necessary you can overwrite the setUp/tearDown later in a class and if necessary call the base class setUp/tearDown.
Related
I'm trying to mock a simple function from the Linux standard library. strerror() returns the error message from an errno. This is my library with the function to mock:
~$ cat mylib.c
#include <string.h>
#include <stdio.h>
int myStrerror()
{
int error_number = 0;
char* buffer = strerror(error_number);
fprintf(stdout, "Returned string = '%s'\n", buffer);
return 0;
}
#if defined (EXECUTABLE)
int main(int argc, char **argv)
{
return myStrerror();
}
#endif
~$ g++ -pedantic-errors -Wall -c mylib.c
This is my google test:
~$ cat test_mylib.cpp
#include "gtest/gtest.h"
#include "gmock/gmock.h"
int myStrerror();
class strerrorMock {
public:
MOCK_METHOD(char*, strerror, (int));
};
strerrorMock strerrorMockObj;
char *strerror(int error_number) {
return strerrorMockObj.strerror(error_number);
}
TEST(MockTestSuite, strerror)
{
using ::testing::Return;
char response[] = "mocked strerror function";
EXPECT_CALL(strerrorMockObj, strerror(0))
.WillOnce(Return(response));
EXPECT_EQ(myStrerror(), 0);
::testing::Mock::VerifyAndClearExpectations(&strerrorMockObj);
}
int main(int argc, char **argv) {
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
~$ g++ -pedantic-errors -Wall \
-o test_mylib.a \
-I"$BUILD_DIR"/googletest-src/googletest/include \
-I"$BUILD_DIR"/googletest-src/googlemock/include \
test_mylib.cpp \
"$BUILD_DIR"/lib/libgtestd.a \
"$BUILD_DIR"/lib/libgmockd.a \
./mylib.o \
-lpthread
This is what it returns normally:
~$ ./mylib.a
Returned string = 'Success'
and Running the test gives this:
~$ ./test_mylib.a
[==========] Running 1 test from 1 test suite.
[----------] Global test environment set-up.
[----------] 1 test from MockTestSuite
[ RUN ] MockTestSuite.strerror
Returned string = 'mocked strerror function'
[ OK ] MockTestSuite.strerror (0 ms)
[----------] 1 test from MockTestSuite (0 ms total)
[----------] Global test environment tear-down
[==========] 1 test from 1 test suite ran. (0 ms total)
[ PASSED ] 1 test.
test_mylib.cpp:32: ERROR: this mock object (used in test MockTestSuite.strerror) should be deleted but never is. Its address is #0x56114aa239e0.
ERROR: 1 leaked mock object found at program exit. Expectations on a mock object are verified when the object is destructed. Leaking a mock means that its expectations aren't verified, which is usually a test bug. If you really intend to leak a mock, you can suppress this error using testing::Mock::AllowLeak(mock_object), or you may use a fake or stub instead of a mock.
What have I to do to avoid the memory leak?
The problem is that we use a free global function strerror() from the system library. It isn't really mocked by an interface as usual with Googlemock. So we do not need an Interface. We have to cover the mocked function with also a free function that must be global to be on the same scope than the system function because it shall replace it. This is what we do with:
strerrorMock strerrorMockObj;
char* strerror(int error_number) {
return strerrorMockObj.strerror(error_number);
}
Here the instance strerrorMockObj of the mock is also in the global scope to be callable within the function. But obviously Googletest cannot delete a global mock object as noted in the error message. One solution I have found is to instantiate the mock object within the test macro as usual and store a global pointer to it so the function can address it:
strerrorMock* ptrStrerrorMockObj;
char* strerror(int error_number) {
return ptrStrerrorMockObj->strerror(error_number);
}
TEST(MockTestSuite, strerror)
{
strerrorMock strerrorMockObj;
ptrStrerrorMockObj = &strerrorMockObj;
...
}
Then the complete test program without complaining a memory leak looks like this:
~$ cat test_strerror.cpp
#include "gtest/gtest.h"
#include "gmock/gmock.h"
int myStrerror();
class strerrorMock {
public:
MOCK_METHOD(char*, strerror, (int));
};
strerrorMock* ptrStrerrorMockObj;
char* strerror(int error_number) {
return ptrStrerrorMockObj->strerror(error_number);
}
TEST(MockTestSuite, strerror)
{
using ::testing::Return;
strerrorMock strerrorMockObj;
ptrStrerrorMockObj = &strerrorMockObj;
char mockedstr[] = "mocked strerror function";
EXPECT_CALL(strerrorMockObj, strerror(0))
.WillOnce(Return(mockedstr));
EXPECT_EQ(myStrerror(), 0);
}
int main(int argc, char **argv) {
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
After some month using the solution of my first answer on several platforms I found that it is not very stable. In particular on MS Windows I had trouble that GoogleMock does not always find the mocking function. So I decided to accept minimal modification of the production code and use a wrapper class for the free system functions as recommended by googletest.
With the following I only have to add a header file to the production code and change its system calls for example
# from
fd = fopen("openclose.txt", "a");
# to
fd = stdioif->fopen("openclose.txt", "a");
On Microsoft Windows I have cloned googletest from github built it using powershell with settings cmake -S . -B build then cmake --build build --config MinSizeRel and stay in its root directory using this structure:
├── build
│ └── lib
│ └── MinSizeRel
│ ├── gmock.lib
│ ├── gmock_main.lib
│ ├── gtest.lib
│ └── gtest_main.lib
├── include
│ └── stdioif.h
├── src
│ ├── main.cpp
│ ├── openclose.cpp
│ └── test_openclose.cpp
├── main.exe
├── main.obj
├── openclose.txt
├── test_openclose.exe
└── test_openclose.obj
Here is the header file:
#ifndef INCLUDE_STDIOIF_H
#define INCLUDE_STDIOIF_H
#include <stdio.h>
class Istdio {
// Interface to stdio system calls
public:
virtual ~Istdio() {}
virtual FILE* fopen(const char* pathname, const char* mode) = 0;
virtual int fprintf(FILE* stream, const char* format) = 0;
virtual int fclose(FILE* stream) = 0;
};
// Global pointer to the current object (real or mocked), will be set by the
// constructor of the respective object.
Istdio* stdioif;
class Cstdio : public Istdio {
// Real class to call the system functions.
public:
virtual ~Cstdio() {}
// With the constructor initialize the pointer to the interface that may be
// overwritten to point to a mock object instead.
Cstdio() { stdioif = this; }
FILE* fopen(const char* pathname, const char* mode) override {
return ::fopen(pathname, mode);
}
int fprintf(FILE* stream, const char* format) override {
return ::fprintf(stream, format);
}
int fclose(FILE* stream) override {
}
};
// This is the instance to call the system functions. This object is called
// with its pointer stdioif (see above) that is initialzed with the
// constructor. That pointer can be overwritten to point to a mock object
// instead.
Cstdio stdioObj;
/*
* In the production code you must call it with, e.g.:
stdioif->fopen(...)
* The following class should be coppied to the test source. It is not a good
* idea to move it here to the header. It uses googletest macros and you always
* hove to compile the code with googletest even for production and not used.
class Mock_stdio : public Istdio {
// Class to mock the free system functions.
public:
virtual ~Mock_stdio() {}
Mock_stdio() { stdioif = this; }
MOCK_METHOD(FILE*, fopen, (const char* pathname, const char* mode), (override));
MOCK_METHOD(int, fprintf, (FILE* stream, const char* format), (override));
MOCK_METHOD(int, fclose, (FILE* stream), (override));
};
* In a gtest you will instantiate the Mock class, prefered as protected member
* variable for the whole testsuite:
Mock_stdio mocked_stdio;
* and call it with: mocked_stdio.fopen(...) (prefered)
* or stdioif->fopen(...)
*/
#endif // INCLUDE_STDIOIF_H
This is the simple example program:
#include "stdioif.h"
#include <iostream>
int openclose() {
FILE* fd = nullptr;
int rc = 0;
fd = stdioif->fopen("openclose.txt", "a");
if(fd == NULL) {
std::cerr << "Error opening file\n";
return 1;
}
rc = stdioif->fprintf(fd, "hello world :-)\n");
if(rc < 0) {
std::cerr << "Error appending to file with return code: " << rc << "\n";
stdioif->fclose(fd);
return rc;
}
rc = stdioif->fclose(fd);
if(rc) {
std::cerr << "Error closing file with return code: " << rc << "\n";
return rc;
}
std::cout << "done.\n";
return 0;
}
I execute it with:
#include "src/openclose.cpp"
int main() {
return openclose();
The test program looks like this:
#include "gtest/gtest.h"
#include "gmock/gmock.h"
#include "stdioif.h"
#include "src/openclose.cpp"
using ::testing::_;
using ::testing::Return;
class Mock_stdio : public Istdio {
// Class to mock the free system functions.
public:
virtual ~Mock_stdio() {}
Mock_stdio() { stdioif = this; }
MOCK_METHOD(FILE*, fopen, (const char* pathname, const char* mode), (override));
MOCK_METHOD(int, fprintf, (FILE* stream, const char* format), (override));
MOCK_METHOD(int, fclose, (FILE* stream), (override));
};
class OpenCloseTestSuite: public ::testing::Test {
protected:
// Member variables of the whole testsuite: instantiate the mock objects.
Mock_stdio mocked_stdio;
};
TEST_F(OpenCloseTestSuite, open_close) {
EXPECT_CALL(mocked_stdio, fopen(_, _))
.WillOnce(Return((FILE*)0x123456abcdef));
EXPECT_CALL(mocked_stdio, fprintf(_,_))
.WillOnce(Return(-1));
EXPECT_CALL(mocked_stdio, fclose(_)).Times(1);
// process unit
EXPECT_EQ(openclose(), 0);
}
int main(int argc, char** argv) {
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
To compile it on Microsoft Windows I use:
cl -nologo /EHsc -I. -I.\include -I.\googletest\include -I.\googlemock\include .\build\lib\MinSizeRel\gtest.lib .\build\lib\MinSizeRel\gmock.lib .\src\[main.cpp | test_openclose.cpp]
i'm not able to find answer in any stackoverflow topic. I have faced with Threads and Class, i want to use Class controller variables and actions, in global *.m file. without attached second Class.
here is code:
Controller.h
#import <Cocoa/Cocoa.h>
#interface Controller : NSObject
{
IBOutlet NSWindow *Main;
IBOutlet NSButton *myButton;
}
- (void)awakeFromNib;
- (IBAction)action:(id)sender;
- (IBAction)Display(id)sender;
#end
Controller.m
#import "Controller.h"
#implementation Controller
- (void)awakeFromNib
{
//At this point i can reach any variable from Controller.h
}
- (IBAction)Display:(id)sender
{
//Same, i can reach any variable from Controller.h
}
//After closing "}" and starting from new line, i can't call [Display] or anything else from Controller.h, my thread code goes here , and i want to write thread to call Display, or use awakeFromNib variables, strings, actions.
Thread code
#include assert.h
#include pthread.h
void* PosixThreadMainRoutine(void* data)
{
// I want to call here, example [Display click:self];
// but i only see [Controller]...
int ac = 0;
while (ac < 8)
{
sleep(1);
printf("Test");
ac++;
}
return NULL;
}
void LaunchThread()
{
// Create the thread using POSIX routines.
pthread_attr_t attr;
pthread_t posixThreadID;
int returnVal;
returnVal = pthread_attr_init(&attr);
assert(!returnVal);
returnVal = pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
assert(!returnVal);
int threadError = pthread_create(&posixThreadID, &attr, &PosixThreadMainRoutine, NULL);
returnVal = pthread_attr_destroy(&attr);
assert(!returnVal);
if (threadError != 0)
{
// Report an error.
}
}
#end
Thread code works 100%, but i can't call any variable or function in PosixThreadMainRoutine, can some one explain how to do it?
`
If you want to execute code in separated thread with accesing to #interface methods/variables its better to use:
[NSThread detachNewThreadSelector:#selector(Display:) toTarget:self withObject:t];
or
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_apply(10, queue, ^(size_t i) {
///Thread code here
});
In your example unclear - what is [Display click:self]; As I see Display - its method but not interface. Also PosixThreadMainRoutine() are not instance or class method. That is why you cant invoke call method. In general you dont have access because compiler dont know interface with name Dispaly and dont know declaration of click: method.
I sugest you next article: From C++ to Objective-C
Controller.m
I deleted thread, and i used this example:
[NSThread detachNewThreadSelector:#selector(Display:) toTarget:self withObject:nil];
- (IBAction)action:(id)sender{
[NSThread detachNewThreadSelector:#selector(Display:) toTarget:self withObject:nil];
}
It works like charm! i will save code , if someone knows answer i will try in currect situation.
I am trying to make c++11 interruptable thread, but always failed on template arg issue.
I compiled the following code under Visual Studio 2013, and always got errors like Args has not been declared. After trying to modify some parts of it, I even caused a MS compiler crash.
class interruptible_thread
{
public:
template <class Function, class... Args>
interruptible_thread(typename Function&& _fun, Args... _args)
: _thread([](std::atomic_bool &f, Function&& fun, Args... args)
{
f.store(false);
// put interrupt flag ptr into TLS table
auto gd = std::this_thread::detail::thread_guard(&f);
try{
fun(std::forward<Args>(args)...);
}
catch (interrupt_thread_exception &)
{
// log thread exit info in debug
}
catch (...)
{
// user exception handler
}
},
_flag,
std::forward<Function>(_fun),
std::forward<Args>(_args)...
)
{}
/* ... */
};
void somefun(int i){}
interruptible_thread myt(somefun,1);
construction with no args works well:
template <class Function >
explicit interruptible_thread(Function&& fun) :
_thread([&]()
{
_flag.store(false);
// put interrupt flag ptr into TLS table
auto gd = std::this_thread::detail::thread_guard(&_flag);
try{
// user function
fun();
}
catch (interrupt_thread_exception &)
{
// log thread exit info in debug
}
catch (...)
{
// user exception handler
}
}
){}
I've just started experiencing with thread and can't get some basics. How can i write to Console from thread with interval say 10 msec? So i have a thread class:
public ref class SecThr
{
public:
DateTime^ dt;
void getdate()
{
dt= DateTime::Now;
Console::WriteLine(dt->Hour+":"+dt->Minute+":"+dt->Second);
}
};
int main()
{
Console::WriteLine("Hello!");
SecThr^ thrcl=gcnew SecThr;
Thread^ o1=gcnew Thread(gcnew ThreadStart(SecThr,&thrcl::getdate));
}
I cannot compile it in my Visual c++ 2010 c++ cli, get a lot of errors C3924, C2825, C2146
You are just writing incorrect C++/CLI code. The most obvious mistakes:
missing using namespace directives for the classes you use, like System::Threading, required if you don't write System::Threading::Thread in full.
using the ^ hat on value types like DateTime, not signaled as a compile error but very detrimental to program efficiency, it will cause the value to be boxed.
not constructing a delegate object correctly, first argument is the target object, second argument is the function pointer.
Rewriting it so it works:
using namespace System;
using namespace System::Threading;
public ref class SecThr
{
DateTime dt;
public:
void getdate() {
dt= DateTime::Now;
Console::WriteLine(dt.Hour + ":" + dt.Minute + ":" + dt.Second);
}
};
int main(array<System::String ^> ^args)
{
Console::WriteLine("Hello!");
SecThr^ thrcl=gcnew SecThr;
Thread^ o1=gcnew Thread(gcnew ThreadStart(thrcl, &SecThr::getdate));
o1->Start();
o1->Join();
Console::ReadKey();
}
Platform: Qt 4.8.2 (built from source using MinGW x64), Win 7
I'm using QRunnable to separate long running tasks from main GUI thread, and I sometimes experience random crash/strange behavior with no traceable errors. Please help to provide suggestions on what/how to debug. Thanks
Runner class: multi-inherit for signal/slot connection to main window
class MyRunner : public QObject, public QRunnable
{
Q_OBJECT
Q_SIGNALS:
void feedbackLog(QString text);
void finished();
public:
explicit MyRunner(/* some args */) { /* some initialization */ }
void run() {
stopped_ = false;
for (int run = 0; run < SOME_COUNT; run++) {
Q_EMIT feedbackLog("Resetting everything ...");
if (stopped_) return;
/* start the daily interaction until the epidemic is over */
do
{
if (stopped_) return;
lengthySubTaskA();
if (stopped_) return;
lengthySubTaskB();
if (stopped_) return;
lengthySubTaskC();
}
while (conditionNotReached());
} // end: for(run)
stopped_ = true;
Q_EMIT finished();
}
bool isStopped() { return stopped_; }
public Q_SLOTS:
void stop() {
Q_EMIT feedbackLog("Cancel ...");
stopped_ = true;
}
private:
bool stopped_;
/** other class members follow */
};
MainWindow segment
void MainWindow::callMyRunnable() {
runner_ = new MyRunner(/* args */); // runner_ is class member */
runner_->setAutoDelete(true); // (a)
progress_dialog_ = new QProgressDialog("Running", "Cancel", 0, 0, this);
progress_dialog_->setAttribute(Qt::WA_DeleteOnClose);
connect(runner_, SIGNAL(feedbackLog(QString)), SLOT(logMessage(QString)));
connect(runner_, SIGNAL(finished()), SLOT(endLengthyJob()));
connect(runner_, SIGNAL(finished()), progress_dialog_, SLOT(close()));
connect(progress_dialog_, SIGNAL(canceled()), runner_, SLOT(stop()));
connect(progress_dialog_, SIGNAL(canceled()), SLOT(endLengthyJob()));
QThreadPool::globalInstance()->start(runner_);
progress_dialog_->show();
/* flu_runner_->deleteLater(); */ // (b)
}
void MainWindow::closeEvent(QCloseEvent *e) {
if (runner_ && !runner_->isStopped()) runner_->stop(); // (c)
if (QThreadPool::globalInstance()->activeThreadCount())
{
/* display a dialog to notify user about shutdown */
Dialog::WaitDialog dlg(5 * 1000);
dlg.exec();
}
event->accept();
} // end_event(MainWindow::closeEvent)
1) If I disable autodelete at (a), should I add statement (b) to prevent leaking? Or any better way to handle the leaking?
2) Sometimes, when the Runnable task completed, I cannot close the app normally (neither [x] button nor Alt-F4 work), and I have to kill the app from within QtCreator (I'm debugging, right?). What would be possible cause to this?
[Edit]: 3) For un-closable mainwindow, sometimes it happens after I cancelled the task handled by MyRunner class, will this be a possible cause?
[Edit]: I added qDebug() statement around (c), and found that it stop at (c) and refuse to proceed to display the waiting dialog in case if the [x] button is not responding.
Thanks.
The problem is solved by changing the 'close-strategy' of the mainwindow: remove 'auto-killing' and force user to wait for spawned thread. Variables runner_ and progress_dialog_ are now localized to the function callMyRunnable()