77 lines · cpp
1//===-- Unittests for snprintf --------------------------------------------===//2//3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.4// See https://llvm.org/LICENSE.txt for license information.5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception6//7//===----------------------------------------------------------------------===//8 9#include "src/stdio/snprintf.h"10 11#include "test/UnitTest/ErrnoCheckingTest.h"12#include "test/UnitTest/ErrnoSetterMatcher.h"13#include "test/UnitTest/Test.h"14 15using LlvmLibcSNPrintfTest = LIBC_NAMESPACE::testing::ErrnoCheckingTest;16 17// The sprintf test cases cover testing the shared printf functionality, so18// these tests will focus on snprintf exclusive features.19 20TEST(LlvmLibcSNPrintfTest, CutOff) {21 char buff[100];22 int written;23 24 written = LIBC_NAMESPACE::snprintf(buff, 16,25 "A simple string with no conversions.");26 EXPECT_EQ(written, 36);27 ASSERT_STREQ(buff, "A simple string");28 29 written = LIBC_NAMESPACE::snprintf(buff, 5, "%s", "1234567890");30 EXPECT_EQ(written, 10);31 ASSERT_STREQ(buff, "1234");32 33 written = LIBC_NAMESPACE::snprintf(buff, 67, "%-101c", 'a');34 EXPECT_EQ(written, 101);35 ASSERT_STREQ(buff, "a "36 " " // Each of these is 8 spaces, and there are 8.37 " " // In total there are 65 spaces38 " " // 'a' + 65 spaces + '\0' = 6739 " "40 " "41 " "42 " "43 " ");44 45 // passing null as the output pointer is allowed as long as buffsz is 0.46 written = LIBC_NAMESPACE::snprintf(nullptr, 0, "%s and more", "1234567890");47 EXPECT_EQ(written, 19);48 49 written = LIBC_NAMESPACE::snprintf(nullptr, 0, "%*s", INT_MIN, "nothing");50 EXPECT_EQ(written, INT_MAX);51}52 53TEST(LlvmLibcSNPrintfTest, NoCutOff) {54 char buff[64];55 int written;56 57 written = LIBC_NAMESPACE::snprintf(buff, 37,58 "A simple string with no conversions.");59 EXPECT_EQ(written, 36);60 ASSERT_STREQ(buff, "A simple string with no conversions.");61 62 written = LIBC_NAMESPACE::snprintf(buff, 20, "%s", "1234567890");63 EXPECT_EQ(written, 10);64 ASSERT_STREQ(buff, "1234567890");65}66 67TEST(LlvmLibcSNPrintfTest, CharsWrittenOverflow) {68 char buff[0];69 70 // Trigger an overflow in the return value of snprintf by writing more than71 // INT_MAX bytes.72 int int_max = LIBC_NAMESPACE::cpp::numeric_limits<int>::max();73 int written = LIBC_NAMESPACE::snprintf(buff, 0, "%*stest", int_max, "");74 EXPECT_LT(written, 0);75 ASSERT_ERRNO_FAILURE();76}77