File: expect_check_data_advanced.c

package info (click to toggle)
cmocka 2.0.1-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 1,372 kB
  • sloc: ansic: 13,134; xml: 226; makefile: 23
file content (554 lines) | stat: -rw-r--r-- 18,214 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
/*
 * Advanced examples of expect_check_data() usage.
 *
 * This file demonstrates sophisticated patterns for complex testing scenarios:
 *
 * 1. FLOATING-POINT VALIDATION - Testing graphics APIs with epsilon tolerance
 * 2. STATEFUL CHECKERS - Validating call sequences and ordering
 * 3. PARTIAL STRUCT VALIDATION - Selectively checking struct fields
 * 4. COMPLEX RANGE CHECKING - Combining absolute and relative tolerances
 * 5. MULTIPLE INDEPENDENT CHECKERS - Different validators for different params
 *
 * These patterns go beyond basic parameter checking to enable testing of
 * complex, real-world APIs.
 */

#include <cmocka.h>
#include <string.h>
#include <math.h>

/*
 * ===========================================================================
 * PATTERN 1: Floating-Point Struct Validation with Epsilon
 * ===========================================================================
 *
 * Problem: Comparing floating-point values with == is unreliable due to
 * rounding errors. Graphics APIs often use floating-point coordinates.
 *
 * Solution: Use epsilon tolerance when comparing float/double values.
 */

/* Graphics API structure with floating-point coordinates */
typedef struct {
    float x;      /* X coordinate */
    float y;      /* Y coordinate */
    float width;  /* Rectangle width */
    float height; /* Rectangle height */
} Rectangle;

/* Mock graphics function */
void draw_rectangle(const Rectangle *rect, float rotation, const char *color);

void draw_rectangle(const Rectangle *rect, float rotation, const char *color)
{
    check_expected_ptr(rect);
    check_expected_float(rotation);
    check_expected_ptr(color);
}

/*
 * Checker configuration for rectangle validation
 *
 * This structure holds both the expected rectangle and the tolerance
 * (epsilon) to use when comparing floating-point values.
 */
typedef struct {
    Rectangle expected; /* Expected rectangle values */
    float epsilon;      /* Tolerance for floating-point comparison */
} RectangleChecker;

/*
 * Custom checker: validates rectangle with epsilon tolerance
 *
 * Floating-point comparison requires tolerance because:
 *   10.0f + 0.1f + 0.1f might not exactly equal 10.2f
 *
 * This checker compares each field with epsilon tolerance using fabsf().
 *
 * IMPORTANT: For floating-point types, actual.ptr points to the struct.
 * We can't use actual.float_val here because we're checking a pointer
 * to a Rectangle, not a single float.
 */
static int check_rectangle(CMockaValueData actual, CMockaValueData expected)
{
    RectangleChecker *checker = (RectangleChecker *)expected.ptr;
    Rectangle *actual_rect = (Rectangle *)actual.ptr;
    Rectangle *expected_rect = &checker->expected;
    float epsilon = checker->epsilon;

    /*
     * Compare each field with epsilon tolerance
     * fabsf() returns absolute value of the difference
     * If difference < epsilon, values are "equal enough"
     */
    return (fabsf(actual_rect->x - expected_rect->x) < epsilon &&
            fabsf(actual_rect->y - expected_rect->y) < epsilon &&
            fabsf(actual_rect->width - expected_rect->width) < epsilon &&
            fabsf(actual_rect->height - expected_rect->height) < epsilon);
}

/*
 * Test: Rectangle validation with epsilon
 *
 * This demonstrates validating a complex struct with floating-point fields.
 * Without epsilon tolerance, even small rounding errors would cause failures.
 */
static void test_rectangle_drawing(void **state)
{
    (void)state; /* unused */

    /* Define the expected rectangle */
    Rectangle default_rect = {.x = 10.0f,
                              .y = 20.0f,
                              .width = 100.0f,
                              .height = 50.0f};

    /*
     * Set up checker with 0.001f tolerance
     * This means values within 0.001 of expected are considered equal
     * E.g., 10.0001f would match 10.0f
     */
    RectangleChecker rect_checker = {.expected = default_rect,
                                     .epsilon = 0.001f};

    /* Use the epsilon-aware checker for the rectangle parameter */
    expect_check_data_count(draw_rectangle,
                            rect,
                            check_rectangle,
                            cast_ptr_to_cmocka_value(&rect_checker),
                            EXPECT_ALWAYS);

    /* Don't care about rotation or color for this test */
    expect_any_count(draw_rectangle, rotation, 3);
    expect_any_count(draw_rectangle, color, 3);

    /*
     * Make multiple calls with the same rectangle but different rotations
     * The rectangle checker validates all fields match within epsilon
     */
    draw_rectangle(&default_rect, 0.0f, "red");
    draw_rectangle(&default_rect, 45.0f, "blue");
    draw_rectangle(&default_rect, 90.0f, "green");
}

/*
 * ===========================================================================
 * PATTERN 2: Stateful Checker for Call Sequence Validation
 * ===========================================================================
 *
 * Problem: Sometimes you need to verify calls happen in a specific order
 * with specific values at each step (e.g., priority must increase).
 *
 * Solution: Maintain state in the checker struct to track call sequence.
 */

/*
 * Stateful sequence checker structure
 *
 * This maintains state across multiple checker invocations to validate
 * that function calls occur in a specific sequence.
 */
typedef struct {
    int call_count;            /* Current call number (incremented each call) */
    int max_calls;             /* Maximum expected calls (safety check) */
    int expected_sequence[10]; /* Array of expected values in order */
} SequenceChecker;

/*
 * Stateful checker: validates call sequence
 *
 * This checker maintains state (call_count) and validates that each
 * call provides the expected value for that position in the sequence.
 *
 * KEY INSIGHT: The checker struct persists across calls, so we can
 * increment call_count and use it to index into expected_sequence.
 *
 * Example: If expected_sequence = {1, 3, 5, 7, 9}, then:
 *   - First call must have priority = 1
 *   - Second call must have priority = 3
 *   - Third call must have priority = 5, etc.
 */
static int check_increasing_priority_sequence(CMockaValueData actual,
                                              CMockaValueData expected)
{
    SequenceChecker *checker = (SequenceChecker *)expected.ptr;
    int actual_priority = actual.int_val;

    /* Safety check: detect if more calls than expected */
    if (checker->call_count >= checker->max_calls) {
        return 0; /* Too many calls */
    }

    /* Get the expected value for this call position */
    int expected_priority = checker->expected_sequence[checker->call_count];

    /*
     * Increment call counter for next invocation
     * IMPORTANT: This modifies the checker state!
     */
    checker->call_count++;

    /* Validate the priority matches the expected sequence value */
    return (actual_priority == expected_priority);
}

/* Function to test sequence */
void process_task(int task_id, int priority);

void process_task(int task_id, int priority)
{
    check_expected_int(task_id);
    check_expected_int(priority);
}

/* Test: Validate call sequence */
static void test_priority_sequence(void **state)
{
    (void)state; /* unused */

    SequenceChecker seq_checker = {.call_count = 0,
                                   .max_calls = 5,
                                   .expected_sequence = {1, 3, 5, 7, 9}};

    expect_check_data_count(process_task,
                            priority,
                            check_increasing_priority_sequence,
                            cast_ptr_to_cmocka_value(&seq_checker),
                            EXPECT_ALWAYS);

    expect_any_count(process_task, task_id, 5);

    /* Priorities must be in the expected sequence */
    process_task(100, 1);
    process_task(101, 3);
    process_task(102, 5);
    process_task(103, 7);
    process_task(104, 9);

    /* Verify all expected calls were made */
    assert_int_equal(seq_checker.call_count, 5);
}

/* Example: Configuration struct validation */
typedef struct {
    int max_connections;
    int timeout_ms;
    const char *server_name;
    bool enable_ssl;
    int port;
} ServerConfig;

void configure_server(const ServerConfig *config);

void configure_server(const ServerConfig *config)
{
    check_expected_ptr(config);
}

typedef struct {
    ServerConfig expected;
    bool check_ssl;
    bool check_port;
} ConfigChecker;

static int check_server_config(CMockaValueData actual, CMockaValueData expected)
{
    ConfigChecker *checker = (ConfigChecker *)expected.ptr;
    const ServerConfig *actual_config = (const ServerConfig *)actual.ptr;
    const ServerConfig *expected_config = &checker->expected;

    /* Always check these fields */
    if (actual_config->max_connections != expected_config->max_connections) {
        return 0;
    }
    if (actual_config->timeout_ms != expected_config->timeout_ms) {
        return 0;
    }
    if (strcmp(actual_config->server_name, expected_config->server_name) != 0) {
        return 0;
    }

    /* Conditionally check these fields */
    if (checker->check_ssl) {
        if (actual_config->enable_ssl != expected_config->enable_ssl) {
            return 0;
        }
    }

    if (checker->check_port) {
        if (actual_config->port != expected_config->port) {
            return 0;
        }
    }

    return 1;
}

/* Test: Partial struct validation */
static void test_server_config(void **state)
{
    (void)state; /* unused */

    ServerConfig default_config = {.max_connections = 100,
                                   .timeout_ms = 5000,
                                   .server_name = "test-server",
                                   .enable_ssl = true,
                                   .port = 8080};

    ConfigChecker config_checker = {
        .expected = default_config,
        .check_ssl = true,
        .check_port = false /* Don't care about port for these tests */
    };

    expect_check_data_count(configure_server,
                            config,
                            check_server_config,
                            cast_ptr_to_cmocka_value(&config_checker),
                            EXPECT_ALWAYS);

    /* These should pass even with different ports */
    ServerConfig cfg1 = default_config;
    cfg1.port = 9090;
    configure_server(&cfg1);

    ServerConfig cfg2 = default_config;
    cfg2.port = 7070;
    configure_server(&cfg2);
}

/* Example: Multiple data types in one checker */
typedef struct {
    double expected_value;
    double tolerance_percent;
    double min_absolute;
    double max_absolute;
} DoubleRangeChecker;

static int check_double_in_range_or_near(CMockaValueData actual,
                                         CMockaValueData expected)
{
    DoubleRangeChecker *checker = (DoubleRangeChecker *)expected.ptr;
    double actual_val = actual.real_val;

    /* Check absolute range */
    if (actual_val < checker->min_absolute ||
        actual_val > checker->max_absolute)
    {
        return 0;
    }

    /* Check relative tolerance */
    double diff = fabs(actual_val - checker->expected_value);
    double tolerance = fabs(checker->expected_value *
                            checker->tolerance_percent / 100.0);

    return (diff <= tolerance);
}

void set_temperature(double celsius);

void set_temperature(double celsius)
{
    check_expected_double(celsius);
}

/* Test: Complex double validation */
static void test_temperature_range(void **state)
{
    (void)state; /* unused */

    /* Accept values near 20.0°C (±5%) but within -10 to 50 absolute range */
    DoubleRangeChecker temp_checker = {.expected_value = 20.0,
                                       .tolerance_percent = 5.0,
                                       .min_absolute = -10.0,
                                       .max_absolute = 50.0};

    expect_check_data_count(set_temperature,
                            celsius,
                            check_double_in_range_or_near,
                            cast_ptr_to_cmocka_value(&temp_checker),
                            EXPECT_ALWAYS);

    /* These should all pass */
    set_temperature(20.0); /* Exact match */
    set_temperature(19.0); /* Within 5% */
    set_temperature(21.0); /* Within 5% */
}

/*
 * ===========================================================================
 * PATTERN 5: Multiple Independent Checkers
 * ===========================================================================
 *
 * Problem: Different parameters need different validation logic.
 *
 * Solution: Use different checkers for different parameters, each with
 * their own validation rules and data.
 */

/* Checker for validating task IDs are in valid range */
typedef struct {
    int min_id;
    int max_id;
    const char *allowed_prefix; /* Not used in this example, but could be */
} IdChecker;

/*
 * ID range validator
 *
 * Simple range check for integer IDs.
 * Could be extended to check prefix, checksums, etc.
 */
static int check_valid_task_id(CMockaValueData actual, CMockaValueData expected)
{
    IdChecker *checker = (IdChecker *)expected.ptr;
    int actual_id = actual.int_val;

    /* ID must be in range */
    if (actual_id < checker->min_id || actual_id > checker->max_id) {
        return 0;
    }

    /* For this example, we'll just check the range */
    /* In a real scenario, you might validate ID format, checksums, etc. */
    return 1;
}

typedef struct {
    const char *allowed_prefixes[5];
    size_t num_prefixes;
} StringPrefixChecker;

static int check_string_prefix(CMockaValueData actual, CMockaValueData expected)
{
    StringPrefixChecker *checker = (StringPrefixChecker *)expected.ptr;
    const char *actual_str = (const char *)actual.ptr;

    for (size_t i = 0; i < checker->num_prefixes; i++) {
        const char *prefix = checker->allowed_prefixes[i];
        size_t prefix_len = strlen(prefix);

        if (strncmp(actual_str, prefix, prefix_len) == 0) {
            return 1;
        }
    }

    return 0;
}

void execute_command(int task_id, const char *command);

void execute_command(int task_id, const char *command)
{
    check_expected_int(task_id);
    check_expected_ptr(command);
}

/*
 * Test: Multiple independent checkers
 *
 * This demonstrates using completely different validation logic for
 * different parameters. The task_id uses range checking while the
 * command uses prefix matching - two separate checkers with different
 * data structures and logic.
 *
 * KEY INSIGHT: You can mix and match checkers freely. Each parameter
 * gets its own checker with its own validation rules.
 */
static void test_command_validation(void **state)
{
    (void)state; /* unused */

    /* Set up ID range checker (1000-9999) */
    IdChecker id_checker = {.min_id = 1000,
                            .max_id = 9999,
                            .allowed_prefix = "TASK"};

    /* Set up command prefix checker (must start with allowed prefix) */
    StringPrefixChecker cmd_checker = {
        .allowed_prefixes = {"GET_", "SET_", "DELETE_", "UPDATE_", NULL},
        .num_prefixes = 4};

    /*
     * Apply DIFFERENT checkers to DIFFERENT parameters
     * task_id: uses range validation
     * command: uses prefix validation
     */
    expect_check_data_count(execute_command,
                            task_id,
                            check_valid_task_id,
                            cast_ptr_to_cmocka_value(&id_checker),
                            EXPECT_ALWAYS);

    expect_check_data_count(execute_command,
                            command,
                            check_string_prefix,
                            cast_ptr_to_cmocka_value(&cmd_checker),
                            EXPECT_ALWAYS);

    /*
     * All these combinations should pass:
     * - IDs are all in [1000, 9999]
     * - Commands all start with allowed prefixes
     */
    execute_command(1000, "GET_STATUS");
    execute_command(5000, "SET_CONFIG");
    execute_command(9999, "DELETE_TEMP");
    execute_command(7777, "UPDATE_CACHE");
}

/*
 * ===========================================================================
 * SUMMARY OF ADVANCED PATTERNS
 * ===========================================================================
 *
 * This file demonstrated five sophisticated testing patterns:
 *
 * 1. FLOATING-POINT VALIDATION (test_rectangle_drawing)
 *    - Use epsilon tolerance for float/double comparison
 *    - Validate complex structs field-by-field
 *    - Essential for graphics, physics, scientific computing
 *
 * 2. STATEFUL SEQUENCE VALIDATION (test_priority_sequence)
 *    - Maintain state across checker calls
 *    - Validate call ordering and sequences
 *    - Useful for protocol testing, state machines
 *
 * 3. PARTIAL STRUCT VALIDATION (test_server_config)
 *    - Selectively validate only certain struct fields
 *    - Ignore fields that don't matter for the test
 *    - Reduces test brittleness
 *
 * 4. COMPLEX RANGE VALIDATION (test_temperature_range)
 *    - Combine absolute and relative tolerances
 *    - More sophisticated than simple min/max checking
 *    - Useful for testing with realistic constraints
 *
 * 5. MULTIPLE INDEPENDENT CHECKERS (test_command_validation)
 *    - Different parameters get different validators
 *    - Mix range checking, prefix checking, etc.
 *    - Maximum flexibility
 *
 * KEY TAKEAWAYS:
 * - Checkers can maintain state between calls
 * - Checkers can implement arbitrarily complex logic
 * - Different parameters can use completely different checkers
 * - Floating-point requires epsilon tolerance
 * - Checker structs must remain valid until all calls complete
 *
 * See expect_check_data_example.c for simpler patterns and basic usage.
 */

int main(void)
{
    const struct CMUnitTest tests[] = {
        cmocka_unit_test(test_rectangle_drawing),
        cmocka_unit_test(test_priority_sequence),
        cmocka_unit_test(test_server_config),
        cmocka_unit_test(test_temperature_range),
        cmocka_unit_test(test_command_validation),
    };

    return cmocka_run_group_tests(tests, NULL, NULL);
}