2 * Copyright 2017 Facebook, Inc.
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
17 #include <folly/Format.h>
19 #include <glog/logging.h>
21 #include <folly/FBVector.h>
22 #include <folly/FileUtil.h>
23 #include <folly/Portability.h>
24 #include <folly/dynamic.h>
25 #include <folly/json.h>
26 #include <folly/portability/GTest.h>
27 #include <folly/small_vector.h>
29 using namespace folly;
31 TEST(FormatOther, file) {
32 // Test writing to FILE. I'd use open_memstream but that's not available
33 // outside of Linux (even though it's in POSIX.1-2008).
38 // fclose on Windows automatically closes the underlying
45 FILE* fp = fdopen(fds[1], "wb");
47 SCOPE_EXIT { fclose(fp); };
48 writeTo(fp, format("{} {}", 42, 23)); // <= 512 bytes (PIPE_BUF)
52 ssize_t n = readFull(fds[0], buf, sizeof(buf));
55 EXPECT_EQ("42 23", std::string(buf, n));
59 TEST(FormatOther, dynamic) {
62 " \"hello\": \"world\",\n"
64 " \"y\": {\"a\" : 42}\n"
67 EXPECT_EQ("world", sformat("{0[hello]}", dyn));
68 EXPECT_THROW(sformat("{0[none]}", dyn), std::out_of_range);
69 EXPECT_EQ("world", sformat("{0[hello]}", defaulted(dyn, "meow")));
70 EXPECT_EQ("meow", sformat("{0[none]}", defaulted(dyn, "meow")));
72 EXPECT_EQ("20", sformat("{0[x.0]}", dyn));
73 EXPECT_THROW(sformat("{0[x.2]}", dyn), std::out_of_range);
75 // No support for "deep" defaulting (dyn["x"] is not defaulted)
77 EXPECT_EQ("20", sformat("{0[0]}", v));
78 EXPECT_THROW(sformat("{0[2]}", v), std::out_of_range);
79 EXPECT_EQ("20", sformat("{0[0]}", defaulted(v, 42)));
80 EXPECT_EQ("42", sformat("{0[2]}", defaulted(v, 42)));
82 EXPECT_EQ("42", sformat("{0[y.a]}", dyn));
84 EXPECT_EQ("(null)", sformat("{}", dynamic(nullptr)));
90 void testFormatSeq() {
92 EXPECT_EQ("30 10", sformat("{0[2]} {0[0]}", v));
93 EXPECT_EQ("0020", sformat("{0[1]:04}", v));
94 EXPECT_EQ("0020", svformat("{1:04}", v));
95 EXPECT_EQ("10 20", svformat("{} {}", v));
96 EXPECT_EQ("10 20 0030", svformat("{} {} {:04}", v));
101 TEST(FormatOther, fbvector) {
102 testFormatSeq<fbvector<int>>();
105 TEST(FormatOther, small_vector) {
106 testFormatSeq<small_vector<int, 2>>();
109 int main(int argc, char *argv[]) {
110 testing::InitGoogleTest(&argc, argv);
111 gflags::ParseCommandLineFlags(&argc, &argv, true);
112 return RUN_ALL_TESTS();