1 /*
2 * Copyright 2020 The WebRTC Project Authors. All rights reserved.
3 *
4 * Use of this source code is governed by a BSD-style license
5 * that can be found in the LICENSE file in the root of the source
6 * tree. An additional intellectual property rights grant can be found
7 * in the file PATENTS. All contributing project authors may
8 * be found in the AUTHORS file in the root of the source tree.
9 */
10
11 #include "rtc_base/strings/string_format.h"
12
13 #include <vector>
14
15 #include "absl/strings/string_view.h"
16 #include "rtc_base/checks.h"
17 #include "rtc_base/string_encode.h"
18 #include "test/gtest.h"
19
20 namespace rtc {
21
TEST(StringFormatTest,Empty)22 TEST(StringFormatTest, Empty) {
23 EXPECT_EQ("", StringFormat("%s", ""));
24 }
25
TEST(StringFormatTest,Misc)26 TEST(StringFormatTest, Misc) {
27 EXPECT_EQ("123hello w", StringFormat("%3d%2s %1c", 123, "hello", 'w'));
28 EXPECT_EQ("3 = three", StringFormat("%d = %s", 1 + 2, "three"));
29 }
30
TEST(StringFormatTest,MaxSizeShouldWork)31 TEST(StringFormatTest, MaxSizeShouldWork) {
32 const int kSrcLen = 512;
33 char str[kSrcLen];
34 std::fill_n(str, kSrcLen, 'A');
35 str[kSrcLen - 1] = 0;
36 EXPECT_EQ(str, StringFormat("%s", str));
37 }
38
39 // Test that formating a string using `absl::string_view` works as expected
40 // whe using `%.*s`.
TEST(StringFormatTest,FormatStringView)41 TEST(StringFormatTest, FormatStringView) {
42 const std::string main_string("This is a substring test.");
43 std::vector<absl::string_view> string_views = rtc::split(main_string, ' ');
44 ASSERT_EQ(string_views.size(), 5u);
45
46 const absl::string_view& sv = string_views[3];
47 std::string formatted =
48 StringFormat("We have a %.*s.", static_cast<int>(sv.size()), sv.data());
49 EXPECT_EQ(formatted.compare("We have a substring."), 0);
50 }
51
52 } // namespace rtc
53