From aa75cefcef4109d636fd5f3cb4da5488a1b6ea88 Mon Sep 17 00:00:00 2001 From: Christian Brauner Date: Wed, 7 Sep 2016 17:51:33 +0200 Subject: [PATCH] tests: add unit tests for lxc_safe_int() Signed-off-by: Christian Brauner --- src/tests/lxc-test-utils.c | 33 +++++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) diff --git a/src/tests/lxc-test-utils.c b/src/tests/lxc-test-utils.c index 9f25419f7..46f8cf3ed 100644 --- a/src/tests/lxc-test-utils.c +++ b/src/tests/lxc-test-utils.c @@ -221,6 +221,7 @@ non_test_error: if (fret == EXIT_SUCCESS) return; exit(fret); +} void test_lxc_safe_uint(void) { @@ -251,6 +252,37 @@ void test_lxc_safe_uint(void) lxc_test_assert_abort((-ERANGE == lxc_safe_uint(uint_max, &n))); } +void test_lxc_safe_int(void) +{ + int ret; + signed int n; + size_t len = /* 2^64 = 21 - 1 */ 21; + char int_max[len]; + + ret = snprintf(int_max, len, "%ld", (signed long)INT_MAX + 1); + if (ret < 0 || (size_t)ret >= len) { + lxc_error("%s\n", "Failed to create string via snprintf()."); + exit(EXIT_FAILURE); + } + + lxc_test_assert_abort((0 == lxc_safe_int("1234345", &n)) && n == 1234345); + lxc_test_assert_abort((0 == lxc_safe_int(" 345", &n)) && n == 345); + lxc_test_assert_abort((0 == lxc_safe_int("-1234345", &n)) && n == -1234345); + lxc_test_assert_abort((0 == lxc_safe_int(" -345", &n)) && n == -345); + lxc_test_assert_abort((-EINVAL == lxc_safe_int(" g345", &n))); + lxc_test_assert_abort((-EINVAL == lxc_safe_int(" 3g45", &n))); + lxc_test_assert_abort((-EINVAL == lxc_safe_int(" 345g", &n))); + lxc_test_assert_abort((-EINVAL == lxc_safe_int("g345", &n))); + lxc_test_assert_abort((-EINVAL == lxc_safe_int("3g45", &n))); + lxc_test_assert_abort((-EINVAL == lxc_safe_int("345g", &n))); + lxc_test_assert_abort((-EINVAL == lxc_safe_int("g345 ", &n))); + lxc_test_assert_abort((-EINVAL == lxc_safe_int("3g45 ", &n))); + lxc_test_assert_abort((-EINVAL == lxc_safe_int("345g ", &n))); + lxc_test_assert_abort((-EINVAL == lxc_safe_int("g", &n))); + lxc_test_assert_abort((-EINVAL == lxc_safe_int(" g345", &n))); + lxc_test_assert_abort((-ERANGE == lxc_safe_int(int_max, &n))); +} + void test_lxc_string_replace(void) { char *s; @@ -310,6 +342,7 @@ int main(int argc, char *argv[]) test_lxc_deslashify(); test_detect_ramfs_rootfs(); test_lxc_safe_uint(); + test_lxc_safe_int(); exit(EXIT_SUCCESS); }