When I analyze gcov results for the following code (after using c++filt to demangle), I see two FooTest::~FooTest() in the coverage information file, both mapped to the same line number. One is marked as called and the other is not. Note: No compiler optimizations are used (i.e. -O0).
#include "gtest/gtest.h"
struct FooTest : ::testing::Test {
~FooTest() = default;
};
TEST_F(FooTest, run) {}
int main(int argc, char* argv[]) {
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
If I put the declaration of FooTest in the unnamed namespace, I only see 1 destructor (anonymous namespace)::FooTest::~FooTest() in the coverage info.
#include "gtest/gtest.h"
namespace {
struct FooTest : ::testing::Test {
~FooTest() = default;
};
}
TEST_F(FooTest, run) {}
int main(int argc, char* argv[]) {
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
I realize that the visibility of FooTest is different when placed in the unnamed namespace. But, I wouldn't have expected that to cause the difference since the translation unit is compiled without optimizations.
What precisely is happening to cause gcov to report two destructors with the same signature to exist when the test fixture is not placed in the unnamed namespace?
The link posted by Eljay, https://stackoverflow.com/a/6614369/4641116, contains an explanation as to why multiple dtors are created.
In the code snippit above, the base object destructor (D2) is called by the derived test class defined via the TEST_F macro. The deleting destructor (D0) is not called by the program and hence not reported as covered by GCOV.
When the class has default visibility, the compiler cannot prove that no one outside the translation unit might require the deleting destructor, which is why it is created.
I am using Google test framework for C++. Each file includes a config.hpp which defined a global configuration variable. I would like to define my config in a variable, not a compile-time const or constexpr. How can I define the dependencies to have the same variable in different files that are linked together? Do I have to use a singleton? Can I avoid that? Is there a better recommended way to use multiple test files xUnit style?
My config file: config.hpp:
#pragma once
struct {
const float tolerance = 0.001;
// ...
} CONFIG_VAR;
Each test *.cpp source file is like:
#include "gtest/gtest.h"
#include "core/config.hpp"
TEST(a, b) { ... }
My main file:
#include "gtest/gtest.h"
int main(int argc, char **argv) {
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
I compile and link using:
em++ -I $GTEST_ROOT/googletest/include main_all_tests.cpp test_*.cpp
PS. My problem is multiple definition of the variable CONFIG_VAR.
My solution is based on a related question.
Everything you need is right here at the Google Test's official repository on GitHub.
Anyway, to sharing something in the same file test you do it like that:
class YourTestCase : public ::testing::Test
{
protected:
virtual void SetUp()
{
globalObject = new YourObject();
}
virtual void TearDown() {
delete globalObject;
globalObject = nullptr;
}
Object * globalObject = nullptr;
};
so, in your test cases:
TEST_F(YourTestCase, TestOne) {
ASSERT_EQ("your value here", globalObject->getValue());
}
TEST_F(YourTestCase, TestTwo) {
ASSERT_EQ("your value here", globalObject->getValue());
}
TEST_F(YourTestCase, TestThree) {
ASSERT_EQ("your value here", globalObject->getValue());
}
Note.: Pay attention to the function's name. It is TEST_F not TEST.
On the other hand, if what you want to do it is at the test program level ― sharing something among files, you will need to set up an environment object. Something like this:
Environment * AddGlobalTestEnvironment(Environment * env);
I have never worked with that before, so I can not tell you so much about it, but there is more information at that link I shared above. Usually, global variables make the code harder to read and may cause problems. You'd be better off avoiding them.
I get this error in a C++ file where I am writing some tests:
error: no member named 'Session' in namespace 'Catch'
testResult = Catch::Session().run(test_argc, test_argv);
~~~~~~~^
Looking at the catch.hpp single header file, I noticed that the code that should implement the Session() member function is greyed out, probably because of an #ifdef somewhere, which I cannot find.
Is there any macro to set to use the Session class?
Catch versions: 1.5.3 and 1.5.6.
Reference: https://github.com/philsquared/Catch/blob/master/docs/own-main.md
You're attempting to call the constructor of Catch::Session from a file where you're not defining your own main to execute. According to the documentation on defining your own main, there is supposed to be only one instance of Catch::Session:
Catch::Session session; // There must be exactly once instance
It's likely Catch is preventing construction of Catch::Session in translation units where it can't be used in a custom main definition (since that's where it's supposed to be used), to prevent exactly the mistake you've made from compiling.
Reference to https://github.com/catchorg/Catch2/blob/master/docs/own-main.md
You can only provide main in the same file you defined CATCH_CONFIG_RUNNER.
#define CATCH_CONFIG_RUNNER
#include "catch.hpp"
int main( int argc, char* argv[] ) {
// global setup...
int result = Catch::Session().run( argc, argv );
// global clean-up...
return result;
}
I need to temporarily put a main() function in my object to test alternate functionality (beyond a simple unit test), but I keep having to comment out my main() function to run my unit tests.
Is there a #define _KEYWORD_ for CxxTest to allow this to happen automatically?
You simply need to encapsulate the offending code with a compiler directive based on the definition of the CXXTEST_RUNNING keyword.
For example:
class myClass {
public:
myClass () {}
};
#ifndef CXXTEST_RUNNING
int main (int argc, char *argv[]) {
// Temporary runner. Typically deleted upon completion
// of alternate functionality added later in the project.
}
#endif
In this case, when using the CxxTest framework the main() function will be ignored in favor of the main() created by the testing framework. Otherwise, the main() function you have provided will be used.
In order to ensure that some initialization code runs before main (using Arduino/avr-gcc) I have code such as the following:
class Init {
public:
Init() { initialize(); }
};
Init init;
Ideally I'd like to be able to simply write:
initialize();
but this doesn't compile...
Is there a less verbose way to achieve the same effect?
Note: the code is part of an Arduino sketch so the main function is automatically generated and cannot be modified (for example to call initialize before any other code).
Update: ideally the initialization would be performed in the setup function, but in this case there is other code depending on it which occurs before main.
You can use GCC's constructor attribute to ensure that it gets called before main():
void Init(void) __attribute__((constructor));
void Init(void) { /* code */ } // This will always run before main()
You can make the above very slightly shorter by giving "initialize" a return type, and using that to initialize a global variable:
int initialize();
int dummy = initialize();
However, you need to be careful with this, the standard does not guarantee that the above initialization (or the one for your init object) takes place before main is run (3.6.2/3):
It is implementation-defined whether or not the dynamic initialization (8.5, 9.4, 12.1, 12.6.1) of an object of namespace scope is done before the first statement of main.
The only thing that is guaranteed is that the initialization will take place before 'dummy' is ever used.
A more intrusive option (if it's possible) might be to use "-D main=avr_main" in your makefile. You could then add your own main as follows:
// Add a declaration for the main declared by the avr compiler.
int avr_main (int argc, const char * argv[]); // Needs to match exactly
#undef main
int main (int argc, const char * argv[])
{
initialize ();
return avr_main (argc, argv);
}
At least here you're guaranteed that the initialization will take place when you expect.
Here's a somewhat evil method of achieving this:
#include <stdio.h>
static int bar = 0;
int __real_main(int argc, char **argv);
int __wrap_main(int argc, char **argv)
{
bar = 1;
return __real_main(argc, argv);
}
int main(int argc, char **argv)
{
printf("bar %d\n",bar);
return 0;
}
Add the following to the linker flags: --wrap main
eg.
gcc -Xlinker --wrap -Xlinker main a.c
The linker will replace all calls to main with calls to __wrap_main, see the ld man page on --wrap
Your solution in simple and clean. What you can additionally do is to put your code in anonymous namespace. I don't see any need to make it better than that :)
If you are using the Arduino environment, is there any reason you can't place it in the setup method?
Of course, this is after the Arduino-specific hardware setup, so if you have such low-level stuff that it really has to go before main, then you need some constructor magic.
UPDATE:
Ok, if it has to be done before the main I think the only way is to use a constructor like you already do.
You can always make a preprocessor macro of it:
#define RUN_EARLY(code) \
namespace { \
class Init { \
Init() { code; } \
}; \
Init init; \
}
Now this should work:
RUN_EARLY(initialize())
But it's not really making things shorter, just moving the verbose code around.
You can use the ".init*" sections to add C code to be run before main() (and even the C runtime). These sections are linked into the executable at the end and called up at specific time during program initialization. You can get the list here:
http://www.nongnu.org/avr-libc/user-manual/mem_sections.html
.init1 for example is weakly bound to __init(), so if you define __init(), it will be linked and called first thing. However, the stack hasn't been setup, so you have to be careful in what you do (only use register8_t variable, not call any functions).
Use static members of classes. They are initialized before entering to main. The disadvantage is that you can't control the order of the initialization of the static class members.
Here is your example transformed:
class Init {
private:
// Made the constructor private, so to avoid calling it in other situation
// than for the initialization of the static member.
Init() { initialize(); }
private:
static Init INIT;
};
Init Init::INIT;
Sure, you put this in one of your your header files, say preinit.h:
class Init { public: Init() { initialize(); } }; Init init;
and then, in one of your compilation units, put:
void initialize(void) {
// weave your magic here.
}
#include "preinit.h"
I know that's a kludge but I'm not aware of any portable way to do pre-main initialization without using a class constructor executed at file scope.
You should also be careful of including more than one of these initialization functions since I don't believe C++ dictates the order - it could be random.
I'm not sure of this "sketch" of which you speak but would it be possible to transform the main compilation unit with a script before having it passed to the compiler, something like:
awk '{print;if (substr($0,0,11) == "int main (") {print "initialize();"};}'
You can see how this would affect your program because:
echo '#include <stdio.h>
int main (void) {
int x = 1;
return 0;
}' | awk '{
print;
if (substr($0,0,11) == "int main (") {
print " initialize();"
}
}'
generates the following with the initialize() call added:
#include <stdio.h>
int main (void) {
initialize();
int x = 1;
return 0;
}
It may be that you can't post-process the generated file in which case you should ignore that final option, but that's what I'd be looking at first.
There is how I perform pre-main coding.
There are sever init sections executed before main, refers to http://www.nongnu.org/avr-libc/user-manual/mem_sections.html initN sections.
Anyhow, this only works on -O0 optimization for some reason. I still try to find out which option "optimized" my pre-main assembly code away.
static void
__attribute__ ((naked))
__attribute__ ((section (".init8"))) /* run this right before main */
__attribute__ ((unused)) /* Kill the unused function warning */
stack_init(void) {assembly stuff}
Update, it turns out I claimed this function is unused, leading to optimize the routine away. I was intended to kill function unused warning. It is fixed to used used attribute instead.