From a45c58f0b5a0d2884eff485def7f985d69d73b4e Mon Sep 17 00:00:00 2001 From: Sebastian Ramacher Date: Fri, 25 Jan 2013 23:19:26 +0100 Subject: [PATCH] Add tests for replace_substring --- tests/test_utils.c | 41 +++++++++++++++++++++++++++++++++++++++++ utils.c | 2 +- 2 files changed, 42 insertions(+), 1 deletion(-) diff --git a/tests/test_utils.c b/tests/test_utils.c index 6f927e2..a36b3a9 100644 --- a/tests/test_utils.c +++ b/tests/test_utils.c @@ -25,6 +25,38 @@ START_TEST(test_file_valid_extension_null) { fail_unless(file_valid_extension(NULL, "pdf") == false, NULL); } END_TEST +START_TEST(test_strings_replace_substrings_invalid) { + fail_unless(replace_substring(NULL, NULL, NULL) == NULL); + fail_unless(replace_substring("", NULL, NULL) == NULL); + fail_unless(replace_substring("", "", NULL) == NULL); +} END_TEST + +START_TEST(test_strings_replace_substrings_nothing_to_replace) { + fail_unless(replace_substring("test", "n", "y") == NULL); +} END_TEST + +START_TEST(test_strings_replace_substrings_1) { + char* result = replace_substring("test", "e", "f"); + fail_unless(result != NULL); + fail_unless(strncmp(result, "tfst", 5) == 0); + g_free(result); +} END_TEST + +START_TEST(test_strings_replace_substrings_2) { + char* result = replace_substring("test", "es", "f"); + fail_unless(result != NULL); + fail_unless(strncmp(result, "tft", 4) == 0); + g_free(result); +} END_TEST + +START_TEST(test_strings_replace_substrings_3) { + char* result = replace_substring("test", "e", "fg"); + fail_unless(result != NULL); + fail_unless(strncmp(result, "tfgst", 6) == 0); + g_free(result); +} END_TEST + + Suite* suite_utils() { TCase* tcase = NULL; @@ -42,5 +74,14 @@ Suite* suite_utils() tcase_add_test(tcase, test_file_valid_extension_null); suite_add_tcase(suite, tcase); + /* strings */ + tcase = tcase_create("strings"); + tcase_add_test(tcase, test_strings_replace_substrings_invalid); + tcase_add_test(tcase, test_strings_replace_substrings_nothing_to_replace); + tcase_add_test(tcase, test_strings_replace_substrings_1); + tcase_add_test(tcase, test_strings_replace_substrings_2); + tcase_add_test(tcase, test_strings_replace_substrings_3); + suite_add_tcase(suite, tcase); + return suite; } diff --git a/utils.c b/utils.c index 06de445..b72762d 100644 --- a/utils.c +++ b/utils.c @@ -461,7 +461,7 @@ replace_substring(const char* string, const char* old, const char* new) /* replace */ while (*string != '\0') { if (strstr(string, old) == string) { - strcpy(&ret[i], new); + strncpy(&ret[i], new, new_len); i += new_len; string += old_len; } else {