| 1 | /*
|
|---|
| 2 | * SPDX-FileCopyrightText: 2014 Vojtech Horky
|
|---|
| 3 | *
|
|---|
| 4 | * SPDX-License-Identifier: BSD-3-Clause
|
|---|
| 5 | */
|
|---|
| 6 |
|
|---|
| 7 | #include <stdio.h>
|
|---|
| 8 | #include <str.h>
|
|---|
| 9 | #include <pcut/pcut.h>
|
|---|
| 10 |
|
|---|
| 11 | #define BUFFER_SIZE 8192
|
|---|
| 12 | #define TEQ(expected, actual) PCUT_ASSERT_STR_EQUALS(expected, actual)
|
|---|
| 13 | #define TF(expected, format, ...) TEQ(expected, fmt(format, ##__VA_ARGS__))
|
|---|
| 14 |
|
|---|
| 15 | #define SPRINTF_TEST(test_name, expected_string, actual_format, ...) \
|
|---|
| 16 | PCUT_TEST(test_name) { \
|
|---|
| 17 | snprintf(buffer, BUFFER_SIZE, actual_format, ##__VA_ARGS__); \
|
|---|
| 18 | PCUT_ASSERT_STR_EQUALS(expected_string, buffer); \
|
|---|
| 19 | }
|
|---|
| 20 |
|
|---|
| 21 | PCUT_INIT;
|
|---|
| 22 |
|
|---|
| 23 | PCUT_TEST_SUITE(sprintf);
|
|---|
| 24 |
|
|---|
| 25 | static char buffer[BUFFER_SIZE];
|
|---|
| 26 |
|
|---|
| 27 | PCUT_TEST_BEFORE
|
|---|
| 28 | {
|
|---|
| 29 | memset(buffer, 0, BUFFER_SIZE);
|
|---|
| 30 | }
|
|---|
| 31 |
|
|---|
| 32 | SPRINTF_TEST(no_formatting, "This is a test.", "This is a test.");
|
|---|
| 33 |
|
|---|
| 34 | SPRINTF_TEST(string_plain, "some text", "%s", "some text");
|
|---|
| 35 |
|
|---|
| 36 | SPRINTF_TEST(string_dynamic_width, " tex", "%*.*s", 5, 3, "text");
|
|---|
| 37 |
|
|---|
| 38 | SPRINTF_TEST(string_dynamic_width_align_left, "text ", "%-*.*s", 7, 7, "text");
|
|---|
| 39 |
|
|---|
| 40 | SPRINTF_TEST(string_pad, " text", "%8.10s", "text");
|
|---|
| 41 |
|
|---|
| 42 | SPRINTF_TEST(string_pad_but_cut, " very lon", "%10.8s", "very long text");
|
|---|
| 43 |
|
|---|
| 44 | SPRINTF_TEST(char_basic, "[a]", "[%c]", 'a');
|
|---|
| 45 |
|
|---|
| 46 | SPRINTF_TEST(int_various_padding, "[1] [ 02] [03 ] [004] [005]",
|
|---|
| 47 | "[%d] [%3.2d] [%-3.2d] [%2.3d] [%-2.3d]",
|
|---|
| 48 | 1, 2, 3, 4, 5);
|
|---|
| 49 |
|
|---|
| 50 | SPRINTF_TEST(int_negative_various_padding, "[-1] [-02] [-03] [-004] [-005]",
|
|---|
| 51 | "[%d] [%3.2d] [%-3.2d] [%2.3d] [%-2.3d]",
|
|---|
| 52 | -1, -2, -3, -4, -5);
|
|---|
| 53 |
|
|---|
| 54 | SPRINTF_TEST(long_negative_various_padding, "[-1] [-02] [-03] [-004] [-005]",
|
|---|
| 55 | "[%lld] [%3.2lld] [%-3.2lld] [%2.3lld] [%-2.3lld]",
|
|---|
| 56 | (long long) -1, (long long) -2, (long long) -3, (long long) -4,
|
|---|
| 57 | (long long) -5);
|
|---|
| 58 |
|
|---|
| 59 | SPRINTF_TEST(int_as_hex, "[0x11] [0x012] [0x013] [0x00014] [0x00015]",
|
|---|
| 60 | "[%#x] [%#5.3x] [%#-5.3x] [%#3.5x] [%#-3.5x]",
|
|---|
| 61 | 17, 18, 19, 20, 21);
|
|---|
| 62 |
|
|---|
| 63 | PCUT_EXPORT(sprintf);
|
|---|