1 // Copyright 2017 The Abseil Authors.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // https://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 #include "absl/strings/internal/ostringstream.h"
16
17 #include <memory>
18 #include <ostream>
19 #include <string>
20 #include <type_traits>
21
22 #include "gtest/gtest.h"
23
24 namespace {
25
TEST(OStringStream,IsOStream)26 TEST(OStringStream, IsOStream) {
27 static_assert(
28 std::is_base_of<std::ostream, absl::strings_internal::OStringStream>(),
29 "");
30 }
31
TEST(OStringStream,ConstructDestroy)32 TEST(OStringStream, ConstructDestroy) {
33 {
34 absl::strings_internal::OStringStream strm(nullptr);
35 EXPECT_EQ(nullptr, strm.str());
36 }
37 {
38 std::string s = "abc";
39 {
40 absl::strings_internal::OStringStream strm(&s);
41 EXPECT_EQ(&s, strm.str());
42 }
43 EXPECT_EQ("abc", s);
44 }
45 {
46 std::unique_ptr<std::string> s(new std::string);
47 absl::strings_internal::OStringStream strm(s.get());
48 s.reset();
49 }
50 }
51
TEST(OStringStream,Str)52 TEST(OStringStream, Str) {
53 std::string s1;
54 absl::strings_internal::OStringStream strm(&s1);
55 const absl::strings_internal::OStringStream& c_strm(strm);
56
57 static_assert(std::is_same<decltype(strm.str()), std::string*>(), "");
58 static_assert(std::is_same<decltype(c_strm.str()), const std::string*>(), "");
59
60 EXPECT_EQ(&s1, strm.str());
61 EXPECT_EQ(&s1, c_strm.str());
62
63 strm.str(&s1);
64 EXPECT_EQ(&s1, strm.str());
65 EXPECT_EQ(&s1, c_strm.str());
66
67 std::string s2;
68 strm.str(&s2);
69 EXPECT_EQ(&s2, strm.str());
70 EXPECT_EQ(&s2, c_strm.str());
71
72 strm.str(nullptr);
73 EXPECT_EQ(nullptr, strm.str());
74 EXPECT_EQ(nullptr, c_strm.str());
75 }
76
TEST(OStreamStream,WriteToLValue)77 TEST(OStreamStream, WriteToLValue) {
78 std::string s = "abc";
79 {
80 absl::strings_internal::OStringStream strm(&s);
81 EXPECT_EQ("abc", s);
82 strm << "";
83 EXPECT_EQ("abc", s);
84 strm << 42;
85 EXPECT_EQ("abc42", s);
86 strm << 'x' << 'y';
87 EXPECT_EQ("abc42xy", s);
88 }
89 EXPECT_EQ("abc42xy", s);
90 }
91
TEST(OStreamStream,WriteToRValue)92 TEST(OStreamStream, WriteToRValue) {
93 std::string s = "abc";
94 absl::strings_internal::OStringStream(&s) << "";
95 EXPECT_EQ("abc", s);
96 absl::strings_internal::OStringStream(&s) << 42;
97 EXPECT_EQ("abc42", s);
98 absl::strings_internal::OStringStream(&s) << 'x' << 'y';
99 EXPECT_EQ("abc42xy", s);
100 }
101
102 } // namespace
103