https://github.com/objarni/poorprogrammersccodecoverage
An hack using the preprocessor to get (non-branching) line code coverage
https://github.com/objarni/poorprogrammersccodecoverage
Last synced: 4 months ago
JSON representation
An hack using the preprocessor to get (non-branching) line code coverage
- Host: GitHub
- URL: https://github.com/objarni/poorprogrammersccodecoverage
- Owner: objarni
- License: mit
- Created: 2021-10-16T07:31:44.000Z (over 4 years ago)
- Default Branch: main
- Last Pushed: 2021-10-27T06:07:05.000Z (over 4 years ago)
- Last Synced: 2025-02-06T11:55:25.553Z (over 1 year ago)
- Size: 28.3 KB
- Stars: 1
- Watchers: 1
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# Poor Programmers C Code Coverage (or, if you prefer, PreProCessor Code Coverage)
A hack using the preprocessor to get (non-branching) code coverage.
# Idea
Why not use the `__LINE__` preprocessor directive to keep track of what lines have been executed?
Let's say we have simple function like this:
```cpp
void maybe_trigger(float temperature) {
if(temperature > 100) {
printf("Triggered at value %d.\n", temperature);
}
else {
printf(Not triggered yet.\n");
}
}
```
We want to write unit tests to cover as much as possible of this function, be we don't have the
tooling available. What can we do?
Well, we can define a macro C (for cover) like this:
```cpp
#define C (lineVisited[numLinesVisited++] = __LINE__);
int lineVisited[50000];
int numLinesVisited = 0;
```
`lineVisited` together with `numLinesVisited` keeps track of what lines are visited, using the
`__LINE__` preprocessor macro. They can e.g be defined just above the function we want to cover.
Then we can put this C macro at the start of every line we want to cover:
```cpp
void maybe_trigger(float temperature) { // Line 37
C if(temperature > 100) {
C printf("Triggered at value %d.\n", a);
C }
else { // Line 40
C printf(Not triggered yet.\n");
C } // Line 42
}
```
Note that we cannot put a coverage C on line 40, since it would break the syntax of the language
putting a statement inbetween '}' and 'else'.
Now we can write unit tests, which will update the lineVisited buffer, and using this
little helper function, we can display what coverage we have in percent, and what lines
are missing:
```cpp
void coverageReport(int lineStart, int lineEnd) {
int totalLines = lineEnd - lineStart + 1;
int numCovered = 0;
for(int line = lineStart; line <= lineEnd; line++) {
int covered = 0;
for(int i=0; i