2 * Copyright 2004-present 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.
16 #include <folly/String.h>
17 #include <folly/experimental/logging/LogMessage.h>
18 #include <folly/experimental/logging/Logger.h>
19 #include <folly/experimental/logging/LoggerDB.h>
20 #include <folly/portability/GTest.h>
22 using namespace folly;
24 #define CHECK_MSG(expected, value, hasNewlines) \
27 "input string: \"" + folly::backslashify<std::string>(value) + "\""); \
28 LogMessage checkMsg{ \
29 category, LogLevel::ERR, __FILE__, __LINE__, std::string{value}}; \
30 EXPECT_EQ(expected, checkMsg.getMessage()); \
31 EXPECT_EQ(hasNewlines, checkMsg.containsNewlines()); \
32 EXPECT_EQ(__FILE__, checkMsg.getFileName()); \
33 EXPECT_EQ(__LINE__, checkMsg.getLineNumber()); \
36 TEST(LogMessage, sanitize) {
37 LoggerDB db{LoggerDB::TESTING};
38 Logger logger{&db, "test"};
39 auto* category = logger.getCategory();
41 CHECK_MSG("foo", "foo", false);
42 CHECK_MSG("foo\\\\bar", "foo\\bar", false);
43 CHECK_MSG("foo\\x01test", "foo\01test", false);
44 CHECK_MSG("test 1234 ", "test 1234 ", false);
45 CHECK_MSG("\\x07", "\a", false);
46 CHECK_MSG("\n", "\n", true);
47 CHECK_MSG("\t", "\t", false);
48 CHECK_MSG("\n\t\n", "\n\t\n", true);
49 // Test strings containing NUL bytes
50 CHECK_MSG("test\\x00.1234\\x00", std::string("test\0.1234\0", 11), false);
51 CHECK_MSG("test\\x00\n1234\\x00", std::string("test\0\n1234\0", 11), true);
52 // Test all ASCII characters except NUL
54 ("\\x01\\x02\\x03\\x04\\x05\\x06\\x07\\x08"
55 "\t\n\\x0b\\x0c\\x0d\\x0e\\x0f"
56 "\\x10\\x11\\x12\\x13\\x14\\x15\\x16\\x17"
57 "\\x18\\x19\\x1a\\x1b\\x1c\\x1d\\x1e\\x1f"
58 " !\"#$%&'()*+,-./0123456789:;<=>?"
59 "@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\\\]^_"
60 "`abcdefghijklmnopqrstuvwxyz{|}~\\x7f"),
61 ("\001\002\003\004\005\006\007"
62 "\010\011\012\013\014\015\016\017"
63 "\020\021\022\023\024\025\026\027"
64 "\030\031\032\033\034\035\036\037"
65 " !\"#$%&'()*+,-./0123456789:;<=>?"
66 "@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_"
67 "`abcdefghijklmnopqrstuvwxyz{|}~\177"),
70 // Test some high-bit characters
71 CHECK_MSG("\x82\x83", "\x82\x83", false);
72 CHECK_MSG("\x82\n\x83\n", "\x82\n\x83\n", true);
73 CHECK_MSG("\x82\n\\x0c\x83\n", "\x82\n\f\x83\n", true);