virstringtest.c 32.0 KB
Newer Older
1
/*
E
Eric Blake 已提交
2
 * Copyright (C) 2012-2016 Red Hat, Inc.
3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library.  If not, see
 * <http://www.gnu.org/licenses/>.
 *
 * Author: Daniel P. Berrange <berrange@redhat.com>
 */

#include <config.h>

#include <stdlib.h>

#include "testutils.h"
26
#include "verify.h"
27
#include "virerror.h"
28
#include "viralloc.h"
29
#include "virfile.h"
30
#include "virlog.h"
31 32 33 34
#include "virstring.h"

#define VIR_FROM_THIS VIR_FROM_NONE

35 36
VIR_LOG_INIT("tests.stringtest");

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
struct testStreqData {
    const char *a;
    const char *b;
};

static int testStreq(const void *args)
{
    const struct testStreqData *data = args;
    int ret = -1;
    bool equal = true;
    bool streq_rv, strneq_rv;
    size_t i;

    if ((size_t) data->a ^ (size_t) data->b)
        equal = false;
    if (data->a && data->b) {
        for (i = 0; data->a[i] != '\0'; i++) {
            if (data->b[i] == '\0' ||
                data->a[i] != data->b[i]) {
                equal = false;
                break;
            }
        }
    }

    streq_rv = STREQ_NULLABLE(data->a, data->b);
    strneq_rv = STRNEQ_NULLABLE(data->a, data->b);

    if (streq_rv != equal) {
        virFilePrintf(stderr,
                      "STREQ not working correctly. Expected %d got %d",
                      (int) equal, (int) streq_rv);
        goto cleanup;
    }

    if (strneq_rv == equal) {
        virFilePrintf(stderr,
                      "STRNEQ not working correctly. Expected %d got %d",
                      (int) equal, (int) strneq_rv);
        goto cleanup;
    }

    ret = 0;
 cleanup:
    return ret;
}

84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101
struct testSplitData {
    const char *string;
    const char *delim;
    size_t max_tokens;
    const char **tokens;
};


struct testJoinData {
    const char *string;
    const char *delim;
    const char **tokens;
};

static int testSplit(const void *args)
{
    const struct testSplitData *data = args;
    char **got;
102 103
    size_t ntokens;
    size_t exptokens = 0;
104 105 106 107
    char **tmp1;
    const char **tmp2;
    int ret = -1;

108 109
    if (!(got = virStringSplitCount(data->string, data->delim,
                                    data->max_tokens, &ntokens))) {
110 111 112 113 114 115 116 117
        VIR_DEBUG("Got no tokens at all");
        return -1;
    }

    tmp1 = got;
    tmp2 = data->tokens;
    while (*tmp1 && *tmp2) {
        if (STRNEQ(*tmp1, *tmp2)) {
118
            virFilePrintf(stderr, "Mismatch '%s' vs '%s'\n", *tmp1, *tmp2);
119 120 121 122
            goto cleanup;
        }
        tmp1++;
        tmp2++;
123
        exptokens++;
124 125
    }
    if (*tmp1) {
126
        virFilePrintf(stderr, "Too many pieces returned\n");
127 128 129
        goto cleanup;
    }
    if (*tmp2) {
130
        virFilePrintf(stderr, "Too few pieces returned\n");
131 132 133
        goto cleanup;
    }

134 135 136 137 138 139 140 141
    if (ntokens != exptokens) {
        virFilePrintf(stderr,
                      "Returned token count (%zu) doesn't match "
                      "expected count (%zu)",
                      ntokens, exptokens);
        goto cleanup;
    }

142
    ret = 0;
143
 cleanup:
144
    virStringListFree(got);
145 146 147 148 149 150 151 152 153 154 155

    return ret;
}


static int testJoin(const void *args)
{
    const struct testJoinData *data = args;
    char *got;
    int ret = -1;

156
    if (!(got = virStringListJoin(data->tokens, data->delim))) {
157 158 159 160
        VIR_DEBUG("Got no result");
        return -1;
    }
    if (STRNEQ(got, data->string)) {
161
        virFilePrintf(stderr, "Mismatch '%s' vs '%s'\n", got, data->string);
162 163 164 165
        goto cleanup;
    }

    ret = 0;
166
 cleanup:
167 168 169 170 171
    VIR_FREE(got);

    return ret;
}

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

static int testAdd(const void *args)
{
    const struct testJoinData *data = args;
    char **list = NULL;
    char *got = NULL;
    int ret = -1;
    size_t i;

    for (i = 0; data->tokens[i]; i++) {
        char **tmp = virStringListAdd((const char **)list, data->tokens[i]);
        if (!tmp)
            goto cleanup;
        virStringListFree(list);
        list = tmp;
        tmp = NULL;
    }

    if (!list &&
        VIR_ALLOC(list) < 0)
        goto cleanup;

    if (!(got = virStringListJoin((const char **)list, data->delim))) {
        VIR_DEBUG("Got no result");
        goto cleanup;
    }

    if (STRNEQ(got, data->string)) {
        virFilePrintf(stderr, "Mismatch '%s' vs '%s'\n", got, data->string);
        goto cleanup;
    }

    ret = 0;
 cleanup:
    virStringListFree(list);
    VIR_FREE(got);
    return ret;
}


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
static int testRemove(const void *args)
{
    const struct testSplitData *data = args;
    char **list = NULL;
    size_t ntokens;
    size_t i;
    int ret = -1;

    if (!(list = virStringSplitCount(data->string, data->delim,
                                     data->max_tokens, &ntokens))) {
        VIR_DEBUG("Got no tokens at all");
        return -1;
    }

    for (i = 0; data->tokens[i]; i++) {
        virStringListRemove(&list, data->tokens[i]);
        if (virStringListHasString((const char **) list, data->tokens[i])) {
            virFilePrintf(stderr, "Not removed %s", data->tokens[i]);
            goto cleanup;
        }
    }

    if (list && list[0]) {
        virFilePrintf(stderr, "Not removed all tokens: %s", list[0]);
        goto cleanup;
    }

    ret = 0;
 cleanup:
    virStringListFree(list);
    return ret;
}


E
Eric Blake 已提交
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
static bool fail;

static const char *
testStrdupLookup1(size_t i)
{
    switch (i) {
    case 0:
        return "hello";
    case 1:
        return NULL;
    default:
        fail = true;
        return "oops";
    }
}

static size_t
testStrdupLookup2(size_t i)
{
    if (i)
        fail = true;
    return 5;
}

static int
testStrdup(const void *data ATTRIBUTE_UNUSED)
{
    char *array[] = { NULL, NULL };
    size_t i = 0;
    size_t j = 0;
    size_t k = 0;
    int ret = -1;
    int value;

    value = VIR_STRDUP(array[i++], testStrdupLookup1(j++));
    if (value != 1) {
282
        virFilePrintf(stderr, "unexpected strdup result %d, expected 1\n", value);
E
Eric Blake 已提交
283 284
        goto cleanup;
    }
J
John Ferlan 已提交
285
    /* coverity[dead_error_begin] */
E
Eric Blake 已提交
286
    if (i != 1) {
287
        virFilePrintf(stderr, "unexpected side effects i=%zu, expected 1\n", i);
E
Eric Blake 已提交
288 289
        goto cleanup;
    }
J
John Ferlan 已提交
290
    /* coverity[dead_error_begin] */
E
Eric Blake 已提交
291
    if (j != 1) {
292
        virFilePrintf(stderr, "unexpected side effects j=%zu, expected 1\n", j);
E
Eric Blake 已提交
293 294 295
        goto cleanup;
    }
    if (STRNEQ_NULLABLE(array[0], "hello") || array[1]) {
296 297
        virFilePrintf(stderr, "incorrect array contents '%s' '%s'\n",
                      NULLSTR(array[0]), NULLSTR(array[1]));
E
Eric Blake 已提交
298 299 300 301 302 303
        goto cleanup;
    }

    value = VIR_STRNDUP(array[i++], testStrdupLookup1(j++),
                        testStrdupLookup2(k++));
    if (value != 0) {
304
        virFilePrintf(stderr, "unexpected strdup result %d, expected 0\n", value);
E
Eric Blake 已提交
305 306
        goto cleanup;
    }
J
John Ferlan 已提交
307
    /* coverity[dead_error_begin] */
E
Eric Blake 已提交
308
    if (i != 2) {
309
        virFilePrintf(stderr, "unexpected side effects i=%zu, expected 2\n", i);
E
Eric Blake 已提交
310 311
        goto cleanup;
    }
J
John Ferlan 已提交
312
    /* coverity[dead_error_begin] */
E
Eric Blake 已提交
313
    if (j != 2) {
314
        virFilePrintf(stderr, "unexpected side effects j=%zu, expected 2\n", j);
E
Eric Blake 已提交
315 316
        goto cleanup;
    }
J
John Ferlan 已提交
317
    /* coverity[dead_error_begin] */
E
Eric Blake 已提交
318
    if (k != 1) {
319
        virFilePrintf(stderr, "unexpected side effects k=%zu, expected 1\n", k);
E
Eric Blake 已提交
320 321 322
        goto cleanup;
    }
    if (STRNEQ_NULLABLE(array[0], "hello") || array[1]) {
323 324
        virFilePrintf(stderr, "incorrect array contents '%s' '%s'\n",
                      NULLSTR(array[0]), NULLSTR(array[1]));
E
Eric Blake 已提交
325 326 327 328
        goto cleanup;
    }

    if (fail) {
329
        virFilePrintf(stderr, "side effects failed\n");
E
Eric Blake 已提交
330 331 332 333
        goto cleanup;
    }

    ret = 0;
334
 cleanup:
E
Eric Blake 已提交
335 336 337 338 339
    for (i = 0; i < ARRAY_CARDINALITY(array); i++)
        VIR_FREE(array[i]);
    return ret;
}

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
static int
testStrndupNegative(const void *opaque ATTRIBUTE_UNUSED)
{
    int ret = -1;
    char *dst;
    const char *src = "Hello world";
    int value;

    if ((value = VIR_STRNDUP(dst, src, 5)) != 1) {
        fprintf(stderr, "unexpected virStrndup result %d, expected 1\n", value);
        goto cleanup;
    }

    if (STRNEQ_NULLABLE(dst, "Hello")) {
        fprintf(stderr, "unexpected content '%s'", dst);
        goto cleanup;
    }

    VIR_FREE(dst);
    if ((value = VIR_STRNDUP(dst, src, -1)) != 1) {
        fprintf(stderr, "unexpected virStrndup result %d, expected 1\n", value);
        goto cleanup;
    }

    if (STRNEQ_NULLABLE(dst, src)) {
        fprintf(stderr, "unexpected content '%s'", dst);
        goto cleanup;
    }

    ret = 0;
370
 cleanup:
371 372 373
    VIR_FREE(dst);
    return ret;
}
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

static int
testStringSortCompare(const void *opaque ATTRIBUTE_UNUSED)
{
    const char *randlist[] = {
        "tasty", "astro", "goat", "chicken", "turducken",
    };
    const char *randrlist[] = {
        "tasty", "astro", "goat", "chicken", "turducken",
    };
    const char *sortlist[] = {
        "astro", "chicken", "goat", "tasty", "turducken",
    };
    const char *sortrlist[] = {
        "turducken", "tasty", "goat", "chicken", "astro",
    };
    int ret = -1;
    size_t i;

    qsort(randlist, ARRAY_CARDINALITY(randlist), sizeof(randlist[0]),
          virStringSortCompare);
    qsort(randrlist, ARRAY_CARDINALITY(randrlist), sizeof(randrlist[0]),
          virStringSortRevCompare);

    for (i = 0; i < ARRAY_CARDINALITY(randlist); i++) {
        if (STRNEQ(randlist[i], sortlist[i])) {
            fprintf(stderr, "sortlist[%zu] '%s' != randlist[%zu] '%s'\n",
                    i, sortlist[i], i, randlist[i]);
            goto cleanup;
        }
        if (STRNEQ(randrlist[i], sortrlist[i])) {
            fprintf(stderr, "sortrlist[%zu] '%s' != randrlist[%zu] '%s'\n",
                    i, sortrlist[i], i, randrlist[i]);
            goto cleanup;
        }
    }

    ret = 0;
 cleanup:
    return ret;
}


418 419 420 421 422 423 424 425 426 427
struct stringSearchData {
    const char *str;
    const char *regexp;
    size_t maxMatches;
    size_t expectNMatches;
    const char **expectMatches;
    bool expectError;
};

static int
428
testStringSearch(const void *opaque)
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
{
    const struct stringSearchData *data = opaque;
    char **matches = NULL;
    ssize_t nmatches;
    int ret = -1;

    nmatches = virStringSearch(data->str, data->regexp,
                               data->maxMatches, &matches);

    if (data->expectError) {
        if (nmatches != -1) {
            fprintf(stderr, "expected error on %s but got %zd matches\n",
                    data->str, nmatches);
            goto cleanup;
        }
    } else {
        size_t i;

        if (nmatches < 0) {
            fprintf(stderr, "expected %zu matches on %s but got error\n",
                    data->expectNMatches, data->str);
            goto cleanup;
        }

        if (nmatches != data->expectNMatches) {
            fprintf(stderr, "expected %zu matches on %s but got %zd\n",
                    data->expectNMatches, data->str, nmatches);
            goto cleanup;
        }

459
        if (virStringListLength((const char * const *)matches) != nmatches) {
460 461
            fprintf(stderr, "expected %zu matches on %s but got %zd matches\n",
                    data->expectNMatches, data->str,
462
                    virStringListLength((const char * const *)matches));
463 464 465 466 467 468 469 470 471 472 473 474 475 476 477
            goto cleanup;
        }

        for (i = 0; i < nmatches; i++) {
            if (STRNEQ(matches[i], data->expectMatches[i])) {
                fprintf(stderr, "match %zu expected '%s' but got '%s'\n",
                        i, data->expectMatches[i], matches[i]);
                goto cleanup;
            }
        }
    }

    ret = 0;

 cleanup:
478
    virStringListFree(matches);
479 480 481
    return ret;
}

482

P
Pavel Hrdina 已提交
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
struct stringMatchData {
    const char *str;
    const char *regexp;
    bool expectMatch;
};

static int
testStringMatch(const void *opaque)
{
    const struct stringMatchData *data = opaque;
    bool match;

    match = virStringMatch(data->str, data->regexp);

    if (data->expectMatch) {
        if (!match) {
            fprintf(stderr, "expected match for '%s' on '%s' but got no match\n",
                    data->regexp, data->str);
            return -1;
        }
    } else {
        if (match) {
            fprintf(stderr, "expected no match for '%s' on '%s' but got match\n",
                    data->regexp, data->str);
            return -1;
        }
    }

    return 0;
}


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
struct stringReplaceData {
    const char *haystack;
    const char *oldneedle;
    const char *newneedle;
    const char *result;
};

static int
testStringReplace(const void *opaque ATTRIBUTE_UNUSED)
{
    const struct stringReplaceData *data = opaque;
    char *result;
    int ret = -1;

    result = virStringReplace(data->haystack,
                              data->oldneedle,
                              data->newneedle);

    if (STRNEQ_NULLABLE(data->result, result)) {
        fprintf(stderr, "Expected '%s' but got '%s'\n",
                data->result, NULLSTR(result));
        goto cleanup;
    }

    ret = 0;

 cleanup:
    VIR_FREE(result);
    return ret;
}


547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563
struct stringToLongData {
    const char *str;
    const char *suffix;
    int si; /* syntax-check doesn't like bare 'i' */
    int si_ret;
    unsigned int ui;
    int ui_ret;
    /* No expected results for long: on 32-bit platforms, it is the
     * same as int, on 64-bit platforms it is the same as long long */
    long long ll;
    int ll_ret;
    unsigned long long ull;
    int ull_ret;
};

/* This test makes assumptions about our compilation platform that are
 * not guaranteed by POSIX.  Good luck to you if you are crazy enough
E
Eric Blake 已提交
564 565
 * to try and port libvirt to a platform with 16-bit int.  Gnulib
 * already assumes that signed integers are two's complement. */
566 567 568 569 570 571 572 573 574 575 576 577
verify(sizeof(int) == 4);
verify(sizeof(long) == sizeof(int) || sizeof(long) == sizeof(long long));
verify(sizeof(long long) == 8);

static int
testStringToLong(const void *opaque)
{
    const struct stringToLongData *data = opaque;
    int ret = 0;
    char *end;
    long l;
    unsigned long ul;
578 579 580 581 582 583 584
    bool negative;

    if (data->suffix)
        negative = !!memchr(data->str, '-',
                            strlen(data->str) - strlen(data->suffix));
    else
        negative = !!strchr(data->str, '-');
585

586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611
#define TEST_ONE(Str, Suff, Type, Fn, Fmt, Exp, Exp_ret) \
    do { \
        Type value = 5; \
        int result; \
        end = (char *) "oops"; \
        result = virStrToLong_ ## Fn(Str, Suff ? &end : NULL, \
                                     0, &value); \
        /* On failure, end is modified, value is unchanged */ \
        if (result != (Exp_ret)) { \
            fprintf(stderr, \
                    "type " #Fn " returned %d expected %d\n", \
                    result, Exp_ret); \
            ret = -1; \
        } \
        if (value != ((Exp_ret) ? 5 : Exp)) { \
            fprintf(stderr, \
                    "type " #Fn " value " Fmt " expected " Fmt "\n", \
                    value, ((Exp_ret) ? 5 : Exp)); \
            ret = -1; \
        } \
        if (Suff && STRNEQ_NULLABLE(Suff, end)) { \
            fprintf(stderr, \
                    "type " #Fn " end '%s' expected '%s'\n", \
                    NULLSTR(end), Suff); \
            ret = -1; \
        } \
612 613 614 615 616 617
    } while (0)

    TEST_ONE(data->str, data->suffix, int, i, "%d",
             data->si, data->si_ret);
    TEST_ONE(data->str, data->suffix, unsigned int, ui, "%u",
             data->ui, data->ui_ret);
618 619 620 621 622
    if (negative)
        TEST_ONE(data->str, data->suffix, unsigned int, uip, "%u", 0U, -1);
    else
        TEST_ONE(data->str, data->suffix, unsigned int, uip, "%u",
                 data->ui, data->ui_ret);
623 624 625 626 627 628 629 630 631

    /* We hate adding new API with 'long', and prefer 'int' or 'long
     * long' instead, since platform-specific results are evil */
    l = (sizeof(int) == sizeof(long)) ? data->si : data->ll;
    TEST_ONE(data->str, data->suffix, long, l, "%ld",
             l, (sizeof(int) == sizeof(long)) ? data->si_ret : data->ll_ret);
    ul = (sizeof(int) == sizeof(long)) ? data->ui : data->ull;
    TEST_ONE(data->str, data->suffix, unsigned long, ul, "%lu",
             ul, (sizeof(int) == sizeof(long)) ? data->ui_ret : data->ull_ret);
632 633 634 635 636
    if (negative)
        TEST_ONE(data->str, data->suffix, unsigned long, ulp, "%lu", 0UL, -1);
    else
        TEST_ONE(data->str, data->suffix, unsigned long, ulp, "%lu", ul,
                 (sizeof(int) == sizeof(long)) ? data->ui_ret : data->ull_ret);
637 638 639 640 641

    TEST_ONE(data->str, data->suffix, long long, ll, "%lld",
             data->ll, data->ll_ret);
    TEST_ONE(data->str, data->suffix, unsigned long long, ull, "%llu",
             data->ull, data->ull_ret);
642 643 644 645 646 647
    if (negative)
        TEST_ONE(data->str, data->suffix, unsigned long long, ullp, "%llu",
                 0ULL, -1);
    else
        TEST_ONE(data->str, data->suffix, unsigned long long, ullp, "%llu",
                 data->ull, data->ull_ret);
648 649 650 651 652 653 654

#undef TEST_ONE

    return ret;
}


655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696
struct stringToDoubleData {
    const char *str;
    const char *end_ptr;
    double res;
};

/* This test checks if double strings are successfully converted to double
 * number considering the byproduct string too. */
static int
testStringToDouble(const void *opaque)
{
    const struct stringToDoubleData *data = opaque;
    int ret = -1;
    char *end_ptr = NULL;
    double res = 0;

    /* end_ptr returns or a substring or an empty string.
     * It never returns a NULL pointer. */
    if ((ret = virStrToDouble(data->str,
                              data->end_ptr ? &end_ptr : NULL,
                              &res)) < 0) {
        fprintf(stderr, "Convert error of '%s', expected '%lf'\n",
                data->str, data->res);
        return ret;
    }

    if (res != data->res) {
        fprintf(stderr, "Returned '%lf', expected '%lf'\n",
                res, data->res);
        return -1;
    }

    /* Comparing substrings. */
    if (STRNEQ_NULLABLE(end_ptr, data->end_ptr)) {
        fprintf(stderr, "Expected substring '%s', but got '%s'\n",
                end_ptr, data->end_ptr);
        return -1;
    }

    return ret;
}

697 698 699
/* The point of this test is to check whether all members of the array are
 * freed. The test has to be checked using valgrind. */
static int
700
testVirStringListFreeCount(const void *opaque ATTRIBUTE_UNUSED)
701 702 703 704 705 706 707 708 709 710
{
    char **list;

    if (VIR_ALLOC_N(list, 4) < 0)
        return -1;

    ignore_value(VIR_STRDUP(list[0], "test1"));
    ignore_value(VIR_STRDUP(list[2], "test2"));
    ignore_value(VIR_STRDUP(list[3], "test3"));

711
    virStringListFreeCount(list, 4);
712 713 714 715 716

    return 0;
}


717
struct testStripData {
J
Ján Tomko 已提交
718 719 720 721 722 723
    const char *string;
    const char *result;
};

static int testStripIPv6Brackets(const void *args)
{
724
    const struct testStripData *data = args;
J
Ján Tomko 已提交
725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745
    int ret = -1;
    char *res = NULL;

    if (VIR_STRDUP(res, data->string) < 0)
        goto cleanup;

    virStringStripIPv6Brackets(res);

    if (STRNEQ_NULLABLE(res, data->result)) {
        fprintf(stderr, "Returned '%s', expected '%s'\n",
                NULLSTR(res), NULLSTR(data->result));
        goto cleanup;
    }

    ret = 0;

 cleanup:
    VIR_FREE(res);
    return ret;
}

746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768
static int testStripControlChars(const void *args)
{
    const struct testStripData *data = args;
    int ret = -1;
    char *res = NULL;

    if (VIR_STRDUP(res, data->string) < 0)
        goto cleanup;

    virStringStripControlChars(res);

    if (STRNEQ_NULLABLE(res, data->result)) {
        fprintf(stderr, "Returned '%s', expected '%s'\n",
                NULLSTR(res), NULLSTR(data->result));
        goto cleanup;
    }

    ret = 0;

 cleanup:
    VIR_FREE(res);
    return ret;
}
J
Ján Tomko 已提交
769

770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799
struct testFilterData {
    const char *string;
    const char *valid;
    const char *result;
};

static int testFilterChars(const void *args)
{
    const struct testFilterData *data = args;
    int ret = -1;
    char *res = NULL;

    if (VIR_STRDUP(res, data->string) < 0)
        goto cleanup;

    virStringFilterChars(res, data->valid);

    if (STRNEQ_NULLABLE(res, data->result)) {
        fprintf(stderr, "Returned '%s', expected '%s'\n",
                NULLSTR(res), NULLSTR(data->result));
        goto cleanup;
    }

    ret = 0;

 cleanup:
    VIR_FREE(res);
    return ret;
}

800 801 802 803 804
static int
mymain(void)
{
    int ret = 0;

805 806 807 808 809
#define TEST_STREQ(aa, bb) \
    do { \
        struct testStreqData streqData = {.a = aa, .b = bb}; \
        if (virTestRun("Streq", testStreq, &streqData) < 0) \
            ret = -1; \
810 811 812 813 814 815 816 817 818
    } while (0)

    TEST_STREQ("hello", "world");
    TEST_STREQ(NULL, NULL);
    TEST_STREQ(NULL, "");
    TEST_STREQ("", NULL);
    TEST_STREQ("", "");
    TEST_STREQ("hello", "hello");

819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839
#define TEST_SPLIT(str, del, max, toks) \
    do { \
        struct testSplitData splitData = { \
            .string = str, \
            .delim = del, \
            .max_tokens = max, \
            .tokens = toks, \
        }; \
        struct testJoinData joinData = { \
            .string = str, \
            .delim = del, \
            .tokens = toks, \
        }; \
        if (virTestRun("Split " #str, testSplit, &splitData) < 0) \
            ret = -1; \
        if (virTestRun("Join " #str, testJoin, &joinData) < 0) \
            ret = -1; \
        if (virTestRun("Add " #str, testAdd, &joinData) < 0) \
            ret = -1; \
        if (virTestRun("Remove " #str, testRemove, &splitData) < 0) \
            ret = -1; \
840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862
    } while (0)

    const char *tokens1[] = { NULL };
    TEST_SPLIT("", " ", 0, tokens1);

    const char *tokens2[] = { "", "", NULL };
    TEST_SPLIT(" ", " ", 0, tokens2);

    const char *tokens3[] = { "", "", "", NULL };
    TEST_SPLIT("  ", " ", 0, tokens3);

    const char *tokens4[] = { "The", "quick", "brown", "fox", NULL };
    TEST_SPLIT("The quick brown fox", " ", 0, tokens4);

    const char *tokens5[] = { "The quick ", " fox", NULL };
    TEST_SPLIT("The quick brown fox", "brown", 0, tokens5);

    const char *tokens6[] = { "", "The", "quick", "brown", "fox", NULL };
    TEST_SPLIT(" The quick brown fox", " ", 0, tokens6);

    const char *tokens7[] = { "The", "quick", "brown", "fox", "", NULL };
    TEST_SPLIT("The quick brown fox ", " ", 0, tokens7);

863 864 865
    const char *tokens8[] = { "gluster", "rdma", NULL };
    TEST_SPLIT("gluster+rdma", "+", 2, tokens8);

866
    if (virTestRun("strdup", testStrdup, NULL) < 0)
E
Eric Blake 已提交
867
        ret = -1;
868

869
    if (virTestRun("strdup", testStrndupNegative, NULL) < 0)
870 871
        ret = -1;

872
    if (virTestRun("virStringSortCompare", testStringSortCompare, NULL) < 0)
873 874
        ret = -1;

875 876 877 878 879 880 881 882 883 884
#define TEST_SEARCH(s, r, x, n, m, e) \
    do { \
        struct stringSearchData data = { \
            .str = s, \
            .maxMatches = x, \
            .regexp = r, \
            .expectNMatches = n, \
            .expectMatches = m, \
            .expectError = e, \
        }; \
885
        if (virTestRun("virStringSearch " s, testStringSearch, &data) < 0) \
886
            ret = -1; \
887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909
    } while (0)

    /* error due to missing () in regexp */
    TEST_SEARCH("foo", "bar", 10, 0, NULL, true);

    /* error due to too many () in regexp */
    TEST_SEARCH("foo", "(b)(a)(r)", 10, 0, NULL, true);

    /* None matching */
    TEST_SEARCH("foo", "(bar)", 10, 0, NULL, false);

    /* Full match */
    const char *matches1[] = { "foo" };
    TEST_SEARCH("foo", "(foo)", 10, 1, matches1, false);

    /* Multi matches */
    const char *matches2[] = { "foo", "bar", "eek" };
    TEST_SEARCH("1foo2bar3eek", "([a-z]+)", 10, 3, matches2, false);

    /* Multi matches, limited returns */
    const char *matches3[] = { "foo", "bar" };
    TEST_SEARCH("1foo2bar3eek", "([a-z]+)", 2, 2, matches3, false);

910 911 912 913 914 915 916 917 918
#define TEST_MATCH(s, r, m) \
    do { \
        struct stringMatchData data = { \
            .str = s, \
            .regexp = r, \
            .expectMatch = m, \
        }; \
        if (virTestRun("virStringMatch " s, testStringMatch, &data) < 0) \
            ret = -1; \
P
Pavel Hrdina 已提交
919 920 921 922 923 924
    } while (0)

    TEST_MATCH("foo", "foo", true);
    TEST_MATCH("foobar", "f[o]+", true);
    TEST_MATCH("foobar", "^f[o]+$", false);

925 926 927 928 929 930 931 932
#define TEST_REPLACE(h, o, n, r) \
    do { \
        struct stringReplaceData data = { \
            .haystack = h, \
            .oldneedle = o, \
            .newneedle = n, \
            .result = r \
        }; \
933
        if (virTestRun("virStringReplace " h, testStringReplace, &data) < 0) \
934
            ret = -1; \
935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955
    } while (0)

    /* no matches */
    TEST_REPLACE("foo", "bar", "eek", "foo");

    /* complete match */
    TEST_REPLACE("foo", "foo", "bar", "bar");

    /* middle match */
    TEST_REPLACE("foobarwizz", "bar", "eek", "fooeekwizz");

    /* many matches */
    TEST_REPLACE("foofoofoofoo", "foo", "bar", "barbarbarbar");

    /* many matches */
    TEST_REPLACE("fooooofoooo", "foo", "bar", "barooobaroo");

    /* different length old/new needles */
    TEST_REPLACE("fooooofoooo", "foo", "barwizzeek", "barwizzeekooobarwizzeekoo");
    TEST_REPLACE("fooooofoooo", "foooo", "foo", "fooofoo");

956 957 958 959 960 961 962 963 964
#define TEST_STRTOL(str, suff, i, i_ret, u, u_ret, \
                    ll, ll_ret, ull, ull_ret) \
    do { \
        struct stringToLongData data = { \
            str, suff, i, i_ret, u, u_ret, ll, ll_ret, ull, ull_ret, \
        }; \
        if (virTestRun("virStringToLong '" str "'", testStringToLong, \
                       &data) < 0) \
            ret = -1; \
965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020
    } while (0)

    /* Start simple */
    TEST_STRTOL("0", NULL, 0, 0, 0U, 0, 0LL, 0, 0ULL, 0);

    /* All your base are belong to us */
    TEST_STRTOL("0x0", NULL, 0, 0, 0U, 0, 0LL, 0, 0ULL, 0);
    TEST_STRTOL("0XaB", NULL, 171, 0, 171U, 0, 171LL, 0, 171ULL, 0);
    TEST_STRTOL("010", NULL, 8, 0, 8U, 0, 8LL, 0, 8ULL, 0);

    /* Suffix handling */
    TEST_STRTOL("42", NULL, 42, 0, 42U, 0, 42LL, 0, 42ULL, 0);
    TEST_STRTOL("42", "",  42, 0, 42U, 0, 42LL, 0, 42ULL, 0);
    TEST_STRTOL("42.", NULL, 0, -1, 0U, -1, 0LL, -1, 0ULL, -1);
    TEST_STRTOL("42.", ".",  42, 0, 42U, 0, 42LL, 0, 42ULL, 0);

    /* Blatant invalid input */
    TEST_STRTOL("", "", 0, -1, 0U, -1, 0LL, -1, 0ULL, -1);
    TEST_STRTOL("", NULL, 0, -1, 0U, -1, 0LL, -1, 0ULL, -1);
    TEST_STRTOL("  ", "  ", 0, -1, 0U, -1, 0LL, -1, 0ULL, -1);
    TEST_STRTOL("  ", NULL, 0, -1, 0U, -1, 0LL, -1, 0ULL, -1);
    TEST_STRTOL("  -", "  -", 0, -1, 0U, -1, 0LL, -1, 0ULL, -1);
    TEST_STRTOL("  -", NULL, 0, -1, 0U, -1, 0LL, -1, 0ULL, -1);
    TEST_STRTOL("a", "a", 0, -1, 0U, -1, 0LL, -1, 0ULL, -1);
    TEST_STRTOL("a", NULL, 0, -1, 0U, -1, 0LL, -1, 0ULL, -1);

    /* Not a hex number, but valid when suffix expected */
    TEST_STRTOL("  0x", NULL, 0, -1, 0U, -1, 0LL, -1, 0ULL, -1);
    TEST_STRTOL("  0x", "x", 0, 0, 0U, 0, 0LL, 0, 0ULL, 0);

    /* Upper bounds */
    TEST_STRTOL("2147483647", NULL, 2147483647, 0, 2147483647U, 0,
                2147483647LL, 0, 2147483647ULL, 0);
    TEST_STRTOL("2147483648", NULL, 0, -1, 2147483648U, 0,
                2147483648LL, 0, 2147483648ULL, 0);
    TEST_STRTOL("4294967295", NULL, 0, -1, 4294967295U, 0,
                4294967295LL, 0, 4294967295ULL, 0);
    TEST_STRTOL("4294967296", NULL, 0, -1, 0U, -1,
                4294967296LL, 0, 4294967296ULL, 0);
    TEST_STRTOL("9223372036854775807", NULL, 0, -1, 0U, -1,
                9223372036854775807LL, 0, 9223372036854775807ULL, 0);
    TEST_STRTOL("9223372036854775808", NULL, 0, -1, 0U, -1,
                0LL, -1, 9223372036854775808ULL, 0);
    TEST_STRTOL("18446744073709551615", NULL, 0, -1, 0U, -1,
                0LL, -1, 18446744073709551615ULL, 0);
    TEST_STRTOL("18446744073709551616", NULL, 0, -1, 0U, -1,
                0LL, -1, 0ULL, -1);
    TEST_STRTOL("18446744073709551616", "", 0, -1, 0U, -1,
                0LL, -1, 0ULL, -1);

    /* Negative bounds */
    TEST_STRTOL("-0", NULL, 0, 0, 0U, 0, 0LL, 0, 0ULL, 0);
    TEST_STRTOL("-1", "", -1, 0, 4294967295U, 0,
                -1LL, 0, 18446744073709551615ULL, 0);
    TEST_STRTOL("-2147483647", NULL, -2147483647, 0, 2147483649U, 0,
                -2147483647LL, 0, 18446744071562067969ULL, 0);
1021
    TEST_STRTOL("-2147483648", NULL, INT32_MIN, 0, 2147483648U, 0,
1022 1023 1024 1025 1026 1027 1028 1029 1030 1031
                -2147483648LL, 0, 18446744071562067968ULL, 0);
    TEST_STRTOL("-2147483649", NULL, 0, -1, 2147483647U, 0,
                -2147483649LL, 0, 18446744071562067967ULL, 0);
    TEST_STRTOL("-4294967295", NULL, 0, -1, 1U, 0,
                -4294967295LL, 0, 18446744069414584321ULL, 0);
    TEST_STRTOL("-4294967296", NULL, 0, -1, 0U, -1,
                -4294967296LL, 0, 18446744069414584320ULL, 0);
    TEST_STRTOL("-9223372036854775807", NULL, 0, -1, 0U, -1,
                -9223372036854775807LL, 0, 9223372036854775809ULL, 0);
    TEST_STRTOL("-9223372036854775808", NULL, 0, -1, 0U, -1,
1032
                INT64_MIN, 0, 9223372036854775808ULL, 0);
1033 1034 1035 1036 1037 1038 1039
    TEST_STRTOL("-9223372036854775809", NULL, 0, -1, 0U, -1,
                0LL, -1, 9223372036854775807ULL, 0);
    TEST_STRTOL("-18446744073709551615", NULL, 0, -1, 0U, -1,
                0LL, -1, 1ULL, 0);
    TEST_STRTOL("-18446744073709551616", NULL, 0, -1, 0U, -1,
                0LL, -1, 0ULL, -1);

1040 1041 1042 1043 1044 1045 1046 1047
#define TEST_STRTOD(str, end_ptr, res) \
    do { \
        struct stringToDoubleData data = { \
            str, end_ptr, res, \
        }; \
        if (virTestRun("virStringToDouble '" str "'", \
                       testStringToDouble, &data) < 0) \
            ret = -1; \
1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077
    } while (0)

    /* Simple numbers. */
    TEST_STRTOD("0.0", NULL, 0);
    TEST_STRTOD("1.0", NULL, 1);
    TEST_STRTOD("3.14159", NULL, 3.14159);
    TEST_STRTOD("0.57721", NULL, 0.57721);

    /* Testing ending string. */
    TEST_STRTOD("2.718", "", 2.718);
    TEST_STRTOD("2.718 281 828 459", " 281 828 459", 2.718);
    TEST_STRTOD("2.718,281,828,459", ",281,828,459", 2.718);

    /* Scientific numbers. */
    TEST_STRTOD("3.14159e+000", NULL, 3.14159);
    TEST_STRTOD("2.00600e+003", NULL, 2006);
    TEST_STRTOD("1.00000e-010", NULL, 1e-010);

    /* Negative numbers. */
    TEST_STRTOD("-1.6180339887", NULL, -1.6180339887);
    TEST_STRTOD("-0.00031e-010", NULL, -0.00031e-010);

    /* Long numbers. */
    TEST_STRTOD("57089907708238388904078437636832797971793838081897.0",
                NULL,
                57089907708238388904078437636832797971793838081897.0);
    TEST_STRTOD("3.141592653589793238462643383279502884197169399375105",
                NULL,
                3.141592653589793238462643383279502884197169399375105);

1078 1079
    /* test virStringListFreeCount */
    if (virTestRun("virStringListFreeCount", testVirStringListFreeCount,
1080
                   NULL) < 0)
1081 1082
        ret = -1;

1083 1084 1085 1086 1087 1088 1089 1090 1091
#define TEST_STRIP_IPV6_BRACKETS(str, res) \
    do { \
        struct testStripData stripData = { \
            .string = str, \
            .result = res, \
        }; \
        if (virTestRun("Strip brackets from IPv6 " #str, \
                       testStripIPv6Brackets, &stripData) < 0) \
            ret = -1; \
J
Ján Tomko 已提交
1092 1093 1094 1095 1096 1097 1098 1099 1100 1101
    } while (0)

    TEST_STRIP_IPV6_BRACKETS(NULL, NULL);
    TEST_STRIP_IPV6_BRACKETS("[]", "[]");
    TEST_STRIP_IPV6_BRACKETS("[:]", ":");
    TEST_STRIP_IPV6_BRACKETS("[::1]", "::1");
    TEST_STRIP_IPV6_BRACKETS("[hello:", "[hello:");
    TEST_STRIP_IPV6_BRACKETS(":hello]", ":hello]");
    TEST_STRIP_IPV6_BRACKETS(":[]:", ":[]:");

1102 1103 1104 1105 1106 1107 1108 1109 1110
#define TEST_STRIP_CONTROL_CHARS(str, res) \
    do { \
        struct testStripData stripData = { \
            .string = str, \
            .result = res, \
        }; \
        if (virTestRun("Strip control chars from " #str, \
                       testStripControlChars, &stripData) < 0) \
            ret = -1; \
1111 1112 1113 1114 1115 1116 1117
    } while (0)

    TEST_STRIP_CONTROL_CHARS(NULL, NULL);
    TEST_STRIP_CONTROL_CHARS("\nhello \r hello\t", "\nhello \r hello\t");
    TEST_STRIP_CONTROL_CHARS("\x01H\x02" "E\x03L\x04L\x05O", "HELLO");
    TEST_STRIP_CONTROL_CHARS("\x01\x02\x03\x04HELL\x05O", "HELLO");
    TEST_STRIP_CONTROL_CHARS("\nhello \x01\x07hello\t", "\nhello hello\t");
1118 1119 1120 1121

#define TEST_FILTER_CHARS(str, filter, res) \
    do { \
        struct testFilterData filterData = { \
1122
            .string = str, \
1123
            .valid = filter, \
1124
            .result = res, \
1125 1126 1127 1128 1129 1130 1131 1132 1133
        }; \
        if (virTestRun("Filter chars from " #str, \
                       testFilterChars, &filterData) < 0) \
            ret = -1; \
    } while (0)

    TEST_FILTER_CHARS(NULL, NULL, NULL);
    TEST_FILTER_CHARS("hello 123 hello", "helo", "hellohello");

1134
    return ret == 0 ? EXIT_SUCCESS : EXIT_FAILURE;
1135 1136
}

1137
VIR_TEST_MAIN(mymain)