Debian Codegraph @

doc/cgreen-guide-en.asciidoc

raw
1 //////////////////////////////////////////////////////////////////////
2 In this Asciidoc document we use the convention that one sentence is kept on a single line.
3 This creates nice diffs.
4 //////////////////////////////////////////////////////////////////////
5 :source-highlighter: highlightjs
6 :icons: font
7 :numbered:
8 :toc: left
9 :pp: ++
10 :title-page:
11 :title-logo-image: logo.png
12 ifdef::env-github[]
13 :tip-caption: :bulb:
14 :note-caption: :information_source:
15 :important-caption: :heavy_exclamation_mark:
16 :caution-caption: :fire:
17 :warning-caption: :warning:
18 endif::[]
19
20 = Cgreen : Unit Tests, Stubbing and Mocking for C and C++
21 v{VERSION} - Generated {localdate}
22
23
24 == Cgreen Quickstart Guide
25
26 === What is Cgreen?
27
28 *Cgreen* is a unit testing framework for the C and C++ software developer, a test automation and software quality assurance tool for programmers and development teams.
29 The tool is completely open source published under the https://github.com/cgreen-devs/cgreen/blob/master/LICENSE[ISC, OpenBSD, license].
30
31 Unit testing is a development practice popularised by the agile development community.
32 It is characterised by writing many small tests alongside the normal code.
33 Often the tests are written before the code they are testing, in a tight test-code-refactor loop.
34 Done this way, the practice is known as Test Driven Development.
35 *Cgreen* was designed specifically to support this style of development.
36
37 Unit tests are written in the same language as the code, in our case C or C++.
38 This avoids the mental overhead of constantly switching language, and also allows you to use any application code in your tests.
39
40 Here are some of its features:
41
42 - Fluent API resulting in very readable tests
43 - Expressive and clear output using the default reporter
44 - Fully functional mocks, both strict, loose and learning
45 - Mocks with side effects
46 - Each test runs in its own process for test suite robustness
47 - Automatic discovery and running of tests using dynamic library inspection
48 - Extensive and expressive constraints for many datatypes
49 - Custom constraints can be constructed by user
50 - BDD-flavoured test declarations with Before and After declarations
51 - Extensible reporting mechanism
52 - Fully composable test suites
53 - A single test can be run in a single process for easier debugging
54
55 *Cgreen* also supports the classic xUnit-style assertions for easy porting from other frameworks.
56
57 *Cgreen* was initially developed to support C programming, but there is also support for C{pp}.
58 It was initially a spinoff from a research project at Wordtracker and created by Marcus Baker.
59 Significant additions by Matt Hargett and continuous nurturing by Thomas Nilefalk has made *Cgreen* what it is today.
60
61
62 === Cgreen - Vanilla or Chocolate?
63
64 Test driven development (TDD) really catched on when the JUnit framework for Java spread to other langauges, giving us a family of https://en.wikipedia.org/wiki/XUnit[xUnit] tools.
65 *Cgreen* was born in this wave and have many similarities to the xUnit family.
66
67 But TDD evolved over time and modern thinking and practice is more along the lines of BDD, an acronym for Behaviour Driven Development, made popular by people like Dan North and frameworks like JBehave, RSpec, Cucumber and Jasmine.
68
69 *Cgreen* follows this trend and has evolved to embrace a BDD-flavoured style of testing.
70 Although the fundamental mechanisms in TDD and 'technical' BDD are much the same, the shift in focus by changing wording from 'tests' to 'behaviour specifications' is very significant.
71
72 This document will present *Cgreen* using the more modern and better BDD-inspired style.
73 In a later section you can have a peek at the classic xUnit-family TDD API, but you should consider that as outdated.
74
75
76 === Installing Cgreen
77
78 There are two ways to install *Cgreen* in your system.
79
80 ==== Installing a package
81
82 The first way is to use packages provided by the *Cgreen* Team and porters for the various operating systems.
83 If your system uses a package manager ('apt', 'yum', 'brew' and so on) there might be a prebuilt package that you can just install using your systems package manager.
84
85 If no *Cgreen* package is distributed for your system you can download a package from https://github.com/cgreen-devs/cgreen/releases[Cgreen GitHub project].
86 Install it using the normal procedures for your system.
87
88 NOTE: At this point there are pre-built packages available for quite a few environments.
89 They are not all using the latest version, though.
90 If you need that, you can still build from source.
91
92
93 ==== Installing from source
94
95 A second way is available for developers and advanced users.
96 Basically this consists of fetching the sources of the project on https://github.com/cgreen-devs/cgreen[GitHub], just click on "Download ZIP", and then compile them.
97 To do this you need the http://www.cmake.org[CMake] build system.
98
99 Once you have the CMake tool installed, the steps are:
100
101 -----------------------------------------
102 $ unzip cgreen-master.zip
103 $ cd cgreen-master
104 $ make
105 $ make test
106 $ make install
107 -----------------------------------------
108
109 The initial `make` command will configure the build process and create a separate `build` directory before going there and building using *CMake*.
110 This is called an 'out of source build'.
111 It compiles *Cgreen* from outside the sources directory.
112 This helps the overall file organization and enables multi-target builds from the same sources by leaving the complete source tree untouched.
113
114 TIP: Experienced users may tweak the build configuration by going to the build subdirectory and use `ccmake ..` to modify the build configuration in that subtree.
115
116 TIP: The Makefile is just there for convenience, it creates the build directory and invokes *CMake* there, so that you don't have to.
117 This means that experienced *CMake* users can just do as they normally do with a *CMake*-based project instead of invoking `make`.
118
119 The build process will create a library (on unix called `libcgreen.so`) which can be used in conjunction with the `cgreen.h` header file to compile and link your test code.
120 The created library is installed in the system directories, by default in `/usr/local/lib/`.
121
122
123 ==== Your First Test
124
125 We will start demonstrating the use of *Cgreen* by writing some tests for *Cgreen* itself to confirm that everything is working as it should.
126 Let's start with a simple test module with no tests, called `first_test.c`...
127
128 [source,c]
129 ---------------------------------------
130 include::tutorial_src/first_tests0.c[]
131 ---------------------------------------
132
133 This is very unexciting.
134 It just creates an empty test suite and runs it.
135 It's usually easier to proceed in small steps, and this is the smallest one I could think of.
136 The only complication is the `cgreen.h` header file and the mysterious looking "declarations" at the beginning of the file.
137
138 The BDD flavoured *Cgreen* notation calls for a System Under Test
139 (SUT), or a 'context'.
140 The declarations give a context to the tests and it also makes it more natural to talk about which module or class, the system under test, is actually responsible for the functionality we are describing.
141 In one way we are 'describing', or spec'ing, the functionality of the SUT.
142 That's what the `Describe();` does.
143 And for technical reasons (actually requirements of the C language), you must declare the `BeforeEach()` and `AfterEach()` functions even if they are empty.
144 (You will get strange errors if you don't!)
145
146 NOTE: We are using the name "Cgreen" as the SUT in these first examples, as *Cgreen* itself is the object or class we want to test or describe.
147
148 I am assuming you have the *Cgreen* folder in the include search path to ensure compilation works, otherwise you'll need to add that in the compilation command.
149
150 Then, building this test is, of course, trivial...
151
152 -----------------------------
153 $ gcc -c first_test.c
154 $ gcc first_test.o -lcgreen -o first_test
155 $ ./first_test
156 -----------------------------
157
158 Invoking the executable should give...
159
160 -----------------------------
161 include::tutorial_src/first0.out[]
162 -----------------------------
163
164 All of the above rather assumes you are working in a Unix like environment, probably with 'gcc'.
165 The code is pretty much standard C99, so any C compiler should work.
166 *Cgreen* should compile on all systems that support the `sys/msg.h` messaging library.
167 It has been tested on Linux, MacOSX, Cygwin.
168 If you are on Windows we would be glad if you could figure out how to build there.
169
170 So far we have tried compilation, and shown that the test suite actually runs.
171 Let's add a meaningless test or two so that you can see how it runs...
172
173 [source,c]
174 -----------------------------
175 include::tutorial_src/first_tests1.c[]
176 -----------------------------
177
178 A test is denoted by the macro `Ensure` which takes an optional context (`Cgreen`) and a, hopefully descriptive, testname (`passes_this_test`).
179 You add the test to your suite using `add_test_with_context()`.
180
181 On compiling and running, we now get the output...
182
183 -----------------------------
184 include::tutorial_src/first1.out[]
185 -----------------------------
186
187 The `TextReporter`, created by the call to `create_text_reporter()`, is the easiest way to output the test results.
188 It prints the failures as intelligent and expressive text messages on your console.
189
190 Of course "0" would never equal "1", but this shows that *Cgreen* presents the value you expect (`[be true]`) __and__ the expression that you want to assert (`[0 == 1]`).
191 We can also see a handy short form for asserting boolean expressions (`assert_that(0 == 1);`).
192
193 [[tdd_with_cgreen]]
194 === Five Minutes Doing TDD with Cgreen
195
196 For a more realistic example we need something to test.
197 We'll pretend that we are writing a function to split the words of a sentence in place.
198 It would do this by replacing any spaces with string terminators and returns the number of conversions plus one.
199 Here is an example of what we have in mind...
200
201 [source,c]
202 -------------------------------
203 char *sentence = strdup("Just the first test");
204 word_count = split_words(sentence);
205 -------------------------------
206
207 The variable `sentence` should now point at "Just\0the\0first\0test".
208 Not an obviously useful function, but we'll be using it for something more practical later.
209
210 This time around we'll add a little more structure to our tests.
211 Rather than having the test as a stand alone program, we'll separate the runner from the test cases.
212 That way, multiple test suites of test cases can be included in the `main()` runner file.
213 This makes it less work to add more tests later.
214
215 Here is the, so far empty, test case in `words_test.c`...
216
217 [source,c]
218 -------------------------------
219 include::tutorial_src/words_tests0.c[]
220 -------------------------------
221
222 Here is the `all_tests.c` test runner...
223
224 [source,c]
225 -------------------------------
226 include::tutorial_src/all_tests.c[]
227 -------------------------------
228
229 *Cgreen* has two ways of running tests.
230 The default is to run all tests in their own protected processes.
231 This is what happens if you invoke `run_test_suite()`.
232 All tests are then completely independent since they run in separate processes, preventing a single run-away test from bringing the whole program down with it.
233 It also ensures that one test cannot leave any state to the next, thus forcing you to setup the prerequisites for each test correctly and clearly.
234
235 Building this scaffolding...
236
237 -------------------------------
238 $ gcc -c words_test.c
239 $ gcc -c all_tests.c
240 $ gcc words_test.o all_tests.o -lcgreen -o all_tests
241 -------------------------------
242
243 ...and executing the result gives the familiar...
244
245 -------------------------------
246 include::tutorial_src/words0.out[]
247 -------------------------------
248
249 Note that we get an extra level of output here, we have both `main` and `words_tests`.
250 That's because `all_tests.c` adds the words test suite to its own (named `main` since it was created in the function `main()`).
251 All this scaffolding is pure overhead, but from now on adding tests will be a lot easier.
252
253 Here is a first test for `split_words()` in `words_test.c`...
254
255 [source,c]
256 -------------------------------
257 include::tutorial_src/words_tests1.c[]
258 -------------------------------
259
260 The `assert_that()` macro takes two parameters, the value to assert and a constraint.
261 The constraints comes in various forms.
262 In this case we use the probably most common, `is_equal_to()`.
263 With the default `TextReporter` the message is sent to `STDOUT`.
264
265 To get this to compile we need to create the `words.h` header file...
266
267 [source,c]
268 -------------------------------
269 include::tutorial_src/words.h[lines=1]
270 -------------------------------
271
272 ...and to get the code to link we need a stub function in `words.c`...
273
274 [source,c]
275 -------------------------------
276 include::tutorial_src/words1.c[lines=3..5]
277 -------------------------------
278
279 A full build later...
280
281 -------------------------------
282 $ gcc -c all_tests.c
283 $ gcc -c words_test.c
284 $ gcc -c words.c
285 $ gcc all_tests.o words_test.o words.o -lcgreen -o all_tests
286 $ ./all_tests
287 -------------------------------
288
289 ...and we get the more useful response...
290
291 -------------------------------
292 include::tutorial_src/words1.out[]
293 -------------------------------
294
295 The breadcrumb trail following the "Failure" text is the nesting of the tests.
296 It goes from the test suites, which can be nested in each other, through the test function, and finally to the message from the assertion.
297 In the language of *Cgreen*, a "failure" is a mismatched assertion, or constraint, and an "exception" occurs when a test fails to complete for any reason, e.g. a segmentation fault.
298
299 We could get this to pass just by returning the value 4.
300 Doing TDD in really small steps, you would actually do this, but we're not teaching TDD here.
301 Instead we'll go straight to the core of the implementation...
302
303 [source,c]
304 --------------------------------
305 include::tutorial_src/words2.c[]
306 --------------------------------
307
308 Running it gives...
309
310 ---------------------------------
311 include::tutorial_src/words2.out[]
312 ---------------------------------
313
314 There is actually a hidden problem here, but our tests still passed so we'll pretend we didn't notice.
315
316 So it's time to add another test.
317 We want to confirm that the string is broken into separate words...
318
319 [source,c]
320 ---------------------------------
321 ...
322 include::tutorial_src/words_tests2.c[lines=10]
323 ...
324 include::tutorial_src/words_tests2.c[lines=15..23]
325 ---------------------------------
326
327 Sure enough, we get a failure...
328
329 ----------------------------------
330 include::tutorial_src/words3.out[]
331 ----------------------------------
332
333 Not surprising given that we haven't written the code yet.
334
335 The fix...
336
337 [source,c]
338 ----------------------------------
339 include::tutorial_src/words3.c[]
340 ----------------------------------
341
342 ...reveals our previous hack...
343
344 ----------------------------------
345 include::tutorial_src/words4.out[]
346 ----------------------------------
347
348 Our earlier test now fails, because we have affected the `strlen()` call in our loop.
349 Moving the length calculation out of the loop...
350
351 [source,c]
352 ----------------------------------
353 include::tutorial_src/words4.c[lines=3..5]
354 ...
355 include::tutorial_src/words4.c[lines=10..-1]
356 ----------------------------------
357
358 ...restores order...
359
360 ----------------------------------
361 include::tutorial_src/words5.out[]
362 ----------------------------------
363
364 It's nice to keep the code under control while we are actually writing it, rather than debugging later when things are more complicated.
365
366 That was pretty straight forward.
367 Let's do something more interesting.
368
369 === What are Mock Functions?
370
371 The next example is a more realistic extension of our previous attempts.
372 As in real life we first implement something basic and then we go for the functionality that we need.
373 In this case a function that invokes a callback for each word found in a sentence.
374 Something like...
375
376 [source,c]
377 ----------------------------------
378 void act_on_word(const char *word, void *memo) { ... }
379 words("This is a sentence", &act_on_word, &memo);
380 ----------------------------------
381
382 Here the `memo` pointer is just some accumulated data that the `act_on_word()` callback might work with.
383 Other people will write the `act_on_word()` function and probably many other functions like it.
384 The callback is actually a flex point, and not of interest right now.
385
386 The function under test is the `words()` function and we want to make sure it walks the sentence correctly, dispatching individual words as it goes.
387 So what calls are made are very important.
388 How do we go about to test this?
389
390 Let's start with a one word sentence.
391 In this case we would expect the callback to be invoked once with the only word, right?
392 Here is the test for that...
393
394 [source,c]
395 ---------------------------------
396 include::tutorial_src/words_tests3.c[lines=1..2]
397 ...
398 include::tutorial_src/words_tests3.c[lines=27..38]
399 ...
400 include::tutorial_src/words_tests3.c[lines=41..-1]
401 ---------------------------------
402
403 What is the funny looking `mock()` function?
404
405 A mock is basically a programmable object.
406 In C objects are limited to functions, so this is a mock function.
407 The macro `mock()` compares the incoming parameters with any expected values and dispatches messages to the test suite if there is a mismatch.
408 It also returns any values that have been preprogrammed in the test.
409
410 The test is `invokes_callback_once_for_single_word_sentence()`.
411 It programs the mock function using the `expect()` macro.
412 It expects a single call, and that single call should use the parameters `"Word"` and `NULL`.
413 If they don't match, we will get a test failure.
414
415 So when the code under test (our `words()` function) calls the injected `mocked_callback()` it in turn will call `mock()` with the actual parameters.
416
417 Of course, we don't add the mock callback to the test suite, it's not a test.
418
419 For a successful compile and link, the `words.h` file must now look like...
420
421 [source,c]
422 ----------------------------
423 include::tutorial_src/words.h[]
424 ----------------------------
425
426 ...and the `words.c` file should have the stub...
427
428 [source,c]
429 ----------------------------
430 include::tutorial_src/words5.c[lines=14..15]
431 ----------------------------
432
433 This gives us the expected failing test...
434
435 ----------------------------
436 include::tutorial_src/words6.out[]
437 ----------------------------
438
439 *Cgreen* reports that the callback was never invoked.
440 We can easily get the test to pass by filling out the implementation with...
441
442 [source,c]
443 ----------------------------
444 include::tutorial_src/words6.c[lines=14..16]
445 ----------------------------
446
447 That is, we just invoke it once with the whole string.
448 This is a temporary measure to get us moving.
449 For now everything should pass, although it doesn't drive much functionality yet.
450
451 ----------------------------
452 include::tutorial_src/words7.out[]
453 ----------------------------
454
455 That was all pretty conventional, but let's tackle the trickier case of actually splitting the sentence.
456 Here is the test function we will add to `words_test.c`...
457
458 [source,c]
459 ----------------------------
460 include::tutorial_src/words_tests4.c[lines=37..43]
461 ----------------------------
462
463 Each call is expected in sequence.
464 Any failures, or left-over or extra calls, and we get failures.
465 We can see all this when we run the tests...
466
467 ----------------------------
468 include::tutorial_src/words8.out[]
469 ----------------------------
470
471 The first failure tells the story.
472 Our little `words()` function called the mock callback with the entire sentence.
473 This makes sense, because that was the hack we did to get to the next test.
474
475 Although not relevant to this guide, I cannot resist getting these tests to pass.
476 Besides, we get to use the function we created earlier...
477
478 [source,c]
479 -----------------------------
480 include::tutorial_src/words7.c[lines=15..29]
481 -----------------------------
482
483 And with some work we are rewarded with...
484
485 ------------------------------
486 include::tutorial_src/words9.out[]
487 ------------------------------
488
489 More work than I like to admit as it took me three goes to get this right.
490 I firstly forgot the `+ 1` added on to `strlen()`, then forgot to swap `sentence` for `word` in the `(*callback)()` call, and finally third time lucky.
491 Of course running the tests each time made these mistakes very obvious.
492 It's taken me far longer to write these paragraphs than it has to write the code.
493
494
495
496 == Building Cgreen test suites
497
498 *Cgreen* is a tool for building unit tests in the C or C++ languages.
499 These are usually written alongside the production code by the programmer to prevent bugs.
500 Even though the test suites are created by software developers, they are intended to be human readable C code, as part of their function is an executable specification.
501 Used in this way, the test harness delivers constant quality assurance.
502
503 In other words you'll get less bugs.
504
505
506 === Writing Basic Tests
507
508 *Cgreen* tests are like C, or C++, functions with no parameters and no return value.
509 To signal that they actually are tests we mark them with the `Ensure` macro.
510 Here's an example...
511
512 [source,c]
513 -----------------------------
514 include::tutorial_src/strlen_tests1.c[lines=8..10]
515 -----------------------------
516
517 The `Ensure` macro takes two arguments (in the BDD style) where the first is the System Under Test (SUT) which must be declared with the `Describe` macro.
518
519 [source,c]
520 -----------------------------
521 include::tutorial_src/strlen_tests1.c[lines=4]
522 -----------------------------
523
524 The second argument is the test name and can be anything you want as long as it fullfills the rules for an identifier in C and C++.
525 A typical way to choose the named of the tests is what we see here, reading the declaration of the test makes sense since it is almost plain english, "Ensure strlen returns five for 'hello'".
526 No problem understanding what we aim to test, or in TDD lingo, test drive.
527 And it can be viewed as an example from a description of what strlen should be able to do.
528 In a way, extracting all the `Ensure`:s from your test might give you all the documentation you'll need.
529
530 The call to `assert_that()` is the primary part of an assertion, which is complemented with a constraint, in this case
531 `is_equal_to()`, as a parameter.
532 This makes a very fluent interface to the asserts, that actually reads like English.
533 The general format is then
534
535 [source, C]
536 ---------------
537 assert_that(actual, <constraint>);
538 ---------------
539
540 NOTE: Sometimes you just want to fail the test explicitly, and there is a function for that too, `fail_test(const char *message)`.
541 And there is a function to explicitly pass, `pass_test(void)`.
542 There is also a function to programmatically skip a test, `skip_test(void)` to complement the `xEnsure` notation (see <<xensure>>).
543
544 Assertions send messages to *Cgreen*, which in turn outputs the results.
545
546
547 === The Standard Constraints
548
549 Here are the standard constraints...
550
551 |=========================================================
552 |*Constraint* |*Passes if actual value/expression...*
553 | _Basic_ |
554 | `is_true` | evaluates to true, buy you can also just leave out the constraint,
555 e.g. `assert_that(found)` if `found` is of boolean type
556 | `is_false` | evaluates to false
557 | `is_null` | equals null
558 | `is_non_null` | is a non null value
559 | `is_not_null` | d:o
560 ||
561 | _Integer compatible_ |
562 | `is_equal_to(value)` | '== value'
563 | `is_equal_to_hex(value)` | '== value', but will show values in HEX
564 | `is_not_equal_to(value)` | '!= value'
565 | `is_greater_than(value)` | '> value'
566 | `is_less_than(value)` | '< value'
567 ||
568 | _Structs and general data_ |
569 | `is_equal_to_contents_of(pointer, size)` | matches the data pointed
570 to by `pointer` to a size
571 of `size` bytes
572 | `is_not_equal_to_contents_of(pointer, size)` | does not match the data
573 pointed to by `pointer`
574 to a size of `size` bytes
575 ||
576 | _Strings_ |
577 | `is_equal_to_string(value)` | are equal when compared using `strcmp()`
578 | `is_not_equal_to_string(value)` | are not equal when compared using `strcmp()`
579 | `contains_string(value)` | contains `value` when evaluated using `strstr()`
580 | `does_not_contain_string(value)` | does not contain `value` when evaluated
581 using `strstr()`
582 | `begins_with_string(value)` | starts with the string `value`
583 | `does_not_begin_with_string(value)` | does not start with the string `value`
584 | `ends_with_string(value)` | ends with the string `value`
585 | `does_not_end_with_string(value)` | does not end with the string `value`
586 ||
587 | _Double floats_ |
588 | `is_equal_to_double(value)` | are equal to `value` within the number of
589 significant digits (which you can set with a call
590 to `significant_figures_for_assert_double_are(int figures)`)
591 | `is_not_equal_to_double(value)` | are not equal to `value` within the number of
592 significant digits
593 | `is_less_than_double(value)` | `< value` withing the number of significant digits
594 | `is_greater_than_double(value)` | `> value` within the number of significant digits
595 |=========================================================
596
597 The boolean assertion macros accept an `int` value.
598 The equality assertions accept anything that can be cast to `intptr_t` and simply perform an `==` operation.
599 The string comparisons are slightly different in that they use the `<string.h>` library function `strcmp()`.
600 If you use `is_equal_to()` with `char *` pointers then it is the value of the pointers themselves that has to be the same, i.e. the pointers have to point at the same string for the test to pass.
601
602 The constraints above should be used as the second argument to one of the assertion functions:
603
604 |=========================================================
605 |*Assertion* |*Description*
606 | `assert_that(expected, constraint)` | Passes if `expected` fullfulls `constraint`,
607 to be used for all assertions except `double`
608 type values
609 | `assert_that_double(expected, constraint)` | Passes if `expected` fullfulls `constraint`,
610 only to be used for assertions on `double`
611 type values
612 |=========================================================
613
614
615 WARNING: You cannot use C/C++ string literal concatenation (like `"don't" "use" "string" "concatenation"`) in the parameters to the constraints.
616 If you do, you will get weird error messages about missing arguments to the constraint macros.
617 This is caused by the macros using argument strings to produce nice failure messages.
618
619
620 === Asserting C++ Exceptions
621
622 When you use *CGreen* with C++ there is one extra assertion available:
623
624 |=========================================================
625 |*Assertion* |*Description*
626 | `assert_throws(exception, expression)` | Passes if evaluating `expression` throws `exception`
627 |=========================================================
628
629
630 === BDD Style vs. TDD Style
631
632 So far we have encouraged the modern BDD style.
633 It has merits that we really want you to benefit from.
634 But you might come across *Cgreen* test in another style, more like the standard TDD style, which is more inline with previous thinking and might be more similar to other frameworks.
635
636 The only difference, in principle, is the use of the SUT or 'context'.
637 In the BDD style you have it, in the TDD style you don't.
638
639 [source,c]
640 .BDD style:
641 -----------------------------
642 include::tutorial_src/strlen_tests2.c[lines=4..16]
643 -----------------------------
644 <1> The `Describe` macro must name the SUT
645 <2> The `BeforeEach` function...
646 <3> ... and the `AfterEach` functions must exist and name the SUT
647 <4> The test need to name the SUT
648 <5> Adding to the test suite
649
650 CAUTION: You can only have tests for a single SUT in the same source file.
651
652 If you use the older pure-TDD style you skip the `Describe` macro, the `BeforeEach` and `AfterEach` functions.
653 You don't need a SUT in the `Ensure()` macro or when you add the test to the suite.
654
655 [source,c]
656 .TDD style:
657 -----------------------------
658 include::tutorial_src/strlen_tests3.c[lines=3..12]
659 -----------------------------
660 <1> No `Describe`, `BeforeEach()` or `AfterEach()`
661 <2> No SUT/context in the `Ensure()` macro
662 <3> No SUT/context in `add_test()` and you should use this function instead
663 of `..with_context()`.
664
665 TIP: You might think of the TDD style as the BDD style with a default SUT or context.
666
667
668 === A Runner
669
670 The tests are only run by running a test suite in some form.
671 (But see also <<runner>>.)
672 We can create and run one especially for this test like so...
673
674 [source,c]
675 -----------------------------
676 include::tutorial_src/strlen_tests5.c[lines=12..16]
677 -----------------------------
678
679 In case you have spotted that the reference to `returns_five_for_hello` should have an ampersand in front of it, `add_test_with_context()` is actually a macro.
680 The `&` is added automatically.
681 Further more, the `Ensure()`-macro actually mangles the tests name, so it is not actually a function name.
682 (This might also make them a bit difficult to find in the debugger....)
683
684 To run the test suite, we call `run_test_suite()` on it.
685 So we can just write...
686
687 [source,c]
688 -----------------------------
689 include::tutorial_src/strlen_tests5.c[lines=19]
690 -----------------------------
691
692 The results of assertions are ultimately delivered as passes and failures to a collection of callbacks defined in a `TestReporter` structure.
693 There is a predefined `TestReporter` in *Cgreen* called the `TextReporter` that delivers messages in plain text like we have already seen.
694
695 The return value of `run_test_suite()` is a standard C library/Unix exit code that can be returned directly by the `main()` function.
696
697 The complete test code now looks like...
698
699 [source,c]
700 -----------------------------
701 include::tutorial_src/strlen_tests5.c[]
702 -----------------------------
703
704 Compiling and running gives...
705
706 -----------------------------
707 $ gcc -c strlen_test.c
708 $ gcc strlen_test.o -lcgreen -o strlen_test
709 $ ./strlen_test
710 include::tutorial_src/strlen2.out[]
711 -----------------------------
712
713 We can see that the outer test suite is called `our_tests` since it was in `our_tests()` we created the test suite.
714 There are no messages shown unless there are failures.
715 So, let's break our test to see it...
716
717 [source,c]
718 -----------------------------
719 include::tutorial_src/strlen_tests6.c[lines=8..10]
720 -----------------------------
721
722 ...we'll get the helpful message...
723
724 -----------------------------
725 include::tutorial_src/strlen6.out[]
726 -----------------------------
727
728 *Cgreen* starts every message with the location of the test failure so that the usual error message identifying tools (like Emacs's `next-error`) will work out of the box.
729
730 Once we have a basic test scaffold up, it's pretty easy to add more tests.
731 Adding a test of `strlen()` with an empty string for example...
732
733 [source,c]
734 -----------------------------
735 ...
736 include::tutorial_src/strlen_tests7.c[lines=12..21]
737 ...
738 -----------------------------
739
740 And so on.
741
742
743 === BeforeEach and AfterEach
744
745 It's common for test suites to have a lot of duplicate code, especially when setting up similar tests.
746 Take this database code for example...
747
748 [source,c]
749 ------------------------------
750 include::tutorial_src/schema_tests1.c[]
751 ------------------------------
752
753 We have already factored out the duplicate code into its own functions `create_schema()` and `drop_schema()`, so things are not so bad.
754 At least not yet.
755 But what happens when we get dozens of tests?
756 For a test subject as complicated as a database http://www.martinfowler.com/eaaCatalog/activeRecord.html[ActiveRecord], having dozens of tests is very likely.
757
758 We can get *Cgreen* to do some of the work for us by calling these methods before and after each test in the test suite.
759
760 Here is the new version...
761
762 [source,c]
763 ---------------------------
764 ...
765 include::tutorial_src/schema_tests2.c[lines=6]
766 ...
767 include::tutorial_src/schema_tests2.c[lines=11..13]
768 ...
769 include::tutorial_src/schema_tests2.c[lines=18..41]
770 ...
771 ---------------------------
772
773 With this new arrangement *Cgreen* runs the `create_schema()` function before each test, and the `drop_schema()` function after each test.
774 This saves some repetitive typing and reduces the chance of accidents.
775 It also makes the tests more focused.
776
777 The reason we try so hard to strip everything out of the test functions is the fact that the test suite acts as documentation.
778 In our `person.h` example we can easily see that `Person` has some kind of name property, and that this value must be unique.
779 For the tests to act like a readable specification we have to remove as much mechanical clutter as we can.
780
781 In this particular case there are more lines that we could move from the tests to `BeforeEach()`:
782
783 [source,c]
784 ---------------------------
785 include::tutorial_src/schema_tests2.c[lines=25..26]
786 ---------------------------
787
788 Of course that would require an extra variable, and it might make the tests less clear.
789 And as we add more tests, it might turn out to not be common to all tests.
790 This is a typical judgement call that you often get to make with `BeforeEach()` and `AfterEach()`.
791
792 NOTE: If you use the pure-TDD notation, not having the test subject named by the `Describe` macro, you can't have the `BeforeEach()` and `AfterEach()` either.
793 In this case you can still run a function before and after every test.
794 Just nominate any `void(void)` function by calling the function `set_setup()` and/or `set_teardown()` with the suite and the function that you want to run before/after each test.
795 In the example above that would be `set_setup(suite, create_schema);` and `set_teardown(suite, drop_schema);`.
796
797 A couple of details.
798 There is only one `BeforeEach()` and one `AfterEach()` allowed in each `TestSuite`.
799 Also, the `AfterEach()` function might not be run if the test crashes, causing some test interference.
800 This brings us nicely onto the next section...
801
802
803 === Each Test in its Own Process
804
805 Consider this test method...
806
807 [source,c]
808 -----------------------------
809 include::tutorial_src/crash_tests1.c[lines=8..11]
810 -----------------------------
811
812 Crashes are not something you would normally want to have in a test run.
813 Not least because it will stop you receiving the very test output you need to tackle the problem.
814
815 To prevent segmentation faults and other problems bringing down the test suites, *Cgreen* runs every test in its own process.
816
817 Just before calling the `BeforeEach()` (or `setup`) function, *Cgreen* `fork()`:s.
818 The main process waits for the test to complete normally or die.
819 This includes calling the `AfterEach()`(or `teardown`) function, if any.
820 If the test process dies, an exception is reported and the main test process carries on with the next test.
821
822 For example...
823
824 [source,c]
825 -----------------------------
826 include::tutorial_src/crash_tests1.c[]
827 -----------------------------
828
829 When built and run, this gives...
830
831 -----------------------------
832 include::tutorial_src/crash1.out[]
833 -----------------------------
834
835 The normal thing to do in this situation is to fire up the debugger.
836 Unfortunately, the constant `fork()`:ing of *Cgreen* can be one extra complication too many when debugging.
837 It's enough of a problem to find the bug.
838
839 To get around this, and also to allow the running of one test at a time, *Cgreen* has the `run_single_test()` function.
840 The signatures of the two run methods are...
841
842 - `int run_test_suite(TestSuite *suite, TestReporter *reporter);`
843 - `int run_single_test(TestSuite *suite, char *test, TestReporter *reporter);`
844
845 The extra parameter of `run_single_test()`, the `test` string, is the name of the test to select.
846 This could be any test, even in nested test suites (see below).
847 Here is how we would use it to debug our crashing test...
848
849 [source,c]
850 -----------------------------
851 include::tutorial_src/crash_tests2.c[lines=13..17]
852 -----------------------------
853
854 When run in this way, *Cgreen* will not `fork()`.
855 But see the section on <<debugging>>.
856
857 TIP: The function `run()` is a good place to place a breakpoint.
858
859 The following is a typical session:
860
861 -----------------------------------
862 $ gdb crash2
863 ...
864 (gdb) break main
865 (gdb) run
866 ...
867 (gdb) break run
868 (gdb) continue
869 ...
870 Running "main" (1 tests)...
871
872 Breakpoint 2, run_the_test_code (suite=suite@entry=0x2003abb0,
873 spec=spec@entry=0x402020 <CgreenSpec__CrashExample__seg_faults_for_null_dereference__>,
874 reporter=reporter@entry=0x2003abe0) at /cygdrive/c/Users/Thomas/Utveckling/Cgreen/cgreen/src/runner.c:270
875 270 run(spec);
876 (gdb) step
877 run (spec=0x402020 <CgreenSpec__CrashExample__seg_faults_for_null_dereference__>)
878 at /cygdrive/c/Users/Thomas/Utveckling/Cgreen/cgreen/src/runner.c:217
879 217 spec->run();
880 (gdb) step
881 CrashExample__seg_faults_for_null_dereference () at crash_test2.c:9
882 9 int *p = NULL;
883 (gdb) step
884 10 (*p)++;
885 (gdb) step
886
887 Program received signal SIGSEGV, Segmentation fault.
888 0x004011ea in CrashExample__seg_faults_for_null_dereference () at crash_test2.c:10
889 10 (*p)++;
890 -----------------------------------
891
892 Which shows exactly where the problem is.
893
894 This deals with the case where your code throws an exception like segmentation fault, but what about a process that fails to complete by getting stuck in a loop?
895
896 Well, *Cgreen* will wait forever too.
897 But, using the C signal handlers, we can place a time limit on the process by sending it an interrupt.
898 To save us writing this ourselves, *Cgreen* includes the `die_in()` function to help us out.
899
900 Here is an example of time limiting a test...
901
902 [source,c]
903 ---------------------------
904 ...
905 include::tutorial_src/crash_tests3.c[lines=8]
906 ...
907 include::tutorial_src/crash_tests3.c[lines=11..23]
908 ---------------------------
909
910 When executed, the code will slow for a second, and then finish with...
911
912 ---------------------------
913 include::tutorial_src/crash3.out[]
914 ---------------------------
915
916 Note that you see the test results as they come in.
917 *Cgreen* streams the results as they happen, making it easier to figure out where the test suite has problems.
918
919 Of course, if you want to set a general time limit on all your tests, then you can add a `die_in()` to a `BeforeEach()` (or `setup()`) function.
920 *Cgreen* will then apply the limit to each of the tests in that context, of course.
921
922 Another possibility is the use of an environment variable named `CGREEN_TIMEOUT_PER_TEST` which, if set to a number will apply that timeout to every test run.
923 This will apply to all tests in the same run.
924
925
926 [[debugging]]
927 === Debugging *Cgreen* tests
928
929 *Cgreen* protects itself from being torn down by an exception in a test by `fork()`-ing each test into a separate process.
930 A catastrophic error will then only affect the child process for that specific test and *Cgreen* can catch it, rather than crashing too.
931 It can then report the exception and continue with the next test.
932
933 ==== No fork, please
934
935 If you want to debug any of your tests the constant `fork()`-ing might make that difficult or impossible.
936 There are also other circumstances that might require that you don't use `fork()`.
937
938 There are two ways to make *Cgreen* refrain from `fork()`-ing.
939
940 *Cgreen* does not `fork()` when only a single test is run by name with the function `run_single_test()`.
941 To debug you can then obviously set a breakpoint at that test (but note that its actual name probably have been mangled).
942 *Cgreen* does some book-keeping before actually getting to the test, so a function easier to find might be the one simply called `run()`.
943
944 The second way is to define the environment variable `CGREEN_NO_FORK`.
945 If *Cgreen* can get that variable from the environment using `getenv()` it will run the test(s) in the same process.
946 In this case the non-forking applies to *all* tests run, so all test will run in the same process, namely *Cgreen*s main process.
947
948 WARNING: This might bring your whole test suite down if a single test causes an exception.
949 So it is not a recommended setting for normal use.
950
951 ==== Debugging with `cgreen-runner`
952
953 If you use the convenient auto-discovery feature of *Cgreen* (see
954 <<auto-discovery>>) by running dynamic loadable libraries through
955 `cgreen-runner`, it might be tricky to figure out to where to put
956 breaks and to get them to "take".
957
958 `cgreen-runner` obviously loads the library (or libraries) with your
959 tests dynamically so the tests are not available before executing the
960 code that loads them.
961
962 TIP: The function `run()` is a good place to place a breakpoint.
963
964 ==== `cgreen-debug`
965
966 For some platforms a utility script, `cgreen-debug`, is installed when you install *Cgreen*.
967 It makes it very convenient to start a debugging session for a particular test.
968
969 Find out the logical name of the test, which is composed of the Context and the Testname, in the form <context>:<testname>.
970 Then just invoke `cgreen-debug`
971
972 ----
973 $ cgreen-debug <library> <context>:<testname>
974 ----
975
976 The script will try to find a debugger, invoke it on the
977 `cgreen-runner` and break on that test.
978
979 NOTE: Currently it supports `gdb` (will prefer `cgdb` if
980 that's available) and `lldb`.
981
982
983 === Building Composite Test Suites
984
985 The `TestSuite` is a composite structure.
986 This means test suites can be added to test suites, building a tree structure that will be executed in order.
987
988 Let's combine the `strlen()` tests with the `Person` tests above.
989 Firstly we need to remove the `main()` functions.
990 E.g...
991
992 [source,c]
993 ----------------------------
994 include::tutorial_src/suite_strlen_tests.c[lines=8]
995 ...
996 include::tutorial_src/suite_strlen_tests.c[lines=10..12]
997 ...
998 include::tutorial_src/suite_strlen_tests.c[lines=14..-1]
999 ----------------------------
1000
1001 Then we can write a small runner with a new `main()` function...
1002
1003 [source,c]
1004 -----------------------
1005 include::tutorial_src/suite1.c[]
1006 -----------------------
1007
1008 It's usually easier to place the `TestSuite` prototypes directly in the runner source, rather than have lot's of header files.
1009 This is the same reasoning that let us drop the prototypes for the test functions in the actual test scripts.
1010 We can get away with this, because the tests are more about documentation than encapsulation.
1011
1012 As we saw above, we can run a single test using the `run_single_test()` function, and we'd like to be able to do that from the command line.
1013 So we added a simple `if` block to take the test name as an optional argument.
1014 The entire test suite will be searched for the named test.
1015 This trick also saves us a recompile when we debug.
1016
1017 When you use the BDD notation, each test subject is named by a `Describe()` macro and is the equivalent of a suite. Since *Cgreen* 1.6.5 you can have several `Describe()` macros in the same source file (before that each needed its own file).
1018 You can also create composite suites that gather tests from several files and run them in one go.
1019
1020 CAUTION: Rewrite pending.
1021 The next couple of sections does not reflect the current best thinking.
1022 They are remnants of the TDD notation.
1023 Using BDD notation you would create separate contexts, each in its own file, with separate names, for each of the fixture cases.
1024
1025 NOTE: If you use the TDD (non-BDD) notation you can build several test suites in the same file, even nesting them.
1026 We can even add mixtures of test functions and test suites to the same parent test suite.
1027 Loops will give trouble, however.
1028
1029 NOTE: If we do place several suites in the same file, then all the suites will be named the same in the breadcrumb trail in the test message.
1030 They will all be named after the function the create call sits in.
1031 If you want to get around this, or you just like to name your test suites, you can use `create_named_test_suite()` instead of `create_test_suite()`.
1032 This takes a single string parameter.
1033 In fact `create_test_suite()` is just a macro that inserts the `__func__` constant into `create_named_test_suite()`.
1034
1035 What happens to `setup` and `teardown` functions in a `TestSuite` that contains other `TestSuite`:s?
1036
1037 Well firstly, *Cgreen* does not `fork()` when running a suite.
1038 It leaves it up to the child suite to `fork()` the individual tests.
1039 This means that a `setup` and `teardown` will run in the main process.
1040 They will be run once for each child suite.
1041
1042 We can use this to speed up our `Person` tests above.
1043 Remember we were creating a new connection and closing it again in the fixtures.
1044 This means opening and closing a lot of connections.
1045 At the slight risk of some test interference, we could reuse the connection accross tests...
1046
1047 [source,c]
1048 -----------------------
1049 ...
1050 static MYSQL *connection;
1051
1052 static void create_schema() {
1053 mysql_query(connection, "create table people (name, varchar(255) unique)");
1054 }
1055
1056 static void drop_schema() {
1057 mysql_query(connection, "drop table people");
1058 }
1059
1060 Ensure(can_add_person_to_database) { ... }
1061 Ensure(cannot_add_duplicate_person) { ... }
1062
1063 void open_connection() {
1064 connection = mysql_init(NULL);
1065 mysql_real_connect(connection, "localhost", "me", "secret", "test", 0, NULL, 0);
1066 }
1067
1068 void close_connection() {
1069 mysql_close(connection);
1070 }
1071
1072 TestSuite *person_tests() {
1073 TestSuite *suite = create_test_suite();
1074 set_setup(suite, create_schema);
1075 set_teardown(suite, drop_schema);
1076 add_test(suite, can_add_person_to_database);
1077 add_test(suite, cannot_add_duplicate_person);
1078
1079 TestSuite *fixture = create_named_test_suite("Mysql fixture");
1080 add_suite(fixture, suite);
1081 set_setup(fixture, open_connection);
1082 set_teardown(fixture, close_connection);
1083 return fixture;
1084 }
1085 -----------------------
1086
1087 The trick here is creating a test suite as a wrapper whose sole purpose is to wrap the main test suite in the fixture.
1088 This is our 'fixture' pointer.
1089 This code is a little confusing, because we have two sets of fixtures in the same test script.
1090
1091 We have the MySQL connection fixture.
1092 This will run `open_connection()` and `close_connection()` just once at the beginning and end of the person tests.
1093 This is because the `suite` pointer is the only member of `fixture`.
1094
1095 We also have the schema fixture, the `create_schema()` and `drop_schema()`, which is run before and after every test.
1096 Those are still attached to the inner `suite`.
1097
1098 In the real world we would probably place the connection fixture in its own file...
1099
1100 [source,c]
1101 -----------------------
1102 static MYSQL *connection;
1103
1104 MYSQL *get_connection() {
1105 return connection;
1106 }
1107
1108 static void open_connection() {
1109 connection = mysql_init(NULL);
1110 mysql_real_connect(connection, "localhost", "me", "secret", "test", 0, NULL, 0);
1111 }
1112
1113 static void close_connection() {
1114 mysql_close(connection);
1115 }
1116
1117 TestSuite *connection_fixture(TestSuite *suite) {
1118 TestSuite *fixture = create_named_test_suite("Mysql fixture");
1119 add_suite(fixture, suite);
1120 set_setup(fixture, open_connection);
1121 set_teardown(fixture, close_connection);
1122 return fixture;
1123 }
1124 -----------------------
1125
1126 This allows the reuse of common fixtures across projects.
1127
1128
1129 == Mocking functions with Cgreen
1130
1131 When testing you want certainty above all else.
1132 Random events destroy confidence in your test suite and force needless extra runs "to be sure".
1133 A good test places the system under test into a tightly controlled environment.
1134 A test chamber if you like.
1135 This makes the tests fast, repeatable and reliable.
1136
1137 To create a test chamber for testing code, we have to control any outgoing calls from the code under test.
1138 We won't believe our test failure if our code is making calls to the internet for example.
1139 The internet can fail all by itself.
1140 Not only do we not have total control, but it also means we have to get dependent components working before we can test the higher level code.
1141 This makes it difficult to code top down.
1142
1143 The solution to this dilemma is to write stub code for the components whilst the higher level code is written.
1144 This pollutes the code base with temporary code, and the test isolation disappears when the system is eventually fleshed out.
1145
1146 The ideal is to have minimal stubs written for each individual test.
1147 *Cgreen* encourages this approach by making such tests easier to write.
1148
1149
1150 === The Problem with Streams
1151
1152 How would we test the following code...?
1153
1154 [source,c]
1155 -----------------------
1156 include::tutorial_src/read_paragraph1.c[lines=4..-1]
1157 -----------------------
1158
1159 This is a fairly generic stream filter that turns the incoming characters into C string paragraphs.
1160 Each call creates one paragraph, returning a pointer to it or returning `NULL` if there is no paragraph.
1161 The paragraph has memory allocated to it and the stream is advanced ready for the next call.
1162 That's quite a bit of functionality, and there are plenty of nasty boundary conditions.
1163 I really want this code tested before I deploy it.
1164
1165 The problem is the stream dependency.
1166 We could use a real stream, but that will cause all sorts of headaches.
1167 It makes the test of our paragraph formatter dependent on a working stream.
1168 It means we have to write the stream first, bottom up coding rather than top down.
1169 It means we will have to simulate stream failures - not easy.
1170 It will also mean setting up external resources.
1171 This is more work, will run slower, and could lead to spurious test failures.
1172
1173 By contrast, we could write a simulation of the stream for each test, called a "server stub".
1174
1175 For example, when the stream is empty nothing should happen.
1176 We hopefully get `NULL` from `read_paragraph` when the stream is exhausted.
1177 That is, it just returns a steady stream of `EOF`s.
1178
1179 Fortunately, this function takes the stream as a parameter.
1180 This is called dependency injection and is a very important concept.
1181 Thanks to this we can write a small function, a stub, with the same signature, that simulates a real stream, and inject that instead of a real stream, which the production code probably does.
1182
1183 NOTE: If the code does not inject the dependency this way we can often compile the stub separately and link with that instead the real stream.
1184 In this case your stub will have to have the same name as the original function, of course.
1185 (This is sometimes called the linkage seam.)
1186
1187 [source,c]
1188 -----------------------
1189 include::tutorial_src/stream_tests0.c[lines=6..22]
1190 -----------------------
1191
1192 Our simulation is easy here, because our fake stream returns only one value.
1193 Things are harder when the function result changes from call to call as a real stream would.
1194 Simulating this would mean messing around with static variables and counters that are reset for each test.
1195 And of course, we will be writing quite a few stubs.
1196 Often a different one for each test.
1197 That's a lot of clutter.
1198
1199 *Cgreen* can handle this clutter for us by letting us write a single programmable function for all our tests.
1200
1201
1202 === Record and Playback
1203
1204 We can redo our example by creating a `stream_stub()` function.
1205 We can call it anything we want, and since I thought we wanted to have a stubbed stream...
1206
1207 [source,c]
1208 -----------------------
1209 include::tutorial_src/stream_tests1.c[lines=6..8]
1210 -----------------------
1211
1212 Hardly longer that our trivial server stub above, it is just a macro to generate a return value, but we can reuse this in test after test.
1213 Let's see how.
1214
1215 For our simple example above we just tell it to always return `EOF`...
1216
1217 [source,c]
1218 -----------------------
1219 include::tutorial_src/stream_tests1.c[lines=1..17]
1220 -----------------------
1221
1222 <1> The `always_expect()` macro takes the function name as an argument and also defines the return value using the call to `will_return()`.
1223 This is a declaration of an expectation of a call to the stub, and we have told our `stream_stub()` to always return `EOF` when called.
1224
1225 Let's see if our production code actually works...
1226
1227 -----------------------
1228 include::tutorial_src/stream1.out[]
1229 -----------------------
1230
1231 So far, so good.
1232 On to the next test.
1233
1234 If we want to test a one character line, we have to send the terminating `EOF` or `"\n"` as well as the single character.
1235 Otherwise our code will loop forever, giving an infinite line of that character.
1236
1237
1238 Here is how we can do this...
1239
1240 [source,c]
1241 -----------------------
1242 include::tutorial_src/stream_tests2.c[lines=19..25]
1243 -----------------------
1244
1245 Unlike the `always_expect()` instruction, `expect()` sets up an expectation of a single call and specifying `will_return()` sets the single return value for just that call.
1246 It acts like a record and playback model.
1247 Successive expectations map out the return sequence that will be given back once the test proper starts.
1248
1249 We'll add this test to the suite and run it...
1250
1251 -----------------------
1252 include::tutorial_src/stream2.out[]
1253 -----------------------
1254
1255 Oops.
1256 Our code under test doesn't work.
1257 Already we need a fix...
1258
1259 [source,c]
1260 -----------------------
1261 include::tutorial_src/read_paragraph2.c[lines=4..19]
1262 -----------------------
1263
1264 <1> After moving the indexing here...
1265 <2> and here...
1266
1267 around a bit everything is fine:
1268
1269 -----------------------
1270 include::tutorial_src/stream3.out[]
1271 -----------------------
1272
1273 So, how do the *Cgreen* stubs work?
1274 Each `expect()` describes one call to the stub and when a call to `will_return()` is included, the return values will be collected and returned in order as the expected calls arrive.
1275
1276 The `mock()` macro captures the parameter names, their values and the `__func__` property (the name of the stub function).
1277 *Cgreen* can then use these to look up entries in the return list, and also to generate more helpful messages.
1278
1279 We can now crank out our tests quite quickly...
1280
1281 [source,c]
1282 -----------------------
1283 include::tutorial_src/stream_tests3.c[lines=27..33]
1284 -----------------------
1285
1286 I've been a bit naughty.
1287 As each test runs in its own process, I haven't bothered to free the pointers to the paragraphs.
1288 I've just let the operating system do it.
1289 Purists may want to add the extra clean up code.
1290
1291 I've also used `always_expect()` for the last instruction.
1292 Without this, if the stub is given an instruction it does not expect, it will throw a test failure.
1293 This is overly restrictive, as our `read_paragraph()` function could quite legitimately call the stream after it had run off of the end.
1294 OK, that would be odd behaviour, but that's not what we are testing here.
1295 If we were, it would be placed in a test of its own.
1296 The `always_expect()` call tells *Cgreen* to keep going after the first three letters, allowing extra calls.
1297
1298 As we build more and more tests, they start to look like a specification of the wanted behaviour...
1299
1300 [source,c]
1301 -----------------------
1302 include::tutorial_src/stream_tests4.c[lines=35..41]
1303 -----------------------
1304
1305 ...and just for luck...
1306
1307 [source,c]
1308 -----------------------
1309 include::tutorial_src/stream_tests4.c[lines=43..46]
1310 -----------------------
1311
1312 This time we must not use `always_return()`.
1313 We want to leave the stream where it is, ready for the next call to `read_paragraph()`.
1314 If we call the stream beyond the line ending, we want to fail.
1315
1316 Oops, that was a little too fast.
1317 Turns out we are failing anyway...
1318
1319 -----------------------
1320 include::tutorial_src/stream5.out[]
1321 -----------------------
1322
1323 Clearly we are passing through the line ending.
1324 Another fix later...
1325
1326 [source,c]
1327 -----------------------
1328 include::tutorial_src/read_paragraph3.c[lines=4..20]
1329 -----------------------
1330
1331 And we are passing again...
1332
1333 -----------------------
1334 include::tutorial_src/stream6.out[]
1335 -----------------------
1336
1337 There are no limits to the number of stubbed methods within a test,
1338 only that two stubs cannot have the same name.
1339 The following will cause problems...
1340
1341 [source,c]
1342 -----------------------
1343 include::tutorial_src/multiple_streams1.c[lines=10..-1]
1344 -----------------------
1345
1346 You __could__ program the same stub to return values for the two streams, but that would make a very brittle test.
1347 Since we'd be making it heavily dependent on the exact internal behaviour that we are trying to test, or test drive, it will break as soon as we change that implementation.
1348 The test will also become very much harder to read and understand. And we really don't want that.
1349
1350 So, it will be necessary to have two stubs to make this test behave, but that's not a problem...
1351
1352 [source,c]
1353 -----------------------
1354 include::tutorial_src/multiple_streams2.c[lines=10..-1]
1355 -----------------------
1356
1357 We now have a way of writing fast, clear tests with no external dependencies.
1358 The information flow is still one way though, from stub to the code under test.
1359 When our code calls complex procedures, we won't want to pick apart the effects to infer what happened.
1360 That's too much like detective work.
1361 And why should we? We just want to know that we dispatched the correct information down the line.
1362
1363 Things get more interesting when we think of the traffic going the other way, from code to stub.
1364 This gets us into the same territory as mock objects.
1365
1366
1367 === Setting Expectations on Mock Functions
1368
1369 To swap the traffic flow, we'll look at an outgoing example instead.
1370 Here is the prewritten production code...
1371
1372 [source,c]
1373 -----------------------
1374 include::tutorial_src/stream.c[lines=23..32]
1375 -----------------------
1376
1377 This is the start of a formatter utility.
1378 Later filters will probably break the paragaphs up into justified text, but right now that is all abstracted behind the `void write(void *, char *)` interface.
1379 Our current interests are: does it loop through the paragraphs, and does it crash?
1380
1381 We could test correct paragraph formation by writing a stub that collects the paragraphs into a `struct`.
1382 We could then pick apart that `struct` and test each piece with assertions.
1383 This approach is extremely clumsy in C.
1384 The language is just not suited to building and tearing down complex edifices, never mind navigating them with assertions.
1385 We would badly clutter our tests.
1386
1387 Instead we'll test the output as soon as possible, right in the called function...
1388
1389 [source,c]
1390 -----------------------
1391 ...
1392 include::tutorial_src/formatter_tests0.c[lines=12..-1]
1393 ...
1394 -----------------------
1395
1396 By placing the assertions into the mocked function, we keep the tests minimal.
1397 The catch with this method is that we are back to writing individual functions for each test.
1398 We have the same problem as we had with hand coded stubs.
1399
1400 Again, *Cgreen* has a way to automate this.
1401 Here is the rewritten test...
1402
1403 [source,c]
1404 -----------------------
1405 include::tutorial_src/formatter_tests1.c[lines=10..-1]
1406 -----------------------
1407
1408 Where are the assertions?
1409
1410 Unlike our earlier stub, `reader()` can now check its parameters.
1411 In object oriented circles, an object that checks its parameters as well as simulating behaviour is called a mock object.
1412 By analogy `reader()` is a mock function, or mock callback.
1413
1414 Using the `expect()` macro, we have set up the expectation that `writer()` will be called just once.
1415 That call must have the string `"a"` for the `paragraph` parameter.
1416 If the actual value of that parameter does not match, the mock function will issue a failure straight to the test suite.
1417 This is what saves us writing a lot of assertions.
1418
1419 === Running Tests With Mocked Functions
1420
1421
1422 It's about time we actually ran our test...
1423
1424 -----------------------
1425 include::tutorial_src/formatter1.out[]
1426 -----------------------
1427
1428 Confident that a single character works, we can further specify the behaviour.
1429 Firstly an input sequence...
1430
1431 [source,c]
1432 -----------------------
1433 include::tutorial_src/formatter_tests2.c[lines=25..34]
1434 -----------------------
1435
1436 A more intelligent programmer than me would place all these calls in a
1437 loop.
1438
1439 -------------------------
1440 include::tutorial_src/formatter2.out[]
1441 -------------------------
1442
1443 Next, checking an output sequence...
1444
1445 [source,c]
1446 -----------------------
1447 include::tutorial_src/formatter_tests3.c[lines=36..-1]
1448 -----------------------
1449
1450 Again we can se that the `expect()` calls follow a record and playback model.
1451 Each one tests a successive call.
1452 This sequence confirms that we get `"a"`, `"b"` and `"c"` in order.
1453
1454 -----------------------
1455 include::tutorial_src/formatter3.out[]
1456 -----------------------
1457
1458 So, why the 5 passes?
1459 Each `expect()` with a constrait is actually an assert.
1460 It asserts that the call specified is actually made with the parameters given and in the specified order.
1461 In this case all the expected calls were made.
1462
1463 Then we'll make sure the correct stream pointers are passed to the correct functions.
1464 This is a more realistic parameter check...
1465
1466 [source,c]
1467 -----------------------
1468 include::tutorial_src/formatter_tests4.c[lines=49..-1]
1469 -----------------------
1470
1471 -----------------------
1472 include::tutorial_src/formatter4.out[]
1473 -----------------------
1474
1475 And finally we'll specify that the writer is not called if
1476 there is no paragraph.
1477
1478 [source,c]
1479 -----------------------
1480 include::tutorial_src/formatter_tests5.c[lines=56..-1]
1481 -----------------------
1482
1483 This last test is our undoing...
1484
1485 -----------------------
1486 include::tutorial_src/formatter5.out[]
1487 -----------------------
1488
1489 Obviously blank lines are still being dispatched to the `writer()`.
1490 Once this is pointed out, the fix is obvious...
1491
1492 [source,c]
1493 -----------------------
1494 include::tutorial_src/stream2.c[lines=23..-1]
1495 -----------------------
1496
1497 Tests with `never_expect()` can be very effective at uncovering subtle
1498 bugs.
1499
1500 -----------------------
1501 include::tutorial_src/formatter6.out[]
1502 -----------------------
1503
1504 All done.
1505
1506
1507 === Mocks Are...
1508
1509 Using mocks is a very handy way to isolate a unit by catching and
1510 controlling calls to external units.
1511 Depending on your style of coding two schools of thinking have emerged. And of course *Cgreen* supports both!
1512
1513
1514 ==== Strict or Loose Mocks
1515
1516 The two schools are thinking a bit differently about what mock expectations means.
1517 Does it mean that all external calls must be declared and expected?
1518 What happens if a call was made to a mock that wasn't expected?
1519 And vice versa, if an expected call was not made?
1520
1521 Actually, the thinking is not only a school of thought, you might want to switch from one to the other depending on the test.
1522 So *Cgreen* allows for that too.
1523
1524 By default *Cgreen* mocks are 'strict', which means that a call to an non-expected mock will be considered a failure.
1525 So will an expected call that was not fullfilled.
1526 You might consider this a way to define a unit through all its exact behaviours towards its neighbours.
1527
1528 On the other hand, 'loose' mocks are looser.
1529 They allow both unfulfilled expectations and try to handle unexpected calls in a reasonable way.
1530
1531 You can use both with in the same suite of tests using the call `cgreen_mocks_are(strict_mocks);` and `cgreen_mocks_are(loose_mocks);` respectively.
1532 Typically you would place that call at the beginning of the test, or in a setup or `BeforeEach()` if it applies to all tests in a suite.
1533
1534
1535 ==== Learning Mocks
1536
1537 Working with legacy code and trying to apply TDD, BDD, or even simply adding some unit tests, is not easy.
1538 You're working with unknown code that does unknown things with unknown counterparts.
1539
1540 So the first step would be to isolate the unit.
1541 We won't go into details on how to do that here, but basically you would replace the interface to other units with mocks.
1542 This is a somewhat tedious manual labor, but will result in an isolated unit where you can start applying your unit tests.
1543
1544 Once you have your unit isolated in a harness of mocks, we need to figure out which calls it does to other units, now replaced by mocks, in the specific case we are trying to test.
1545
1546 This might be complicated, so *Cgreen* can make that a bit simpler.
1547 There is a third 'mode' of the *Cgreen* mocks, the __learning mocks__.
1548
1549 If you temporarily add the call `cgreen_mocks_are(learning_mocks);` at the beginning of your unit test, the mocks will record all calls and present a list of those calls in order, including the actual parameter values, on the standard output.
1550
1551 So let's look at the following example from the *Cgreen* unit tests.
1552 It's a bit contorted since the test actually call the mocked functions directly, but I believe it will serve as an example.
1553
1554 [source,c]
1555 -----
1556 include::tutorial_src/learning_mocks.c[lines=8..-1]
1557 -----
1558
1559 We can see the call to `cgreen_mocks_are()` starting the test and
1560 setting the mocks into learning mode.
1561
1562 If we run this, just as we usually run tests, the following will show
1563 up in our terminal:
1564
1565 // This needs to be copied and pasted from the output of make in tutorial_src
1566 // At least, I couldn't make 'make' capture it into the output file
1567 // It ought to be:
1568 // include::tutorial_src/learning_mocks.out[]
1569 ----
1570 Running "learning_mocks" (1 tests)...
1571 LearningMocks -> emit_pastable_code : Learned mocks are
1572 expect(string_out, when(p1, is_equal_to(1)));
1573 expect(string_out, when(p1, is_equal_to(2)));
1574 expect(integer_out);
1575 expect(integer_out);
1576 expect(string_out, when(p1, is_equal_to(3)));
1577 expect(integer_out);
1578 Completed "LearningMocks": 0 passes, 0 failures, 0 exceptions.
1579 Completed "learning_mocks": 0 passes, 0 failures, 0 exceptions.
1580 ----
1581
1582 If this was for real we could just copy this and paste it in place of
1583 the call to `cgreen_mocks_are()` and we have all the expectations
1584 done.
1585
1586 NOTE: Before you can do this you need to implement the mock functions, of course.
1587 I.e. write functions that replaces the real functions and instead calls `mock()`.
1588
1589 NOTE: If a test fails with an exception, you won't get the learned calls unfortunately.
1590 They are collected and printed at the end of the test.
1591 This might be improved at some future time.
1592
1593 TIP: You can try the `cgreen-mocker` for this, as described in <<cgreen-mocker>>.
1594
1595
1596 == More on `expect()` and `mock()`
1597
1598 === Important Things To Remember About `expect()` and `mock()`
1599
1600 Using `expect()` and `mock()` is a very powerful way to isolate your code under test from its dependencies.
1601 But it is not always easy to follow what happens, and when.
1602
1603 Here are some important things to remember when working with *Cgreen* mocks.
1604
1605 - calls to `expect()` collects constraints and any other required information when it is called
1606 - this also goes for `will_return()` which will save the value of its parameter _when it is called_
1607 - the actual evaluation and execution of those constraints occur when `mock()` is called in the function named in the `expect()` call(s)
1608 - calls to a function specified by the `expect()` calls are evaluated in the same order as the ``expect()``s were executed, but only for that named function
1609 - the lexical scope of the first parameter in a `when()` is always inside the mocked function where the `mock()` call is made
1610 - the lexical scope of arguments to an `is_equal_to...()` is where that call is made
1611
1612 IMPORTANT: In summary, `expect()` does early collection, including evaluation of return value expression, and `mock()` does late evaluation of the constraints collected against the given arguments to `mock()`.
1613
1614 [[refactoring-tests]]
1615 === Refactoring Tests with Mocks - CAUTION!
1616
1617 After a while you are bound to get tests with calls to `expect()`.
1618 You might even have common patterns in multiple tests.
1619 So your urge to refactor starts to set in.
1620 And that is good, go with it, we have tests to rely on.
1621
1622 But there are a lot of things going on behind the scenes when you use *Cgreen*, often with the help of some serious macro-magic, so special care needs to be taken when refactoring tests that have `expect()` in them.
1623
1624 ==== Renaming
1625
1626 The first "gotcha" is when you rename a function that you mock.
1627 You are likely to have `expect()`s for that function too.
1628
1629 CAUTION: the function name in an `expect()` is "text" so it will not be catched by a refactoring tool.
1630 You will need to change the name there manually.
1631
1632 ==== Local Variables
1633
1634 When you extract common `expect()` setup into a helper function, take a little care with data held in local variables.
1635
1636 `will_set_contents_of_output_parameter()` copies the data at the time of the `expect()` call, so locals are safe -- even in a helper function that has returned before the mocked call is made:
1637
1638 [source,c]
1639 -----------------------------
1640 static void expect_char(char ch) {
1641 expect(mocked_read,
1642 will_set_contents_of_output_parameter(buf, &ch, sizeof(char)),
1643 will_return(1));
1644 }
1645
1646 Ensure(Readline, can_read_some_characters) {
1647 expect_char('a');
1648 expect_char('b');
1649 expect_char('c');
1650 ...
1651 <call something that calls mocked_read()>
1652 ...
1653 -----------------------------
1654
1655 NOTE: Earlier releases of *Cgreen* stored a _pointer_ to the data and only read it when the mock was actually called, so the source had to remain valid until then. If you build against an older *Cgreen* (for example one packaged by your distribution) that caveat still applies; see <<release-history>>.
1656
1657 `will_capture_parameter()` is different, and there the subtlety is unavoidable.
1658 It writes the captured value _into_ a variable of yours, which must be live both when the mock is called and afterwards, when your test reads what was captured.
1659 So it cannot live in a helper function that returns before the call.
1660 In practice this rarely bites, precisely because the test itself needs that variable in order to assert on the captured value -- so it naturally stays in the scope of the test:
1661
1662 [source,c]
1663 -----------------------------
1664 Ensure(Capture, captures_the_value) {
1665 int captured;
1666 expect(mocked_fn, will_capture_parameter(value, captured));
1667 ...
1668 <call something that calls mocked_fn()>
1669 ...
1670 assert_that(captured, is_equal_to(...));
1671 }
1672 -----------------------------
1673
1674 CAUTION: The variable you capture into with `will_capture_parameter()` must be live at the call to the mocked function _and_ where your test reads it -- so keep it in the scope of the test, not in an extracted helper.
1675
1676
1677 === Other Use Cases For Mocks
1678
1679 ==== Out Parameters
1680
1681 In C all function parameters are by value, so a function that needs to return a value through a parameter must do that using a pointer to the area or variable the function should fill. A `Cgreen` mock function also has to be able to fill such an "out parameter".
1682
1683 If the out parameter is a scalar -- an `int`, `long`, `bool`, an `enum` or a pointer -- you would use:
1684
1685 [source, c]
1686 -----------------------
1687 expect(get_option, will_set_scalar_output_parameter(chars_read, 6));
1688 -----------------------
1689
1690 As scalars come in varying sizes the number of bytes written must match the size of the target variable. You control the width of the value written in the same way you would force any C literal to a particular size:
1691
1692 [source, c]
1693 -----------------------
1694 will_set_scalar_output_parameter(count, 6L); // a long
1695 will_set_scalar_output_parameter(small, (short)6); // a short
1696 -----------------------
1697
1698 IMPORTANT: The value's type must match the type of the variable the out parameter points to and is written into. This is your responsibility. *Cgreen* cannot know the actual size of the parameter in the `expect` as that is expanded compile-time with no access to the function declaration. If the widths disagree during run-time, too few or too many bytes will be written. When in doubt, cast the value to the correct size/type. (NOTE: A character literal like `'a'` is an `int` in C but a `char` in C++, so use `(char)'a'` for a `char` out parameter.)
1699
1700 For anything that is not a scalar -- a struct, a string, an array -- you need to use `will_set_contents_of_output_parameter()` with a pointer to the data and an explicit size:
1701
1702 [source, c]
1703 -----------------------
1704 include::tutorial_src/set_contents.c[lines=3..12]
1705 ...
1706 -----------------------
1707
1708 When the mock for `convert_to_uppercase()` is called it will write the string "UPPER CASE" in the area pointed to by `converted_string`.
1709
1710 ==== Setting fields
1711
1712 Sometimes you need to set a field in a struct sent by reference to a mocked function.
1713 You cannot use the `will_set_contents_of_output_parameter()` directly since you can't, or even don't want to, know the complete information in the structure.
1714 But with a little bit of boilerplate in your mock function you can still write to a single field.
1715
1716 In the mock function you need to create a local variable that points to the field you want to update.
1717 You can then use this pointer variable in the mock call to supplement the real parameters.
1718
1719 This local variable will then be accessible in `expect()` calls as if it was a parameter, and you can use it to wrote data to where it points, which then should be the field in the incoming structure.
1720
1721 [source, c]
1722 -----------------------
1723 include::tutorial_src/set_field.c[lines=3..18]
1724 ...
1725 -----------------------
1726
1727 The local variable `field` in the mock function is set to point to the field that we need to update.
1728 It is then exposed by including it in the `mock()` call, and `will_set_contents_of_output_parameter()` will use it to update whatever it points to with the data provided in the `expect()`.
1729
1730 NOTE: Both the local variable and the data argument in the call to `will_set_contents_of_output_parameter()` must be pointers.
1731 You cannot use literals as data, except when it is a string literal which as per C convention is converted to a pointer.
1732
1733 ==== Side Effects
1734
1735 Sometimes returning simple values is not enough.
1736 The function that you want to mock might have some side effect, like setting a global error code, or aggregate some data.
1737
1738 Let's assume that the `reader` increments a counter every time it gets called and we need to mimic that behaviour.
1739 There are many ways to do this, but here is one using the side effect feature.
1740 It works by calling a callback function that you provide, allowing you to feed some data to it.
1741
1742 We create the "side effect function" which needs to take a single argument which should be a pointer to the "side effect data".
1743 You will have to cast that datapointer to the correct type.
1744
1745 [source, c]
1746 -----------------------
1747 include::tutorial_src/side_effect.c[lines=29..44]
1748 -----------------------
1749
1750 === The Mock Macros
1751
1752 When specifying behavior of mocks there are three parts.
1753 First, how often the specified behaviour or expectation will be executed:
1754
1755 |=======================================================================
1756 |*Macro* |*Description*
1757 |`expect(function, ...)` |Expected once, in the specified order, for the same function
1758 |`always_expect(function, ...)`|Expect this behavior from here onwards
1759 |`never_expect(function)` |From this point this mocked function must never be called
1760 |=======================================================================
1761
1762 You can specify constraints and behaviours for each expectation (except for `never_expect()` naturally).
1763 A constraint places restrictions on the parameters (and will tell you if the expected restriction was not met), and a behaviour specifies what the mock should do if the parameter constraints are met.
1764
1765 A parameter constraint is defined using the `when(parameter, constraint)` macro.
1766 It takes two parameters:
1767
1768 |=================================================
1769 |*Parameter* |*Description*
1770 |`parameter` |The name of the parameter to the mock function
1771 |`constraint`|A constraint placed on that parameter
1772 |=================================================
1773
1774 There is a multitude of constraints available (actually, exactly the same as for the assertions we saw earlier):
1775
1776 |==========================================================================
1777 |*Constraint* |*Type*
1778 |`is_equal_to(value)` | Integers
1779 |`is_not_equal_to(value)` | Integers
1780 |`is_greater_than(value)` | Integers
1781 |`is_less_than(value)` | Integers
1782 | |
1783 |`is_equal_to_contents_of(pointer, size_of_contents)` |Bytes/Structures
1784 |`is_not_equal_to_contents_of(pointer, size_of_contents)` |Bytes/Structures
1785 ||
1786 |`is_equal_to_string(value)` |String
1787 |`is_not_equal_to_string(value)` |String
1788 |`contains_string(value)` |String
1789 |`does_not_contain_string(value)` |String
1790 |`begins_with_string(value)` |String
1791 ||
1792 |`is_equal_to_double(value)` |Double
1793 |`is_not_equal_to_double(value)` |Double
1794 |`is_less_than_double(value)` |Double
1795 |`is_greater_than_double(value)` |Double
1796 |==========================================================================
1797
1798 For the double valued constraints you can set the number of significant digits to consider a match with a call to `significant_figures_for_assert_double_are(int figures)`.
1799 The <<floating_point_comparison_algorithm, section on how to work with doubles>> has a more detailed discussion of the algorithm used for comparing floating point numbers.
1800
1801 Then there are a couple of ways to return results from the mocks.
1802 They all provide ways to return various types of values through `mock()`.
1803 In your mocked function you can then simply return that value, or manipulate it as necessary.
1804
1805 |===========================================================================================
1806 |*Macro* |*`mock()` will...*
1807 |`will_return(value)` | return `value`, for integer types
1808 |`will_return_double(value)` | return `value` as a "boxed double", for double floats (required because of C's type coercion rules which would otherwise convert a double into an int)
1809 |`will_return_by_value(struct [, size])` | return a pointer to an allocated copy of the `struct` that can be copied and returned by value from the mocked function; `size` is optional, defaults to `sizeof` the value, and is rarely necessary
1810 |`will_set_scalar_output_parameter(parameter_name, value)`| write the scalar `value` (an integer, `bool`, `enum` or pointer) into the referenced out parameter; the number of bytes is taken from the type of `value`
1811 |`will_set_contents_of_output_parameter(parameter_name, pointer_to_value, size)`| write `size` bytes from the pointed out value (`pointer_to_value`) into where the referenced out parameter (`parameter_name`) is pointing
1812 |`will_capture_parameter(parameter_name, local_variable)` |capture the value of the parameter and store it in the named local variable
1813 |`with_side_effect(function, pointer_to_data)` | call the side effect `function` and pass `pointer_to_data` to it
1814 |===========================================================================================
1815
1816 NOTE: *`will_return_double()`*: The "boxed double" returned by `mock()` have to be "unboxed" by the caller see <<double_mocks>> for details.
1817
1818 NOTE: *`will_return_by_value`*: The memory allocated for the copy of the struct returned by `mock()` needs to be deallocated by the caller or it will be lost. You can do this with the code in the `Box` example below.
1819
1820 NOTE: *`will_set_scalar_output_parameter`*: The number of bytes written is `sizeof` the value you pass, so its type must match the out parameter's type. See _Out Parameters_ above.
1821
1822 NOTE: *`will_set_contents_of_output_parameter`*: The previous name of this macro was `will_set_contents_of_parameter` and it is still available. The new name is prefered due to readability.
1823
1824 NOTE: *`will_capture_parameter`*: The local variable to capture the value in must be live at the time of the call to the mock function, so using a local variable in a function called by your test will not work. See <<refactoring-tests>> for details.
1825
1826 === Combining Expectations
1827
1828 You can combine the expectations for a `mock()` in various ways:
1829
1830 [source,c]
1831 -----------------------
1832 expect(mocked_file_writer,
1833 when(data, is_equal_to(42)),
1834 will_return(EOF));
1835 expect(mocked_file_reader,
1836 when(file, is_equal_to_contents_of(&FD, sizeof(FD))),
1837 when(input, is_equal_to_string("Hello world!"),
1838 with_side_effect(&update_counter, &counter),
1839 will_set_contents_of_output_parameter(status, FD_CLOSED, sizeof(bool))));
1840 -----------------------
1841
1842 If multiple `when()` are specified they all need to be fullfilled.
1843 You can of course only have one for each of the parameters of your mock function.
1844
1845 You can also have multiple `will_set_contents_of_output_parameter()` in an expectation, one for each reference parameter, but naturally only one `will_return()`.
1846
1847 To ensure that a specific call happens `n` times the macro `times(number_times_called)` can be passed as a constraint to a specific call:
1848
1849 [source,c]
1850 -----------------------
1851 expect(mocked_file_writer,
1852 when(data, is_equal_to(42)),
1853 times(1));
1854 -----------------------
1855
1856 This feature only works for `expect()`.
1857
1858 === Order of constraints
1859
1860 When you have multiple constraints in an `expect` the order in which they are executed is not always exactly the order in which they where given.
1861
1862 First all constraints are inspected for validity, such as if the parameter name given cannot be found, but primarily to see if the parameters, if any, matche the actual parameters in the call.
1863
1864 Then all read-only constraints are processed, followed by constraints that set contents.
1865
1866 Finally all side effect constraints are executed.
1867
1868 === Order of multiple `expect`s
1869
1870 The expections still need to respect the order of calling, so if we call the function
1871 `mocker_file_writer` with the following pattern:
1872
1873 [source,c]
1874 -----------------------
1875 file_writer(42);
1876 file_writer(42);
1877 file_writer(43);
1878 file_writer(42);
1879 -----------------------
1880
1881 The expectation code should look like the following
1882
1883 [source,c]
1884 -----------------------
1885 expect(file_writer,
1886 when(data, is_equal_to(42)),
1887 times(2));
1888 expect(file_writer,
1889 when(data, is_equal_to(43)),
1890 times(1));
1891 expect(file_writer,
1892 when(data, is_equal_to(42)),
1893 times(1));
1894 -----------------------
1895
1896 So the order of `expect`s for one mocked file need to mimic the order in which that
1897 function will be called during the test run. This order is enforced and any call
1898 out-of-sequence will be considered a failed expectation.
1899
1900 However, order _between_ mocked calls does not matter, and it is not enforced either. Imagine
1901 we have this source code
1902
1903 [source,c]
1904 -----------------------
1905 file_writer(42);
1906 file_writer(43);
1907 int c = file_reader();
1908 -----------------------
1909
1910 To match that with `expect`s you could have
1911
1912 [source,c]
1913 -----------------------
1914 expect(file_writer, when(data, is_equal_to(42)));
1915 expect(file_writer, when(data, is_equal_to(43)));
1916 expect(file_reader, ...)
1917 -----------------------
1918
1919 or
1920
1921 [source,c]
1922 -----------------------
1923 expect(file_reader, ...)
1924 expect(file_writer, when(data, is_equal_to(42)));
1925 expect(file_writer, when(data, is_equal_to(43)));
1926 -----------------------
1927
1928 or even
1929
1930 [source,c]
1931 -----------------------
1932 expect(file_writer, when(data, is_equal_to(42)));
1933 expect(file_reader, ...)
1934 expect(file_writer, when(data, is_equal_to(43)));
1935 -----------------------
1936
1937
1938 === Handling out-parameters
1939
1940 TBD. Hint: this involves using `will_set_scalar_output_parameter()` and `will_set_contents_of_output_parameter()`.
1941
1942 === Returning `struct`
1943
1944 If the function we are mocking returns structs by value, then our mock function need to do that too.
1945 To do this we must use specific return macro, `will_return_by_value()`.
1946 Below is some example code using an imaginary struct typedef'ed as `Struct` and a corresponding function, `retrieve_struct()`, which we want to mock.
1947
1948 The underlying mechanism of this is that in the test we create the struct that we want to return.
1949 The macro `will_return_by_value()` then copies that to a dynamically allocated area, saving it so that it can be returned by `mock()`.
1950
1951 [source,c]
1952 -----------------------
1953 Struct returned_struct = {...};
1954 expect(retrieve_struct,
1955 will_return_by_value(returned_struct));
1956 /* `returned_struct` has been copied to an allocated area */
1957 -----------------------
1958
1959 NOTE: `will_return_by_value` has an optional `size` argument. When omitted, the macro uses `sizeof` the value; passing it explicitly lets you override the size if you ever need to.
1960
1961
1962 The mock function will then look like this:
1963
1964 [source,c]
1965 -----------------------
1966 Struct retrieve_struct() {
1967 return *(Struct *)mock(); /* De-reference the returned pointer to the allocated area */
1968 }
1969 -----------------------
1970
1971 This would cause a memory leak since the area allocated by the `return_by_value()` macro is not deallocated.
1972 And in many scenarious this might not be a big problem, and you could make do with that simple version.
1973
1974 We might want to be sure, e.g. if we want to use `valgrind` on when unittesting to catch leaks early.
1975 Then we don't want our unittests to pollute the actual leakage analysis.
1976
1977 In that case the mock function needs to free up the area that was automatically allocated by `will_return_by_value()`.
1978 The pointer returned by `mock()` will point to that area.
1979 So, here's a better, although slightly more complicated, version:
1980
1981 [source,c]
1982 -----------------------
1983 Struct retrieve_struct() {
1984 Struct *struct_p = (Struct *)mock(); /* Get the pointer */
1985 Struct the_struct = *struct_p; /* Dereference to get a struct */
1986 free(struct_p); /* Deallocate the returned area */
1987 return the_struct; /* Finally we can return the struct by value */
1988 }
1989 -----------------------
1990
1991
1992 === Mocking `struct` Parameters
1993
1994 Modern C standards allows function parameters to be ``struct``s by value.
1995 Since our `mock()` only can handle scalar values this presents a bit of a conundrum.
1996
1997 [source,c]
1998 -----------------------
1999 include::tutorial_src/struct_parameters.c[lines=11..18]
2000 -----------------------
2001
2002 And we also can not compare a non-scalar value with any of the `is_equal_to...()` constraint macros in the `expect()` call.
2003 Also remember that the C language does not allow comparing non-scalar values using `==`.
2004
2005 There are a couple of ways to handle this and which one to select depends on what you want to do.
2006
2007 ==== Checking Single `struct` Fields
2008
2009 In an `expect(when())` we probably want to check one, or more, of the fields in the struct.
2010
2011 Since `mock()` actually can "mock" anything we can use a normal field expression to access the value we want to check:
2012
2013 [source,c]
2014 -----------------------
2015 include::tutorial_src/struct_parameters.c[lines=26..28]
2016 -----------------------
2017
2018 The trick here is that `mock()` just saves the "name", as a string, given as the argument, in this case "s.i", and pair it with the value of that expression.
2019 There is no requirement that the "name" is actually a parameter, it can be anything.
2020 The only thing to remember is that the exact same string needs to be used when invoking `when()`:
2021
2022 [source,c]
2023 -----------------------
2024 include::tutorial_src/struct_parameters.c[lines=35..36]
2025 -----------------------
2026
2027 You can do this with as many fields as you need.
2028 And there is no (reasonable) limit to how many arguments `mock()` can take, so you can start with the ones that you require and add more as you need them.
2029
2030 [source,c]
2031 -----------------------
2032 include::tutorial_src/struct_parameters.c[lines=42..55]
2033 -----------------------
2034
2035 NOTE: In both example we use an explicit value in `will_return()` instead of the value of the field, "s.i".
2036 That is because it is not possible to use the value of a mocked value in `will_return()`.
2037 Remember, `expect()` does early collection.
2038 At the time of executing it, there is no parameter available, so the value must come from that run-time environment.
2039 Also, since we already explicitly know the value, we have to use it in the `when()` clause, there will be no uncertainty of what it should be.
2040 The only concern might be duplication of an explicit value, but that is not a big problem in a unittest, clarity over DRY, and you can easily fix that with a suitably named local variable.
2041
2042 === Capturing Parameters
2043
2044 TBD. Hint: this involves using `will_capture_parameter()`.
2045
2046
2047 == Special Cases
2048
2049 === Working with `doubles`
2050
2051 We are not talking about
2052 http://www.hostettler.net/blog/2014/05/18/fakes-stubs-dummy-mocks-doubles-and-all-that/[test doubles]
2053 here, but about values of C/C++ ``double`` type (a.k.a. double float.)
2054
2055 *Cgreen* is designed to make it easy and natural to write assertions and expectations.
2056 Many functions can be used for multiple data types, e.g. `is_equal_to()` applies to all integer type values, actually including pointers.
2057
2058 But the C language has its quirks.
2059 One of them is the fact that it is impossible to inspect the datatypes of values during run-time.
2060 This has e.g. forced the introduction of `is_equal_to_string()` to enable string comparisons.
2061
2062 ==== Assertions and Constraints
2063
2064 When it comes to double typed values this has spilled over even further.
2065 For double typed values we have
2066
2067 |==========================================================================
2068 | *Constraint*
2069 | `is_equal_to_double(value)`
2070 | `is_not_equal_to_double(value)`
2071 | `is_less_than_double(value)`
2072 | `is_greater_than_double(value)`
2073 |==========================================================================
2074
2075 But there is also the special assert that you must use when asserting doubles
2076
2077 |=========================================================
2078 | *Assertion*
2079 | `assert_that_double(expected, constraint)`
2080 |=========================================================
2081
2082 and the utility function
2083
2084 |====================
2085 | *Utility*
2086 | `significant_figures_for_assert_double_are(int figures)`
2087 |====================
2088
2089 And of course they are designed to go together.
2090 So, if you want to assert an expression yeilding a `double` typed value, you need to combine them:
2091
2092 [source,c]
2093 -----------------------------
2094 include::tutorial_src/double_tests1.c[lines=11..14]
2095 -----------------------------
2096
2097 NOTE: You have to use `assert_that_double()` and `is_equal_to_double()`
2098 together.
2099
2100 and you would get
2101
2102 -----------------------------
2103 include::tutorial_src/double1.out[lines=2..5]
2104 -----------------------------
2105
2106
2107 [[double_mocks]]
2108 ==== Double Mocks
2109
2110 The general mechanism *Cgreen* uses to transport values to and from mock functions is based on the simple idea that most types fit into a "large" integer and can be type converted to and from whatever type you need.
2111
2112 Since a `double float` will not fit into the same memory space as an integer *Cgreen* handles that by encapsulating ("boxing") the `double` into an area which is represented by the pointer to it.
2113 And that pointer can fit into the integer type value (`intptr_t`) that *Cgreen* uses to transport values into and out of `mock()`.
2114 To get the value back you "unbox" it.
2115
2116 There are two possible uses of `double` that you need to be aware of
2117
2118 1. When a parameter to the mocked function is of `double` type and needs to be matched in an constraint in an `expect()` call.
2119
2120 2. When the mock function itself should return a `double` type value.
2121
2122 In the test you should use the special `double` type constraints and the `will_return_double()` convenience function.
2123 In the mock function you will have to take care to box and unbox as required.
2124
2125 |=================================================================
2126 |*Boxing and unboxing in mock functions* | *Description*
2127 | `box_double(double value)` | Wrap the value in an allocated
2128 memory area and return a pointer
2129 to it
2130 | `unbox_double(BoxedDouble *box)` | Unwrap the value by freeing the
2131 area and returning the value
2132 |=================================================================
2133
2134 Here's an example of that:
2135
2136 [source,c]
2137 -----------------------------
2138 include::tutorial_src/double_tests1.c[lines=16..26]
2139 -----------------------------
2140
2141 <1> We can see that the parameter `d` to the mock function, since it is a
2142 `double`, it will have to be used as `box_double(d)` in the call to
2143 `mock()`.
2144 <2> The corresponding `expect()` uses a double constraint.
2145 <3> The mock function in this small example also returns a `double`.
2146 The `expect()` uses `will_return_double()` so the mock function needs to unbox the return value from `mock()` to be able to return the `double` type value.
2147
2148 NOTE: Strange errors may occur if you box and/or unbox or combine `double` constraints incorrectly.
2149
2150 [[floating_point_comparison_algorithm]]
2151 ==== Details of Floating Point Comparison Algorithm
2152
2153 The number of significant digits set with `significant_figures_for_assert_double_are()` specifies a _relative_ tolerance.
2154 Cgreen considers two double precision numbers +x+ and +y+ equal if their difference normalized by the larger of the two is smaller than +10^(1 - significant_figures)^+.
2155 Mathematically, we check that +|x - y| < max(|x|, |y|) * 10^(1 - significant_figures)^+.
2156
2157 Well documented subtleties arise when comparing floating point numbers close to zero using this algorithm.
2158 The article https://randomascii.wordpress.com/2012/02/25/comparing-floating-point-numbers-2012-edition/[Comparing Floating Point Numbers, 2012 Edition] by Bruce Dawson has an excellent discussion of the issue.
2159 The essence of the problem can be appreciated if we consider the special case where +y == 0+.
2160 In that case, our condition reduces to +|x| < |x| * 10^(1 - significant_figures)^+.
2161 After cancelling +|x|+ this simplifies to +1 < 10^(1 - significant_figures)^+.
2162 But this is only true if +significant_figures < 1+.
2163 In words this can be summarized by saying that, in a relative sense, _all_ numbers are very different from zero.
2164 To circumvent this difficulty we recommend to use a constraint of the following form when comparing numbers close to zero:
2165
2166 [source,c]
2167 -----------------------
2168 assert_that(fabs(x - y) < abs_tolerance);
2169 -----------------------
2170
2171
2172 === Using Cgreen with C{pp}
2173
2174 The examples in this guide uses the C langauge to shows how to use *CGreen*. You can also use *CGreen* with C++.
2175
2176 NOTE: The following needs expansion and more details as the support for C++ is extended.
2177
2178 All you have to do is
2179
2180 * Use the `cgreen` namespace by adding `using namespace cgreen;`
2181 at the beginning of the file with your tests
2182
2183 There is also one extra feature when you use C++, the `assert_throws` function.
2184
2185 NOTE: If you use the autodiscovering runner, as described in <<runner>>, and thus link your tests into a shared library, don't forget to link it with the same C++ library that was used to create the `cgreen-runner`.
2186
2187 == Context, System Under Test & Suites
2188
2189 As mentioned earlier, *Cgreen* promotes the behaviour driven style of test driving code.
2190 The thinking behind BDD is that we don't really want to test anything, if we just could specify the behaviour of our code and ensure that it actually behaves this way we would be fine.
2191
2192 This might seem like an age old dream, but when you think about it, there is actually very little difference in the mechanics from vanillla TDD.
2193 First we write how we want it, then implement it.
2194 But the small change in wording, from `test´ to `behaviour´, from `test that´ to `ensure that´, makes a huge difference in thinking, and also very often in quality of the resulting code.
2195
2196
2197 === The SUT - System Under Test
2198
2199 Since BDD talks about behaviour, there has to be something that we can talk about as having that wanted behaviour.
2200 This is usually called the SUT, the System Under Test.
2201 The "system" might be whatever we are testing, such as a C module ("MUT"), class ("CUT"), object ("OUT"), function ("FUT") or method ("MUT").
2202 We will stick with SUT in this document.
2203 To use *Cgreen* in BDD-ish mode you must define a name for it.
2204
2205 [source, c]
2206 -----------------------
2207 #include <cgreen/cgreen.h>
2208 Describe(SUT);
2209 -----------------------
2210
2211 *Cgreen* supports C++ and there you naturally have the objects and also the Class Under Test.
2212 But in plain C you will have to think about what is actually the "class" under test.
2213 E.g. in `sort_test.c` you might see
2214
2215 [source, c]
2216 ---------------------
2217 #include <cgreen/cgreen.h>
2218 Describe(Sorter);
2219
2220 Ensure(Sorter, can_sort_an_empty_list) {
2221 assert_that(sorter(NULL), is_null);
2222 }
2223 ---------------------
2224
2225 In this example you can clearly see what difference the BDD-ish style makes when it comes to naming.
2226 Convention, and natural language, dictates that typical names for what TDD would call tests, now starts with 'can' or 'finds' or other verbs, which makes the specification so much easier to read.
2227
2228 Yes, I wrote 'specification'. Because that is how BDD views what TDD basically calls a test suite. The suite specifies the behaviour of a `class´.
2229 (That's why some BDD frameworks draw on 'spec', like *RSpec*.)
2230
2231
2232 === Contexts and Before and After
2233
2234 The complete specification of the behaviour of a SUT might become long and require various forms of setup.
2235 When using TDD style you would probably break this up into multiple suites having their own `setup()` and `teardown()`.
2236
2237 With BDD-ish style we could consider a suite as a behaviour specification for our SUT 'in a particular context'.
2238 E.g.
2239
2240 [source, c]
2241 ------------------------
2242 #include <cgreen/cgreen.h>
2243
2244 Describe(shopping_basket_for_returning_customer);
2245
2246 Customer *customer;
2247
2248 BeforeEach(shopping_basket_for_returning_customer){
2249 customer = create_test_customer();
2250 login(customer);
2251 }
2252
2253 AfterEach(shopping_basket_for_returning_customer) {
2254 logout(customer);
2255 destroy_customer(customer);
2256 }
2257
2258 Ensure(shopping_basket_for_returning_customer, allows_use_of_discounts) {
2259 ...
2260 }
2261 ------------------------
2262
2263 The 'context' would then be `shopping_basket_for_returning_customer`, with the SUT being the shopping basket 'class'.
2264
2265 So 'context', 'system under test' and 'suite' are mostly interchangable concepts in *Cgreen* lingo.
2266 It's a named group of 'tests' that share the same `BeforeEach` and `AfterEach` and lives in the same source file.
2267
2268
2269
2270 [[auto-discovery]]
2271 == Automatic Test Discovery
2272
2273
2274 === Forgot to Add Your Test?
2275
2276 When we write a new test we focus on the details about the test we are trying to write.
2277 And writing tests is no trivial matter so this might well take a lot of brain power.
2278
2279 So, it comes as no big surprise, that sometimes you write your test and then forget to add it to the suite.
2280 When we run it it appears that it passed on the first try!
2281 Although this *should* really make you suspicious, sometimes you get so happy that you just continue with churning out more tests and more code.
2282 It's not until some (possibly looong) time later that you realize, after much headache and debugging, that the test did not actually pass.
2283 It was never even run!
2284
2285 There are practices to minimize the risk of this happening, such as always running the test as soon as you can set up the test.
2286 This way you will see it fail before trying to get it to pass.
2287
2288 But it is still a practice, something we, as humans, might fail to do at some point.
2289 Usually this happens when we are most stressed and in need of certainty.
2290
2291
2292 === The Solution - the 'cgreen-runner'
2293
2294 *Cgreen* gives you a tool to avoid not only the risk of this happening, but also the extra work and extra code.
2295 It is called the `cgreen-runner`.
2296
2297 The `cgreen-runner` should come with your *Cgreen* installation if your platform supports the technique that is required, which is 'programatic access to dynamic loading of libraries'.
2298 This means that a program can load an external library of code into memory and inspect it.
2299 Kind of self-inspection, or reflexion.
2300
2301 So all you have to do is to build a dynamically loadable library of all tests (and of course your objects under test and other necessary code).
2302 Then you can run the `cgreen-runner` and point it to the library.
2303 The runner will then load the library, enumerate all tests in it, and run every test.
2304
2305 It's automatic, and there is nothing to forget.
2306
2307
2308 [[runner]]
2309 === Using the Runner
2310
2311 Assuming your tests are in `first_test.c` the typical command to build your library using `gcc` would be
2312
2313 --------------------------
2314 $ gcc -shared -o first_test.so -fPIC first_test.c -lcgreen
2315 --------------------------
2316
2317 The `-fPIC` means to generate 'position independent code' which is required if you want to load the library dynamically.
2318 To explicitly state this is required on many platforms.
2319
2320 How to build a dynamically loadable shared library might vary a lot depending on your platform.
2321 Can't really help you there, sorry!
2322
2323 As soon as we have linked it we can run the tests using the `cgreen-runner` by just giving it the shared, dynamically loadable, object library as an argument:
2324
2325 -------------------------
2326 $ cgreen-runner first_test.so
2327 include::tutorial_src/runner1.out[]
2328 -------------------------
2329
2330 More or less exactly the same output as when we ran our first test in the beginning of this quickstart tutorial. We can see that the top level of the tests will be named as the library it was discovered in, and the second level is the context for our System Under Test, in this case 'Cgreen'.
2331 We also see that the context is mentioned in the failure message, giving a fairly obvious `Cgreen -> fails_this_test`.
2332
2333 Now we can actually delete the main function in our source code.
2334 We don't need all this, since the runner will discover all tests automatically.
2335
2336 [source,c]
2337 ------------------------
2338 include::tutorial_src/first_tests1.c[lines=15..20]
2339 ------------------------
2340
2341 It always feel good to delete code, right?
2342
2343 We can also select which test to run:
2344
2345 -------------------------
2346 $ cgreen-runner first_test.so Cgreen:this_test_should_fail
2347 include::tutorial_src/runner2.out[]
2348 -------------------------
2349
2350 We recommend the BDD notation to discover tests, and you indicate which context the test we want to run is in.
2351 In this example it is `Cgreen` so the test should be refered to as `Cgreen:this_test_should_fail`.
2352
2353 If you don't use the BDD notation there is actually a context anyway, it is called `default`.
2354
2355
2356 [[runner-options]]
2357 === Cgreen Runner Options
2358
2359 Once you get the build set up right for the cgreen-runner everything
2360 is fairly straight-forward. But you have a few options:
2361
2362 --xml <prefix>:: Instead of messages on stdout with the TextReporter,
2363 write results into one XML-file per suite or context,
2364 compatible with Hudson/Jenkins CI. The filename(s)
2365 will be `<prefix>-<suite>.xml`
2366 --suite <name>:: Name the top level suite
2367 --no-run:: Don't run the tests
2368 --verbose:: Show progress information and list discovered tests
2369 --colours:: Use colours (or colors) to emphasis result (requires ANSI-capable terminal)
2370 --quiet:: Output a single character per context (`.` pass, `S` suspended, `F` fail, `X` error) followed by a summary of the totals
2371
2372 The `verbose` option is particularly handy since it will give you the actual names of all tests discovered.
2373 So if you have long test names you can avoid mistyping them by copying and pasting from the output of `cgreen-runner --verbose`.
2374 It will also give the mangled name of the test which should make it easier to find in the debugger.
2375 Here's an example:
2376
2377 ------------------------
2378 include::tutorial_src/runner3.out[]
2379 ------------------------
2380
2381
2382 === Selecting Tests To Run
2383
2384 You can name a single test to be run by giving it as the last argument on the command line.
2385 The name should be in the format `<SUT>:<test>`.
2386 If not obvious you can get that name by using the `--verbose` command option which will show you all tests discovered and both there C/C++ and Cgreen names.
2387 Copying the Cgreen name from that output is an easy way to run only that particular test.
2388 When a single test is named it is run using `run_single_test()`.
2389 As described in <<tdd_with_cgreen>> this means that it is __not__ protected by `fork()`-ing it to run in its own process.
2390
2391 The `cgreen-runner` supports selecting tests with limited pattern matching.
2392 Using an asterisk as a simple 'match many' symbol you can say things like
2393
2394 --------------------
2395 $ cgreen-runner <library> Cgreen:*
2396 $ cgreen-runner <library> C*:*this*
2397 --------------------
2398
2399
2400 === Multiple Test Libraries
2401
2402 You can run tests in multiple libraries in one go by adding them to the `cgreen-runner` command:
2403
2404 -----------------------
2405 $ cgreen-runner first_set.so second_set.so ...
2406 -----------------------
2407
2408
2409 === Setup, Teardown and Custom Reporters
2410
2411 The `cgreen-runner` will only run setup and teardown functions if you use the BDD-ish style with `BeforeEach()` and `AfterEach()` as described above.
2412 The runner does not pickup `setup()` and `teardown()` added to suites, because it actually doesn't run suites.
2413 It discovers all tests and runs them one by one.
2414 The macros required by the BDD-ish style ensures that the corresponding `BeforeEach()` and `AfterEach()` are run before and after each test.
2415
2416 CAUTION: The `cgreen-runner` __will__ discover your tests in a shared library even if you don't use the BDD-ish style.
2417 But it will not be able to find and run the `setup()` and/or `teardown()` attached to your suite(s).
2418 This will probably cause your tests to fail or crash.
2419
2420 In case you have non-BDD style tests __without__ any `setup()` and/or `teardown()` you can still use the runner.
2421 The default suite/context where the tests live in this case is called `default`.
2422 But why don't you convert your tests to BDD notation?
2423 This removes the risk of frustrating trouble-shooting when you added `setup()` and `teardown()` and can't understand why they are not run...
2424
2425 So, the runner encourages you to use the BDD notation.
2426 But since we recommend that you do anyway, that's no extra problem if you are starting out from scratch.
2427 But see <<changing_style>> for some easy tips on how to get you there if you already have non-BDD tests.
2428
2429 You can choose between the TextReporter, which we have been seeing so far, and the built-in JUnit/Ant compatible XML-reporter using the `--xml` option.
2430 But it is not currently possible to use custom reporters as outlined in <<reporter>> with the runner.
2431
2432 If you require another custom reporter you need to resort to the standard, programatic, way of invoking your tests.
2433 For now...
2434
2435
2436 [[xensure]]
2437 === Skipping Tests
2438
2439 Sometimes you find that you need to temporarily remove a test, perhaps to do a refactoring when you have a failing test.
2440 Ignoring that test will allow you to do the refactoring while still in the green.
2441
2442 An old practice is then to comment it out.
2443 That is a slightly cumbersome.
2444 It is also hazardous habit as there is no indication of a missing test if you forget to uncomment it when you are done.
2445
2446 *Cgreen* offers a much better solution.
2447 You can just add an 'x' infront of the `Ensure` for the test and that test will be skipped.
2448
2449 [source, C]
2450 ----------------------------
2451 ...
2452 xEnsure(Reader, ...) {
2453 ...
2454 }
2455 ...
2456 ----------------------------
2457
2458 With this method, it is a one character change to temporarily ignore, and un-ignore, a test.
2459 It is also easily found using text searches through a complete source tree.
2460 *Cgreen* will also tally the skipped tests, so it is clearly visible that you have some skipped test when you run them.
2461
2462 NOTE: You can also programmatically decide to skip a test depending on some run-time information.
2463 You do that simply by checking for the condition and calling `skip_test()` which will tally the test as skipped.
2464
2465 NOTE: `skip_test()` does *not* exit your test function so you need to take care that continuing after the call does not trigger any unintended behaviour.
2466
2467
2468 [[changing_style]]
2469 == Changing Style
2470
2471 If you already have some TDD style *Cgreen* test suites, it is quite easy to change them over to BDD-ish style.
2472 Here are the steps required
2473
2474 * Add `Describe(SUT);`
2475
2476 * Turn your current setup function into a `BeforeEach()` definition by changing its signature to match the macro, or simply call the existing setup function from the BeforeEach().
2477 If you don't have any setup function you still need to define an empty `BeforeEach()`.
2478
2479 * Ditto for `AfterEach()`.
2480
2481 * Add the SUT to each `Ensure()` by inserting it as a first parameter.
2482
2483 * Change the call to add the tests to `add_test_with_context()` by
2484 adding the name of the SUT as the second parameter.
2485
2486 * Optionally remove the calls to `set_setup()` and `set_teardown()`.
2487
2488 Done.
2489
2490 If you want to continue to run the tests using a hand-coded runner,
2491 you can do that by keeping the setup and teardown functions and their
2492 corresponding `set_`-calls.
2493
2494 It's nice that this is a simple process, because you can change over from TDD style to BDD-ish style in small steps.
2495 You can convert one source file at a time, by just following the recipe above.
2496 Everything will still work as before but your tests and code will likely improve.
2497
2498 And once you have changed style you can fully benefit from the
2499 automatic discovery of tests as described in <<auto-discovery>>.
2500
2501
2502
2503 [[reporter]]
2504 == Changing Cgreen Reporting
2505
2506 Replacing the Reporter
2507 ~~~~~~~~~~~~~~~~~~~~~~
2508
2509 In every test suite so far, we have run the tests with this line...
2510
2511 [source,c]
2512 -----------------------
2513 return run_test_suite(our_tests(), create_text_reporter());
2514 -----------------------
2515
2516 We can change the reporting mechanism just by changing this call to create another reporter.
2517
2518
2519 [[builtin_reporters]]
2520 === Built-in Reporters
2521
2522 *Cgreen* has the following built-in reporters that you can choose from when your code runs the test suite.
2523
2524
2525 [options="header", cols=4]
2526 [options="header", cols=4]
2527 |====================================================================================
2528 | Reporter | Purpose
2529 | Signature | Note
2530 | Text | Human readable, with clear messages
2531 | `create_text_reporter(void)` |
2532 | XML | ANT/Jenkins compatible
2533 | `create_xml_reporter(const char *file_prefix)` | `file_prefix` is the prefix of the XML files generated.
2534 | CUTE | CUTE Eclipse-plugin (http://cute-test.org) compatible output
2535 | `create_cute_reporter(void)` |
2536 | CDash | CMake (http://cmake.org) dashboard
2537 | `create_cdash_reporter(CDashInfo *info)` | `info` is a structure defined in `cdash_reporter.h`
2538 |====================================================================================
2539
2540 If you write a runner function like in most examples above, you can just substitute which runner to create.
2541 If you use the `cgreen-runner` (<<auto-discovery>>) to dynamically find all your tests you can force it to use the XML-reporter with the `-x <prefix>` option.
2542
2543 NOTE: Currently `cgreen-runner` only supports the built-in text and XML reporters.
2544
2545
2546 === Rolling Our Own
2547
2548 Although *Cgreen* has a number of options, there are times when you'd like a different output from the reporter, the CUTE and CDash reporters are examples that grew out of such a need.
2549
2550 Perhaps your Continuous Integration server want the result in a different format, or you just don't like the text reporter...
2551
2552 Writing your own reporter is supported.
2553 And we'll go through how that can be done using an XML-reporter as an example.
2554
2555 NOTE: *Cgreen* already has an XML-reporter compatible with ANT/Jenkins, see <<builtin_reporters>>.
2556
2557 Here is the code for `create_text_reporter()`...
2558
2559 [source,c]
2560 -----------------------
2561 TestReporter *create_text_reporter(void) {
2562 TestReporter *reporter = create_reporter();
2563 if (reporter == NULL) {
2564 return NULL;
2565 }
2566 reporter->start_suite = &text_reporter_start_suite;
2567 reporter->start_test = &text_reporter_start_test;
2568 reporter->show_fail = &show_fail;
2569 reporter->show_skip = &show_skip;
2570 reporter->show_incomplete = &show_incomplete;
2571 reporter->finish_test = &text_reporter_finish_test;
2572 reporter->finish_suite = &text_reporter_finish;
2573 return reporter;
2574 }
2575 -----------------------
2576
2577 The `TestReporter` structure contains function pointers that control the reporting.
2578 When called from `create_reporter()` constructor, these pointers are set up with functions that display nothing.
2579 The text reporter code replaces these with something more dramatic, and then returns a pointer to this new object.
2580 Thus the `create_text_reporter()` function effectively extends the object from `create_reporter()`.
2581
2582 The text reporter only outputs content at the start of the first test, at the end of the test run to display the results, when a failure occurs, and when a test fails to complete.
2583 A quick look at the `text_reporter.c` file in *Cgreen* reveals that the overrides just output a message and chain to the versions in `reporter.h`.
2584
2585 To change the reporting mechanism ourselves, we just have to know a little about the methods in the `TestReporter` structure.
2586
2587
2588 === The TestReporter Structure
2589
2590 The *Cgreen* `TestReporter` is a pseudo class that looks
2591 something like...
2592
2593 [source,c]
2594 -----------------------
2595 typedef struct _TestReporter TestReporter;
2596 struct _TestReporter {
2597 void (*destroy)(TestReporter *reporter);
2598 void (*start_suite)(TestReporter *reporter, const char *name, const int count);
2599 void (*start_test)(TestReporter *reporter, const char *name);
2600 void (*show_pass)(TestReporter *reporter, const char *file, int line,
2601 const char *message, va_list arguments);
2602 void (*show_skip)(TestReporter *reporter, const char *file, int line);
2603 void (*show_fail)(TestReporter *reporter, const char *file, int line,
2604 const char *message, va_list arguments);
2605 void (*show_incomplete)(TestReporter *reporter, const char *file, int line,
2606 const char *message, va_list arguments);
2607 void (*assert_true)(TestReporter *reporter, const char *file, int line, int result,
2608 const char * message, ...);
2609 void (*finish_test)(TestReporter *reporter, const char *file, int line);
2610 void (*finish_suite)(TestReporter *reporter, const char *file, int line);
2611 int passes;
2612 int failures;
2613 int exceptions;
2614 void *breadcrumb;
2615 int ipc;
2616 void *memo;
2617 void *options;
2618 };
2619 -----------------------
2620
2621 The first block are the methods that can be overridden:
2622
2623
2624 `void (*destroy)(TestReporter *reporter)`::
2625
2626 This is the destructor for the default structure.
2627 If this is overridden, then the overriding function must call `destroy_reporter(TestReporter *reporter)` to finish the clean up.
2628
2629
2630 `void (*start_suite)(TestReporter *reporter, const char *name, const int count)`::
2631
2632 This is the first of the callbacks.
2633 At the start of each test suite *Cgreen* will call this method on the reporter with the name of the suite being entered and the number of tests in that suite.
2634 The default version keeps track of the stack of tests in the `breadcrumb` pointer of `TestReporter`.
2635 If you make use of the breadcrumb functions, as the defaults do, then you will need to call `reporter_start_suite()` to keep the book-keeping in sync.
2636
2637
2638 `void (*start_test)(TestReporter *reporter, const char *name)`::
2639
2640 At the start of each test *Cgreen* will call this method on the reporter with the name of the test being entered.
2641 Again, the default version keeps track of the stack of tests in the `breadcrumb` pointer of `TestReporter`.
2642 If you make use of the breadcrumb functions, as the defaults do, then you will need to call `reporter_start_test()` to keep the book-keeping in sync.
2643
2644
2645 `void (*show_pass)(TestReporter *reporter, const char *file, int line, const char *message, va_list arguments)`::
2646
2647 This method is initially empty as most reporters see little point in reporting passing tests (but you might do), so there is no need to chain the call to any other function.
2648 Besides the pointer to the reporter structure, *Cgreen* also passes the file name of the test, the line number of failed assertion, the message to show and any additional parameters to substitute into the message.
2649 The message comes in as `printf()` style format string, and so the variable argument list should match the substitutions.
2650
2651
2652 `void (*show_fail)(TestReporter *reporter, const char *file, int line, const char *message, va_list arguments)`::
2653
2654 The partner of `show_pass()`, and the one you'll likely overload first.
2655
2656
2657 `void (*show_skip)(TestReporter *reporter, const char *file, int line)`::
2658
2659 This method will be called when a skipped test is encountered, see <<xensure>>.
2660
2661
2662 `void (*show_incomplete)(TestReporter *reporter, const char *file, int line, const char *message, va_list arguments)`::
2663
2664 When a test fails to complete, this is the handler that is called.
2665 As it's an unexpected outcome, no message is received, but we do get the name of the test.
2666 The text reporter combines this with the breadcrumb to produce the exception report.
2667
2668
2669 `void (*assert_true)(TestReporter *reporter, const char *file, int line, int result, const char * message, ...)`::
2670
2671 This is not normally overridden and is really internal.
2672 It is the raw entry point for the test messages from the test suite.
2673 By default it dispatches the call to either `show_pass()` or `show_fail()`.
2674
2675
2676 `void (*finish_test)(TestReporter *reporter, const char *file, int line)`::
2677
2678 The counterpart to the `(*start_test)()` call.
2679 It is called on leaving the test.
2680 It needs to be chained to the `reporter_finish()` to keep track of the breadcrumb book keeping.
2681
2682
2683 `void (*finish_suite)(TestReporter *reporter, const char *file, int line)`::
2684
2685 The counterpart to the `(*start_suite)()` call called on leaving the test suite, and similar to the `(*finish_test)()` if your reporter needs a handle on that event too.
2686 The default text reporter chains both this and `(*finish_test)()` to the same function where it figures out if it is the end of the top level suite.
2687 If so, it prints the familiar summary of passes and fails.
2688
2689 NOTE: The `show_fail()` and `show_pass()` functions are called from the child process, i.e. the isolated process that is `fork()`:ed to run a single test case.
2690 All others, notably `start_...()`, `finish_...()`, `show_incomplete()` and `show_skip()` are run in the main (parent) process.
2691 This fact might be important since the processes do not share memory.
2692 Information is passed from the child to the parent using messaging performed within the `show_...()` functions.
2693
2694 The second block is simply resources and book keeping that the reporter can use to liven up the messages...
2695
2696 [horizontal]
2697 `passes`:: The number of passes so far.
2698 `skips`:: The number of tests that has been skipped by the `xEnsure` mechanism (see <<xensure>>)
2699 `failures`:: The number of failures generated so far.
2700 `exceptions`:: The number of test functions that have failed to complete so far.
2701 `breadcrumb`:: This is a pointer to the list of test names in the stack.
2702
2703 The `breadcrumb` pointer is different and needs a little explanation.
2704 Basically it is a stack, analogous to the breadcrumb trail you see on websites.
2705 Everytime a `start()` handler is invoked, the name is placed in this stack.
2706 When a `finish()` message handler is invoked, a name is popped off.
2707
2708 There are a bunch of utility functions in `cgreen/breadcrumb.h` that can read the state of this stack.
2709 Most useful are `get_current_from_breadcrumb()` which takes the breadcrumb pointer and returns the current test name, and `get_breadcrumb_depth()` which gives the current depth of the stack.
2710 A depth of zero means that the test run has finished.
2711
2712 If you need to traverse all the names in the breadcrumb, then you can call `walk_breadcrumb()`.
2713 Here is the full signature...
2714
2715 [source,c]
2716 -----------------------
2717 void walk_breadcrumb(Breadcrumb *breadcrumb, void (*walker)(const char *, void *), void *memo);
2718 -----------------------
2719
2720 The `void (*walker)(const char *, void *)` is a callback that will be
2721 passed the name of the test suite for each level of nesting.
2722
2723 It is also passed the `memo` pointer that was passed to the `walk_breadcrumb()` call.
2724 You can use this pointer for anything you want, as all *Cgreen* does is pass it from call to call.
2725 This is so aggregate information can be kept track of whilst still being reentrant.
2726
2727
2728 The last parts of the `TestReporter` structure are...
2729
2730 [horizontal]
2731 `ipc`:: This is an internal structure for handling the messaging between reporter and test suite.
2732 You shouldn't touch this.
2733
2734 `memo`:: By contrast, this is a spare pointer for your own expansion.
2735
2736 `options`:: A pointer to a reporter specific structure that can be used to set options.
2737 E.g. the textreporter defines the structure `TextReporterOptions` which can be used by calling code to define the use of colors when printing passes and failures.
2738 You set it with `set_reporter_options(*void)`.
2739
2740
2741 === An Example XML Reporter
2742
2743 Let's make things real with an example.
2744 Suppose we want to send the output from *Cgreen* in XML format, say for storing in a repository or for sending across the network.
2745
2746 NOTE: The `cgreen-runner` already has an XML-reporter that you can
2747 use if you need to produce Jenkins/ANT compatible XML output.
2748 See <<runner-options>>.
2749
2750 Suppose also that we have come up with the following format...
2751
2752 [source,xml]
2753 -----------------------
2754 <?xml?>
2755 <suite name="Top Level">
2756 <suite name="A Group">
2757 <test name="a_test_that_passes">
2758 </test>
2759 <test name="a_test_that_fails">
2760 <fail>
2761 <message>A failure</message>
2762 <location file="test_as_xml.c" line="8"/>
2763 </fail>
2764 </test>
2765 </suite>
2766 </suite>
2767 -----------------------
2768
2769 In other words a simple nesting of tests with only failures encoded.
2770 The absence of "fail" XML node is a pass.
2771
2772 Here is a test script, `test_as_xml.c` that we can use to construct the
2773 above output...
2774
2775 [source,c]
2776 -----------------------
2777 include::tutorial_src/test_as_xml0.c[]
2778 -----------------------
2779
2780 We can't use the auto-discovering `cgreen-runner` (see <<auto-discovery>>) here since we need to ensure that the nested suites are reported as a nested xml structure.
2781 And we're not actually writing real tests, just something that we can use to drive our new reporter.
2782
2783 The text reporter is used just to confirm that everything is working.
2784 So far it is.
2785
2786 -----------------------
2787 include::tutorial_src/test_as_xml0.out[]
2788 -----------------------
2789
2790 Our first move is to switch the reporter from text, to our
2791 not yet written XML version...
2792
2793 [source,c]
2794 -----------------------
2795 #include "xml_reporter.h"
2796 ...
2797 include::tutorial_src/test_as_xml1.c[lines=24..-1]
2798 -----------------------
2799
2800 We'll start the ball rolling with the `xml_reporter.h`
2801 header file...
2802
2803 [source,c]
2804 -----------------------
2805 include::tutorial_src/xml_reporter.h[]
2806 -----------------------
2807
2808 ...and the simplest possible reporter in `xml_reporter.c`.
2809
2810 [source,c]
2811 -----------------------
2812 include::tutorial_src/xml_reporter0.c[]
2813 -----------------------
2814
2815 One that outputs nothing.
2816
2817 -----------------------
2818 $ gcc -c test_as_xml.c
2819 $ gcc -c xml_reporter.c
2820 $ gcc xml_reporter.o test_as_xml.o -lcgreen -o xml
2821 $ ./xml
2822 -----------------------
2823
2824 Yep, nothing.
2825
2826 Let's add the outer XML tags first, so that we can see *Cgreen*
2827 navigating the test suite...
2828
2829 [source,c]
2830 -----------------------
2831 include::tutorial_src/xml_reporter1.c[]
2832 -----------------------
2833
2834 Although chaining to the underlying `reporter_start_*()` and `reporter_finish_*()` functions is optional, I want to make use of some of the facilities later.
2835
2836 Our output meanwhile, is making its first tentative steps...
2837
2838 [source,xml]
2839 -----------------------
2840 include::tutorial_src/test_as_xml1.out[]
2841 -----------------------
2842
2843 We don't require an XML node for passing tests, so the `show_fail()`
2844 function is all we need...
2845
2846 [source,c]
2847 -----------------------
2848 ...
2849 include::tutorial_src/xml_reporter2.c[lines=18..25]
2850 ...
2851 include::tutorial_src/xml_reporter2.c[lines=37..-1]
2852 -----------------------
2853
2854 We have to use `vprintf()` to handle the variable argument list passed to us.
2855 This will probably mean including the `stdarg.h` header as well as `stdio.h`.
2856
2857 This gets us pretty close to what we want...
2858
2859 [source,xml]
2860 -----------------------
2861 include::tutorial_src/test_as_xml2.out[]
2862 -----------------------
2863
2864 For completeness we should add a tag for a test that doesn't complete.
2865 We'll output this as a failure, although we don't bother with the
2866 location this time...
2867
2868 [source,c]
2869 -----------------------
2870 include::tutorial_src/xml_reporter3.c[lines=27..31]
2871 ...
2872 include::tutorial_src/xml_reporter3.c[lines=44..-1]
2873 -----------------------
2874
2875 All that's left then is the XML declaration and the thorny issue of indenting.
2876 Although the indenting is not strictly necessary, it would make the output a lot more readable.
2877
2878 Given that the test depth is kept track of for us with the `breadcrumb` object in the `TestReporter` structure, indentation will actually be quite simple.
2879 We'll add an `indent()` function that outputs the correct number of tabs...
2880
2881 [source,c]
2882 -----------------------
2883 include::tutorial_src/xml_reporter4.c[lines=7..12]
2884 -----------------------
2885
2886 The `get_breadcrumb_depth()` function just gives the current test depth as recorded in the reporters breadcrumb (from `cgreen/breadcrumb.h`).
2887 As that is just the number of tabs to output, the implementation is trivial.
2888
2889 We can then use this function in the rest of the code.
2890 Here is the complete listing...
2891
2892 [source,c]
2893 -----------------------
2894 include::tutorial_src/xml_reporter4.c[]
2895 -----------------------
2896
2897 And finally the desired output...
2898
2899 [source,xml]
2900 -----------------------
2901 include::tutorial_src/test_as_xml4.out[]
2902 -----------------------
2903
2904 Job done.
2905
2906 Possible other reporter customizations include reporters that write to
2907 `syslog`, talk to IDE plug-ins, paint pretty printed documents or just
2908 return a boolean for monitoring purposes.
2909
2910 == Advanced Usage
2911
2912 === Custom Constraints
2913
2914 Sometimes the built-in constraints that *Cgreen* provide are not sufficient.
2915 With *Cgreen* it is possible to create custom constraints, although you will be depending on some internal structures if you do so.
2916
2917 Here's how to implement a simple example custom constraint that asserts that the value is bigger than 5.
2918 We'll implement this using a static constraint since it does not take any parameter.
2919
2920 WARNING: static constraints are a bad idea...
2921
2922 First we need the actual compare function:
2923
2924 [source,c]
2925 -----------------------------
2926 include::tutorial_src/custom_constraint1.c[lines=1..1]
2927
2928 include::tutorial_src/custom_constraint1.c[lines=9..12]
2929 -----------------------------
2930
2931 And then the static constraint structure, for which we'll need some of
2932 *Cgreen*'s internal functions:
2933
2934 [source,c]
2935 -----------------------------
2936 include::tutorial_src/custom_constraint1.c[lines=2..3]
2937
2938 include::tutorial_src/custom_constraint1.c[lines=13..26]
2939 -----------------------------
2940
2941 This implementation can use a statically declared `Constraint` structure that is prefilled since it does not need to store the value to be checked.
2942 This static custom constraint can then be used directly in the `assert` like this:
2943
2944 [source,c]
2945 -----------------------------
2946 include::tutorial_src/custom_constraint1.c[lines=28..31]
2947 -----------------------------
2948
2949 To create a custom constraint that takes an input parameter, we need to add a function that creates a constraint structure that correctly saves the value to be checked, and, for convenience, a macro.
2950 This time we need to dig into how *Cgreen* stores expected values and we'll also make use of *Cgreen*'s utility function `string_dup()`.
2951
2952 [source,c]
2953 -----------------------------
2954 include::tutorial_src/custom_constraint2.c[lines=2..4]
2955
2956 include::tutorial_src/custom_constraint2.c[lines=9..28]
2957 -----------------------------
2958
2959 This gives a custom constraint that can be used in the `assert` in the
2960 same way as *Cgreen*'s built-in constraints:
2961
2962 [source,c]
2963 -----------------------------
2964 include::tutorial_src/custom_constraint2.c[lines=31..33]
2965 -----------------------------
2966
2967 The last, and definitely more complex, example is a constraint that takes two structures and compares fields in them.
2968 The constraint will, given a structure representing a piece and another structure representing a box, check if the piece can fit inside the box using a size field.
2969
2970 Assuming two "application" structures with `size` fields:
2971
2972 [source,c]
2973 -----------------------------
2974 include::tutorial_src/custom_constraint3.c[lines=9..17]
2975 -----------------------------
2976
2977 We want to be able to write a test like this:
2978
2979 [source,c]
2980 -----------------------------
2981 include::tutorial_src/custom_constraint3.c[lines=54..58]
2982 -----------------------------
2983
2984 To implement the `can_fit_in_box` constraint we first need a comparer
2985 function:
2986
2987 [source,c]
2988 -----------------------------
2989 include::tutorial_src/custom_constraint3.c[lines=19..22]
2990 -----------------------------
2991
2992 And this time we can't rely on *Cgreen*'s checker and message generating function `test_want()` which we used in the previous examples.
2993 So we also need a custom function that calls the comparison and formats a possible error message:
2994
2995 [source,c]
2996 -----------------------------
2997 include::tutorial_src/custom_constraint3.c[lines=24..36]
2998 -----------------------------
2999
3000 Finally we'll use both of those in the constraint creating function
3001 and add the convenience macro:
3002
3003 [source,c]
3004 -----------------------------
3005 include::tutorial_src/custom_constraint3.c[lines=38..52]
3006 -----------------------------
3007
3008 CAUTION: As stated above, using custom constraints makes your tests vulnurable to changes in *Cgreen*'s internals.
3009 Hopefully a method to avoid this will emerge in the future.
3010
3011 TIP: You can write custom constraints directly in a test file, but they can of course also be collected into a separately compiled module which is linked with your tests.
3012
3013
3014
3015 == Hints and Tips
3016
3017 CAUTION: This chapter is intended to contain tips for situations that you might need some help with, but it is nowhere near complete at this time.
3018
3019 [[cgreen-mocker]]
3020 === `cgreen-mocker` - Automated Mocking
3021
3022 Are you starting out with *Cgreen* on a largish legacy system?
3023 And there are loads and loads of functions to mock to get a unit under test?
3024
3025 You could try the `cgreen-mocker` that is supplied as a contributed part of the *Cgreen* source distribution.
3026
3027 It is a Python program that parses C language header files and tries to create a corresponding `.mock` file where each function declaration is replaced with a call to `mock()`.
3028
3029 -----------------
3030 Usage:
3031 cgreen-mocker.py <headerfile> { <cpp_directive> }
3032 <headerfile>: file with function declarations that you want
3033 to mock
3034 <cpp_directive>: any 'cpp' directive but most useful is e.g.
3035 "-I <directory>" to ensure cpp finds files.
3036 -----------------
3037
3038 So given a header file containing lines like
3039
3040 [source,c]
3041 ----------------------------
3042 extern CgreenValue make_cgreen_integer_value(intptr_t integer);
3043 extern CgreenValue make_cgreen_string_value(const char *string);
3044 ----------------------------
3045
3046 `cgreen-mocker` will, given that there are no errors, print something
3047 like this on the screen:
3048
3049 [source,c]
3050 ----------------------------
3051 CgreenValue make_cgreen_integer_value(intptr_t integer) {
3052 return mock(integer);
3053 }
3054
3055 CgreenValue make_cgreen_string_value(const char *string) {
3056 return mock(string);
3057 }
3058 ----------------------------
3059
3060 Of course, you would pipe this output to a file.
3061
3062 To use `cgreen-mocker` you need Python, and the following packages:
3063
3064 * `packaging` -- (https://github.com/pypa/packaging)
3065
3066 * `pycparser` -- (https://github.com/eliben/pycparser)
3067
3068 These can easily be installed with:
3069
3070 ----------------
3071 $ pip install -r requirements.txt
3072 ----------------
3073
3074 NOTE: `cgreen-mocker` is an unsupported contribution to the *Cgreen*
3075 project by Thomas Nilefalk.
3076
3077
3078 === Compiler Error Messages
3079
3080 Sometimes you might get cryptic and strange error messages from the compiler.
3081 Since *Cgreen* uses some C/C++ macro magic this can happen and the error messages might not be straight forward to interpret.
3082
3083 Here are some examples, but the exact messages differ between compilers and versions.
3084
3085 |=========================================================
3086 |*Compiler error message* |*Probable cause...*
3087 |`"contextFor<X>" is undeclared here` | Missing `Describe(<X>);`
3088 |`undefined reference to 'AfterEach_For_<X>'`| Missing `AfterEach(<X>)`
3089 |`CgreenSpec__<X>__<Y>__ is undeclared` | Missing test subject/context in the `Ensure` of a BDD style test
3090 |`use of undeclared identifier 'contextFor<X>'` | Missing `Describe(<X>);`
3091 |=========================================================
3092
3093
3094 === Signed, Unsigned, Hex and Byte
3095
3096 *Cgreen* attempts to handle primitive type comparisons with a single constraint, `is_equal_to()`.
3097 This means that it must store the actual and expected values in a form that will accomodate all possible values that primitive types might take, typically an `intptr_t`.
3098
3099 This might sometimes cause unexpected comparisons since all actual values will be cast to match `intptr_t`, which is a signed value.
3100 E.g.
3101
3102 [source, c]
3103 ------------------------------
3104 Ensure(Char, can_compare_byte) {
3105 char chars[4] = {0xaa, 0xaa, 0xaa, 0};
3106 assert_that(chars[0], is_equal_to(0xaa));
3107 }
3108 ------------------------------
3109
3110 On a system which considers `char` to be signed this will cause the
3111 following *Cgreen* assertion error:
3112
3113 ------------------------------
3114 char_tests.c:11: Failure: Char -> can_compare_byte
3115 Expected [chars[0]] to [equal] [0xaa]
3116 actual value: [-86]
3117 expected value: [170]
3118 ------------------------------
3119
3120 This is caused by the C rules forcing an implicit cast of the `signed char` to `intptr_t` by sign-extension.
3121 This might not be what you expected.
3122 The correct solution, by any standard, is to cast the actual value to `unsigned char` which will then be interpreted correctly.
3123 And the test passes.
3124
3125 NOTE: Casting to `unsigned` will not always suffice since that is interpreted as `unsigned int` which will cause a sign-extension from the `signed char` and might or might not work depending on the size of `int` on your machine.
3126
3127 In order to reveal what really happens you might want to see the actual and expected values in hex. This can easily be done with the `is_equal_to_hex()`.
3128
3129 [source, c]
3130 ------------------------------
3131 Ensure(Char, can_compare_byte) {
3132 char chars[4] = {0xaa, 0xaa, 0xaa, 0};
3133 assert_that(chars[0], is_equal_to_hex(0xaa));
3134 }
3135 ------------------------------
3136
3137 This might make the mistake easier to spot:
3138
3139 ------------------------------
3140 char_tests.c:11: Failure: Char -> can_compare_byte
3141 Expected [chars[0]] to [equal] [0xaa]
3142 actual value: [0xfffffffffffffaa]
3143 expected value: [0xaa]
3144 ------------------------------
3145
3146
3147 === Cgreen and Coverage
3148
3149 *Cgreen* is compatible with coverage tools, in particular `gcov`/`lcov`.
3150 So generating coverage data for your application should be straight forward.
3151
3152 This is what you need to do (using `gcc` or `clang`):
3153
3154 - compile with `-ftest-coverage` and `-fprofile-arcs`
3155 - run tests
3156 - `lcov --directory . --capture --output-file coverage.info`
3157 - `genhtml -o coverage coverage.info`
3158
3159 Your coverage data will be available in `coverage/index.html`.
3160
3161
3162 === Garbled Output
3163
3164 If the output from your *Cgreen* based tests appear garbled or duplicated, this can be caused by the way *Cgreen* terminates its test-running child process.
3165 In many unix-like environments the termination of a child process should be done with `_exit()`.
3166 However, this interfers severily with the ability to collect coverage data.
3167 As this is important for many of us, *Cgreen* instead terminates its child process with the much cruder `exit()` (note: no underscore).
3168
3169 Under rare circumstances this might have the unwanted effect of output becoming garbled and/or duplicated.
3170
3171 If this happens you can change that behaviour using an environment variable `CGREEN_CHILD_EXIT_WITH__EXIT` (note: two underscores).
3172 If set, *Cgreen* will terminate its test-running child process with the more POSIX-compliant `_exit()`.
3173 But as mentioned before, this is, at least at this point in time, incompatible with collecting coverage data.
3174
3175 So, it's coverage __or__ POSIX-correct child exits and guaranteed output consistency.
3176 You can't have both...
3177
3178 [appendix]
3179 == Legacy Style Assertions
3180
3181 Cgreen have been around for a while, developed and matured.
3182 There is an older style of assertions that was the initial version, a style that we now call the 'legacy style', because it was more aligned with the original, now older, unit test frameworks.
3183 If you are not interested in historical artifacts, I recommend that you skip this section.
3184
3185 But for completeness of documentation, here are the legacy style assertion macros:
3186
3187 |=========================================================
3188 |*Assertion* |*Description*
3189 | `assert_true(boolean)` | Passes if boolean evaluates true
3190 | `assert_false(boolean)` | Fails if boolean evaluates true
3191 | `assert_equal(first, second)` | Passes if 'first == second'
3192 | `assert_not_equal(first, second)` | Passes if 'first != second'
3193 | `assert_string_equal(char *, char *)` | Uses 'strcmp()' and passes if
3194 the strings are equal
3195 | `assert_string_not_equal(char *, char *)` | Uses 'strcmp()' and fails
3196 if the strings are equal
3197 |=========================================================
3198
3199 Each assertion has a default message comparing the two values.
3200 If you want to substitute your own failure messages, then you must use the `*_with_message()` counterparts...
3201
3202 |=========================================================
3203 |*Assertion*
3204 | `assert_true_with_message(boolean, message, ...)`
3205 | `assert_false_with_message(boolean, message, ...)`
3206 | `assert_equal_with_message(tried, expected, message, ...)`
3207 | `assert_not_equal_with_message(tried, unexpected, message, ...)`
3208 | `assert_string_equal_with_message(char *, char *, message, ...)`
3209 | `assert_string_not_equal_with_message(char *, char *, message, ...)`
3210 |=========================================================
3211
3212 All these assertions have an additional `char *` message parameter, which is the message you wished to display on failure.
3213 If this is set to `NULL`, then the default message is shown instead.
3214 The most useful assertion from this group is `assert_true_with_message()` as you can use that to create your own assertion functions with your own messages.
3215
3216 Actually the assertion macros have variable argument lists.
3217 The failure message acts like the template in `printf()`.
3218 We could change the test above to be...
3219
3220 [source,c]
3221 -----------------------------
3222 include::tutorial_src/strlen_tests4.c[lines=4..8]
3223 -----------------------------
3224
3225 This should produce a slightly more user friendly message when things go wrong.
3226 But, actually, Cgreens default messages are so good that you are encouraged to skip the legacy style and go for the more modern constraints style assertions.
3227 This is particularly true when you use the BDD style test notation.
3228
3229 IMPORTANT: We strongly recommend the use of BDD Style notation with constraints based assertions.
3230
3231
3232 [appendix]
3233 [[release-history]]
3234 == Release History
3235
3236 In this section we list the changes that are relevant to you as a user of *Cgreen* -- new features, renames, and changes in behaviour that might affect how you use it.
3237 For a detailed log of features, enhancements and bug fixes visit the projects repository on GitHub, https://github.com/cgreen-devs/cgreen.
3238
3239 Since 1.4.1 Cgreen has included the following C pre-processer definition variables
3240
3241 - `CGREEN_VERSION`, a SemVer string
3242 - `CGREEN_VERSION_MAJOR`
3243 - `CGREEN_VERSION_MINOR`
3244 - `CGREEN_VERSION_PATCH`
3245
3246 You can use them to conditionally check for Cgreen features introduced as declared in the following sections.
3247
3248 Since 1.2.0 Cgreen has featured a public version variable in the loaded library, `cgreen_library_version`.
3249 This is mainly used by the `cgreen-runner` to present version of the loaded library, but it can also be used to check for availability of features in the same way.
3250
3251 === Version 1.7.0
3252
3253 - `will_set_contents_of_output_parameter()` (and its older name `will_set_contents_of_parameter()`) now copies the source data at the time of the `expect()` call instead of just storing a pointer to it. The source no longer has to remain valid until the mocked function is called.
3254 - Added `will_set_scalar_output_parameter()` to set a scalar (integer, `bool`, `enum` or pointer) out parameter directly, without a throwaway local and a `sizeof`.
3255 - `will_return_by_value()` no longer needs the `size` argument; it is derived from the value with `sizeof`. The two-argument form still works.
3256 - A mock called with a `NULL` out parameter no longer crashes -- the write is simply skipped.
3257 - In quiet mode (`-q`) suspended (`xEnsure`) and failed tests are now visible: each context shows `.`/`S`/`F`/`X` and a summary of the totals is printed at the end.
3258
3259 === Version 1.6.5
3260
3261 - Added `skip_test()` to programatically skip an individual test
3262 - Allow multiple `Describe`s in a single source file
3263 - Renamed `will_set_contents_of_parameter()` to `will_set_contents_of_output_parameter()` for readability; the old name still works
3264 - Fixed C++ namespace handling for the constraint macros
3265 - Fixed segfaults when building with `CGREEN_WITH_STATIC_LIBRARY=ON`
3266 - The XML reporter no longer corrupts failure messages or captured output containing `%`
3267 - `is_equal_to_hex()` and the legacy `assert_equal()` no longer truncate 64-bit values in their failure messages
3268 - `cgreen_vector` now rejects a one-past-the-end index in `get`/`remove`, fixing an out-of-bounds access
3269
3270 (1.6.4 was tagged but never published; its changes are included here.)
3271
3272 === Version 1.6.3
3273
3274 - Fixed `will_capture_parameter()` on big-endian machines (found on s390x)
3275 - For an unexpected call to a mock, the failure now points to the test rather than the mocked function
3276
3277 === Version 1.6.2
3278
3279 - Fixed a bug in the CUTE reporter
3280 - Improved zsh compatibility for the completion script (manual activation required)
3281
3282 === Version 1.6.1
3283
3284 - Added `libxml2` as an alternative XML report formatter, enabled automatically when available
3285 - Side-effect constraints (`with_side_effect()`) are now evaluated last among an `expect()`'s constraints
3286
3287 === Version 1.6.0
3288
3289 - Reverted use of `libbfd` introduced in 1.5.0 due to portability issues and Debian deeming it to be a serious bug due to `libbfd` not having a stable interface
3290
3291 === Version 1.5.1
3292
3293 - Fixed a problem with `ends_with_string()` which randomly crashed
3294
3295 === Version 1.5.0
3296
3297 - Replaced calling `nm` with BFD library calls, this makes the `cgreen-runner` a bit more fiddly to build on some systems
3298 - Introduced `will_capture_parameter()`
3299
3300 === Version 1.4.0
3301
3302 - A memory leak in `will_return_by_value()` was fixed but now requires user deallocation.
3303
3304 === Version 1.3.0
3305
3306 - Renamed CgreenValueType values to avoid clash, now all start with `CGREEN_`
3307
3308 === Version 1.2.0
3309
3310 - Introduced `will_return_by_value()`
3311 - Introduced `with_side_effect()`
3312
3313 === Version 1.1.0
3314
3315 None.
3316
3317 === Version 1.0.0
3318
3319 First official non-beta release.
3320
3321
3322 [appendix]
3323 == License
3324
3325 Copyright (c) 2006-2021, Cgreen Development Team and contributors +
3326 (https://github.com/cgreen-devs/cgreen/graphs/contributors)
3327
3328 Permission to use, copy, modify, and/or distribute this software and
3329 its documentation for any purpose with or without fee is hereby
3330 granted, provided that the above copyright notice and this permission
3331 notice appear in all copies, regardless of form, including printed and
3332 compiled.
3333
3334 THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHORS DISCLAIMS ALL WARRANTIES
3335 WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
3336 MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR
3337 ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
3338 WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
3339 ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
3340 OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
3341
3342 [appendix]
3343 == Acknowledgements
3344
3345 Thanks to
3346
3347 - Marcus Baker <[email protected]> - initiator and substantial inital work
3348 - Matt Hargett <[email protected]> - upgrading to the modern BDD-ish syntax
3349 - João Freitas <[email protected]> - asciidoc documentation and Cmake build system
3350 - Thomas Nilefalk <[email protected]> - cgreen-runner and current maintainer
3351
3352 Thanks also go to @gardenia, @d-meiser, @stevemadsenblippar and others for their contributions.