How to unit test C (with the help of code blocks)? - c

I have a task of unit testing C project for homework.
It's written in Code Blocks.
Here's one example from the code:
void ServerUserWrite(int Command) //Command "1" prints an extra row into server. For example addinga new user. it expects that the extra row with the correct data is already existing in the structure.
{
FILE *UserDataBase;
int i,j;
UserDataBase=fopen(UserDatabasePath,"w");
if(Command==1)
{ServerUserCount=ServerUserCount+1;}
fprintf(UserDataBase,"%d\n",ServerUserCount);
if(ServerUserCount>0)
{
for(i=0;i<ServerUserCount;i++)
{
fprintf(UserDataBase,"%d ",UserDB[i].UserID);
fprintf(UserDataBase,"%s ",UserDB[i].User);
fprintf(UserDataBase,"%d ",UserDB[i].UserPasswordLength);
fprintf(UserDataBase,"%d ",UserDB[i].Encrypter);
for (j=0;j<UserDB[i].UserPasswordLength;j++)
{fprintf(UserDataBase,"%d ",UserDB[i].Pass[j]);}
fprintf(UserDataBase,"%d ",UserDB[i].BackgroundColor);
fprintf(UserDataBase,"%d ",UserDB[i].ForegroundColor);
fprintf(UserDataBase,"%d ",UserDB[i].UnreadMessages);
fprintf(UserDataBase,"%d\n",UserDB[i].UnreadTweets);
}
}
fclose(UserDataBase);
}
Well the question is:
Is there any unit testing framework to combine with Code Blocks?
And how to do it?

Yes we use Check to unit test our C project too, there is no need to integrate to the IDE, it's more friendly to show the testing result as a plain text.
But there is a framework for C++ unit test which can combined with code block IDE:
Unit testing for Code Block

Don't know about Code Blocks, but you might wanna use check.h and follow this tutorial :
http://check.sourceforge.net/doc/check_html/check_3.html.
Writing test suites with it is pretty easy. I learnt about it looking at gstreamer-editing-services, may'be will you wanna have a look at their test suite:
http://cgit.freedesktop.org/gstreamer/gst-editing-services/tree/tests/check/ges
They reimplemented it but the way it works is basically the same.

The grand-daddy of all unit-testing in C questions is here:
Unit Testing C Code
Again, not specific to Code Blocks, but most of the strategies are standard C.

Related

Mocking/Faking static function within Unit Test Environment

I'm using cpputest to perform Unit Tests of c code.
In my source code under test I have a static function which I would like to be "redirected" to a "faked" version of the function when called from the unit test environment.
Let's say, I have somethig like this:
Source Code under test:
void my_main()
{
read(int8 address);
}
whereby;
static int8 read(int8 address)
{
return something;
}
Unit Test Environment:
TEST(MY_TESTS, READ)
{
my_main();
}
When calling my_main() within Unit Test environment, I would like to redirect the call of
read(int8 address)
to:
int8 fake_read(int8 address)
{
//do_something
}
What will be here the correct way? I tried it already with function pointer than injection of the dependency but it does not work.
Any idea?
Maybe you can utilize the linker to do this: Create two source files – one with the actual production code of the static function and one with the mock implementation.
For the test, link the 2nd one; and for running your application the 1st one.
Ancient question I know, but...
Look at the docs around mock_c() http://cpputest.github.io/mocking_manual.html#other_mock_support
int64_t GetTimeMS (void)
{
mock_c ()->actualCall ("GetTimeMS");
return (mock_c ()->returnValue ().value.longIntValue);
}

how to use the glade xml file to make an executable program

I am learning to use glade 3 to create a GUI.
However, the *.glade file is an xml file. I am not sure how to go forward from here. Google search is not really helping. There is a question already asked for same thing here Tool to convert .Glade (or xml) file to C source . However I am not really able to understand the answer given in that.
Can someone tell the basic flow of the development cycle using glade 3?
Design the UI in glade.
Generate the *.glade xml file.
AND THEN WHAT ????
How can the xml file be converted to an executable ?
A. Should I convert this xml file to a language (C) and compile the C code ?
B. Or is there a way for xml code to be directly converted to an ELF executable ?
I am trying to make the GUI for my own use. I use linux and want an ELF executable (like how I would get if I wrote the C code using gtk library and compiled it using gcc).
If we look at the Wikipedia page for Glade it has an entire section about how to use Glade in a program: with GtkBuilder. Now all that remains is to read the docs and you can begin using Glade. No offense, but I've never used Glade before and this is fairly clear in all docs. For example, here's Glade's homepage.
I would do something like this:
DerivedWindow::DerivedWindow()
{
mainBox = Gtk::manage(new Gtk::Box(Gtk::ORIENTATION_VERTICAL, 7));
builder = Gtk::Builder::create();
try {
builder->add_from_file("filename.glade");
} catch (Glib::Error& ex) {
errMsg("Window Builder Failed: " + ex.what());
}
Gtk::Box* box;
builder->get_widget("name of box inside main window", box);
if (!box) { this->destroy_(); return; }
box->unparent();
mainBox->pack_start(*box, Gtk::PACK_SHRINK);
//optional - if you want full access to particular widgets
builder->get_widget("name of widged id", widgetname);
//connect signals here...
add(*mainBox);
show_all();
}
Note this is Gtkmm 3+.
It is important you unparent the box you got from the glade file, so you can attach it to your derived window.

Implementation of time in Zynq

I'm trying to do a simple STANDALONE application for Zynq. I want to use the 'time.h' to manipulate date/time. I know that there is no hardware implementation on a stanalone BSP, but I want to wire it up on my own.
During compilation, when I call 'time(NULL)' I get a error, that there is no implementation of '_gettimeofday()'. I've found it in and implemented it according to the function definition, so that the errors disappear and everything looks ok, but when I run my project on hardware, I see only zeroes from time().
Can anybody help?
Regards,
G2
Ok, I've done some research, and found this link. This is almost what I'v been searching, but instead of '_times()' I needed '_gettimeofday()' and this is my implementation:
int _gettimeofday(struct timeval *__p, void *__tz)
{
__p->tv_sec = (systemUsCounter / 1000000);
__p->tv_usec = systemUsCounter;
return 0;
}
I left the '__tz' pointer with no chainges.
So this is basicly how to utilize 'time.h' in a standalone application on Zynq.

How to test legacy C code and check which branches where hit

I have a DLL which contains many large (1000+ line) functions. This code has lots of complex logic which I want to ensure doesn't get broken when its maintained so I created a test harness which dynamically loads this DLL and calls its API.
I would like to know a nice way of being able to test which branches of the code where hit within this API from my test harness. The only way I can think of doing this is as follows:
// Pseudo test code
void doTest()
{
loadDllToBeTested();
dll_api_function_1();
assert( dll_api_function_1_branches.branch1Hit == true );
unloadDllToBeTested();
}
// Real api in the C dll
struct dll_api_function_1_branches
{
bool branch1Hit;
}
dll_api_function_1_branches g_dll_api_function_1_branches;
int private_func1()
{
printf("Doing my private stuff\n");
return 1;
}
void dll_api_function_1(void)
{
if ( private_func1() )
{
printf("doing some stuff\n");
dll_api_function_1_branches.branch1Hit = true; // so the test code can check if we got here :(
}
else
{
printf("doing some other stuff\n");
}
// tons of other logic and branching...
}
Which is basically have a struct per function which has values set when certain branches are reached within the function. There would be a global exported instance of this struct which the test code would have to init to zero and then check after calling the API.
Also note that I'm using Visual Studio so tools like gcov can't be used here.
The LLVM project mentions the KLEE tool, which helps creating test cases to exercise all paths (and find bugs in the process). Some of it is strongly Unix-oriented, and it is a current research project (rough edges, some assembly required, and the other disclaimers).

During suite tests EasyMock says 0 matchers expected 1 recorded

So I've been using EasyMock's class extension for a while now. All of a sudden I'm getting this exception, but only when I run the entire test suite:
java.lang.IllegalStateException: 0 matchers expected, 1 recorded.
at org.easymock.internal.ExpectedInvocation.createMissingMatchers(ExpectedInvocation.java:42)
at org.easymock.internal.ExpectedInvocation.<init>(ExpectedInvocation.java:34)
at org.easymock.internal.ExpectedInvocation.<init>(ExpectedInvocation.java:26)
at org.easymock.internal.RecordState.invoke(RecordState.java:64)
at org.easymock.internal.MockInvocationHandler.invoke(MockInvocationHandler.java:24)
at org.easymock.internal.ObjectMethodsFilter.invoke(ObjectMethodsFilter.java:56)
at org.easymock.classextension.internal.ClassProxyFactory$1.intercept(ClassProxyFactory.java:74)
at com.protrade.soccersim.data.emulator.matrix.PositionCategoryMatrix$$EnhancerByCGLIB$$c5298a7.getPossession(<generated>)
at com.protrade.soccersim.data.emulator.stats.team.PossessionCalculatorUnitTest.testDeterminePossessionHomeWin(PossessionCalculatorUnitTest.java:45)
The code involved is this little beauty (trimmed a bit):
#Before
public void setUp() throws Exception {
homeTeam = createMock( PositionCategoryMatrix.class );
awayTeam = createMock( PositionCategoryMatrix.class );
...
}
#Test
public void testDeterminePossessionHomeWin() {
expect(homeTeam.getPossession()).andReturn( 0.15151515 );
expect(awayTeam.getPossession()).andReturn( 0.01515152 );
replay( homeTeam, awayTeam );
...
}
The exception is being thrown on the first expect. And it really doesn't make sense. It says it's getting a matcher, but the method doesn't even take an argument. And odd enough it's only during test suites! I'm creating a new mock in the #Before, so it shouldn't be inheriting anything from somewhere else (not that some other method would have a matcher on it)
So, any ideas?
I was sick and tired of seeing this with each new legacy code base with EasyMock I had to work with. Write one new EasyMock test by the book and all of the sudden random tests start failing because of Matchers never captured. So I went looking how EasyMock stores those Matchers. It makes use of a final class LastControl, in that class are a few threadlocals where different things get stored. One of those was for the Matchers. Luck has it that there is a static method on there to pull all the Matchers from the threadlocal that where still on there. So this gave me this idea (with help of a collegue, thanks Sven, he wanted credit)
/**
* Base class to make sure all EasyMock matchers are cleaned up. This is not pretty but it will work
*
* #author N069261KDS
*
*/
public class BaseTest {
#Before
public void before(){
LastControl.pullMatchers();
}
#After
public void after(){
LastControl.pullMatchers();
}
}
Basicly let your test that fail with the Matchers error extend from this class and you'll be sure the Matchers are cleaned. Note this IS A WORKAROUND. The offending tests should have been written right in the first place. But if you have to wade through 5000+ tests , this is the lesser of two evils. I hope this will help people out !
While it's true that this can be a spurious message resulting from a "silly" EasyMock bug, it is also very likely to be due to invalid usage of the EasyMock API. In my case the message arose from this JUnit 3.8 test (and like you, this only happened when I ran my entire suite of tests, and only via Maven, not Eclipse):
public void testSomething() {
// Set up
MyArgumentType mockArg = (MyArgumentType) EasyMock.anyObject(); // bad API usage
// Invoke the method under test
final String result = objectUnderTest.doSomething(mockArg);
// Verify (assertions, etc.)
...
}
Instead of using anyObject(), I should have used createMock(MyArgumentType.class) or one of its variants. I don't know what I was thinking, I've written millions of these tests and used the API correctly.
The confusing bit is that the test that fails with the "wrong number of matchers" message isn't necessarily (or ever?) the one in which you used the API wrongly. It might be the first test executed after the buggy one that contains a replay() or verify() method, but I haven't verified this experimentally.
I had the same error message. I was (accidentally) using an isA() declaration in the call on the class under test
I.e.
classUnderTest.callStateChanged(calls, isA(LoggingOnlyListener.class));
when I meant:
classUnderTest.callStateChanged(calls, new LoggingOnlyListener());
And it was the test AFTER this one that failed every time.
I just ran into this problem, and I think I managed to figure it out. For me it was due the the previous test (that's in a different Class), where I was (incorrectly) using an EasyMock matcher in an Assert.assertEquals method.
It seems EasyMock couldn't complain about the extra matcher reported until the first expects methods was called.
I am running into a similar problem. From what I observed, even method returns are matched using Matchers. So if your first method fails for any reason, the matcher for the return match is still in the stack. That could be one reason why you are seeing 1 matchers recorded even when your method doesn't take any argument. Basically, the first method invocation never returned a value.
Which version of Easymock are you using?
I read a post about the release of v.2.5.2 and previuous versions might have a
dumb bug on the capture
try to use Easymock 2.5.2+

Resources