1 //===-- LoggerTests.cpp ---------------------------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 #include "support/Logger.h"
9 #include "llvm/Support/Errc.h"
10 #include "llvm/Support/Error.h"
11 #include "gmock/gmock.h"
12 #include "gtest/gtest.h"
13 #include <optional>
14
15 namespace clang {
16 namespace clangd {
17 namespace {
18
TEST(ErrorTest,Overloads)19 TEST(ErrorTest, Overloads) {
20 EXPECT_EQ("foo", llvm::toString(error("foo")));
21 // Inconvertible to error code when none is specified.
22 // Don't actually try to convert, it'll crash.
23 handleAllErrors(error("foo"), [&](const llvm::ErrorInfoBase &EI) {
24 EXPECT_EQ(llvm::inconvertibleErrorCode(), EI.convertToErrorCode());
25 });
26
27 EXPECT_EQ("foo 42", llvm::toString(error("foo {0}", 42)));
28 handleAllErrors(error("foo {0}", 42), [&](const llvm::ErrorInfoBase &EI) {
29 EXPECT_EQ(llvm::inconvertibleErrorCode(), EI.convertToErrorCode());
30 });
31
32 EXPECT_EQ("foo", llvm::toString(error(llvm::errc::invalid_argument, "foo")));
33 EXPECT_EQ(llvm::errc::invalid_argument,
34 llvm::errorToErrorCode(error(llvm::errc::invalid_argument, "foo")));
35
36 EXPECT_EQ("foo 42",
37 llvm::toString(error(llvm::errc::invalid_argument, "foo {0}", 42)));
38 EXPECT_EQ(llvm::errc::invalid_argument,
39 llvm::errorToErrorCode(
40 error(llvm::errc::invalid_argument, "foo {0}", 42)));
41 }
42
TEST(ErrorTest,Lifetimes)43 TEST(ErrorTest, Lifetimes) {
44 std::optional<llvm::Error> Err;
45 {
46 // Check the error contains the value when error() was called.
47 std::string S = "hello, world";
48 Err = error("S={0}", llvm::StringRef(S));
49 S = "garbage";
50 }
51 EXPECT_EQ("S=hello, world", llvm::toString(std::move(*Err)));
52 }
53
TEST(ErrorTest,ConsumeError)54 TEST(ErrorTest, ConsumeError) {
55 llvm::Error Foo = error("foo");
56 llvm::Error Bar = error("bar: {0}", std::move(Foo));
57 EXPECT_EQ("bar: foo", llvm::toString(std::move(Bar)));
58 // No assert for unchecked Foo.
59 }
60
61 } // namespace
62 } // namespace clangd
63 } // namespace clang
64