2 * Copyright 2015 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 <folly/FBVector.h>
20 #include <folly/FileUtil.h>
21 #include <folly/dynamic.h>
22 #include <folly/json.h>
23 #include <folly/small_vector.h>
25 #include <glog/logging.h>
26 #include <gflags/gflags.h>
27 #include <gtest/gtest.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).
37 SCOPE_EXIT { closeNoInt(fds[1]); };
39 FILE* fp = fdopen(fds[1], "wb");
41 SCOPE_EXIT { fclose(fp); };
42 writeTo(fp, format("{} {}", 42, 23)); // <= 512 bytes (PIPE_BUF)
46 ssize_t n = readFull(fds[0], buf, sizeof(buf));
49 EXPECT_EQ("42 23", std::string(buf, n));
53 TEST(FormatOther, dynamic) {
56 " \"hello\": \"world\",\n"
58 " \"y\": {\"a\" : 42}\n"
61 EXPECT_EQ("world", sformat("{0[hello]}", dyn));
62 EXPECT_THROW(sformat("{0[none]}", dyn), std::out_of_range);
63 EXPECT_EQ("world", sformat("{0[hello]}", defaulted(dyn, "meow")));
64 EXPECT_EQ("meow", sformat("{0[none]}", defaulted(dyn, "meow")));
66 EXPECT_EQ("20", sformat("{0[x.0]}", dyn));
67 EXPECT_THROW(sformat("{0[x.2]}", dyn), std::out_of_range);
69 // No support for "deep" defaulting (dyn["x"] is not defaulted)
71 EXPECT_EQ("20", sformat("{0[0]}", v));
72 EXPECT_THROW(sformat("{0[2]}", v), std::out_of_range);
73 EXPECT_EQ("20", sformat("{0[0]}", defaulted(v, 42)));
74 EXPECT_EQ("42", sformat("{0[2]}", defaulted(v, 42)));
76 EXPECT_EQ("42", sformat("{0[y.a]}", dyn));
78 EXPECT_EQ("(null)", sformat("{}", dynamic(nullptr)));
84 void testFormatSeq() {
86 EXPECT_EQ("30 10", sformat("{0[2]} {0[0]}", v));
87 EXPECT_EQ("0020", sformat("{0[1]:04}", v));
88 EXPECT_EQ("0020", svformat("{1:04}", v));
89 EXPECT_EQ("10 20", svformat("{} {}", v));
90 EXPECT_EQ("10 20 0030", svformat("{} {} {:04}", v));
95 TEST(FormatOther, fbvector) {
96 testFormatSeq<fbvector<int>>();
99 TEST(FormatOther, small_vector) {
100 testFormatSeq<small_vector<int, 2>>();
103 int main(int argc, char *argv[]) {
104 testing::InitGoogleTest(&argc, argv);
105 gflags::ParseCommandLineFlags(&argc, &argv, true);
106 return RUN_ALL_TESTS();