Skip to content
Snippets Groups Projects
Commit 2e83335a authored by Bruce Cowan's avatar Bruce Cowan :airplane:
Browse files

Port average to unit test

parent b06c69cd
No related branches found
No related tags found
No related merge requests found
......@@ -18,16 +18,18 @@
* SPDX-License-Identifier: GPL-3.0-or-later
*/
#include <math.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include "array.h"
#include <array.h>
#define INT_TO_PTR(x) ((void *) (size_t) (x))
#define PTR_TO_INT(x) ((int) (size_t) (x))
static double
total_val (const Array *array,
get_total (const Array *array,
ValueFunc func)
{
double total = 0;
......@@ -40,10 +42,10 @@ total_val (const Array *array,
}
static double
average_val (const Array *array,
get_average (const Array *array,
ValueFunc func)
{
return total_val (array, func) / array_get_length (array);
return get_total (array, func) / array_get_length (array);
}
static double
......@@ -52,20 +54,6 @@ array_to_int (const void *data)
return (double) PTR_TO_INT (data);
}
static void
print_array (Array *array)
{
size_t length = array_get_length (array);
printf ("Array at %p is of length %zu\n", array, length);
printf ("Array has capacity %zu\n", array_get_capacity (array));
double total = total_val (array, array_to_int);
double average = average_val (array, array_to_int);
printf ("Array total is %lf\n", total);
printf ("Array average is %lf\n", average);
}
static Array *
create_test_array (size_t start,
size_t end)
......@@ -78,11 +66,40 @@ create_test_array (size_t start,
return array;
}
static bool
is_close (double a,
double b)
{
return fabs (a - b) <= (1e-8 + 1e-5 * b); // Values from numpy
}
int
main (void)
{
Array *array = create_test_array (0, 100);
print_array (array);
int start = 1;
int end = 100;
Array *array = create_test_array (start, end);
int n = end - start;
double expected_total = (n * (n+1)) / 2; // Only valid if starting from 1
double expected_average = expected_total / n;
double total = get_total (array, array_to_int);
if (!is_close (total, expected_total))
{
fprintf (stderr, "Expected total %lf, value returned was %lf\n",
expected_total, total);
return EXIT_FAILURE;
}
double average = get_average (array, array_to_int);
if (!is_close (average, expected_average))
{
fprintf (stderr, "Expected average %lf, value returned was %lf\n",
expected_average, average);
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
executable('testarray', 'testarray.c', link_with: lib, include_directories: lib_inc)
executable('average', 'average.c', link_with: lib, include_directories: lib_inc)
avg = executable('average', 'average.c', link_with: lib, include_directories: lib_inc)
executable('range', 'range.c', link_with: lib, include_directories: lib_inc)
test('average', avg)
\ No newline at end of file
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment