Introduce line editor library.
[oota-llvm.git] / unittests / LineEditor / LineEditor.cpp
1 //===-- LineEditor.cpp ----------------------------------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9
10 #include "llvm/LineEditor/LineEditor.h"
11 #include "llvm/Support/Path.h"
12 #include "gtest/gtest.h"
13
14 using namespace llvm;
15
16 class LineEditorTest : public testing::Test {
17 public:
18   SmallString<64> HistPath;
19   LineEditor *LE;
20
21   LineEditorTest() {
22     init();
23   }
24
25   void init() {
26     sys::fs::createTemporaryFile("temp", "history", HistPath);
27     ASSERT_FALSE(HistPath.empty());
28     LE = new LineEditor("test", HistPath);
29   }
30
31   ~LineEditorTest() {
32     delete LE;
33     sys::fs::remove(HistPath.str());
34   }
35 };
36
37 TEST_F(LineEditorTest, HistorySaveLoad) {
38   LE->saveHistory();
39   LE->loadHistory();
40 }
41
42 struct TestListCompleter {
43   std::vector<LineEditor::Completion> Completions;
44
45   TestListCompleter(const std::vector<LineEditor::Completion> &Completions)
46       : Completions(Completions) {}
47
48   std::vector<LineEditor::Completion> operator()(StringRef Buffer,
49                                                  size_t Pos) const {
50     EXPECT_TRUE(Buffer.empty());
51     EXPECT_EQ(0u, Pos);
52     return Completions;
53   }
54 };
55
56 TEST_F(LineEditorTest, ListCompleters) {
57   std::vector<LineEditor::Completion> Comps;
58
59   Comps.push_back(LineEditor::Completion("foo", "int foo()"));
60   LE->setListCompleter(TestListCompleter(Comps));
61   LineEditor::CompletionAction CA = LE->getCompletionAction("", 0);
62   EXPECT_EQ(LineEditor::CompletionAction::AK_Insert, CA.Kind);
63   EXPECT_EQ("foo", CA.Text);
64
65   Comps.push_back(LineEditor::Completion("bar", "int bar()"));
66   LE->setListCompleter(TestListCompleter(Comps));
67   CA = LE->getCompletionAction("", 0);
68   EXPECT_EQ(LineEditor::CompletionAction::AK_ShowCompletions, CA.Kind);
69   ASSERT_EQ(2u, CA.Completions.size());
70   ASSERT_EQ("int foo()", CA.Completions[0]);
71   ASSERT_EQ("int bar()", CA.Completions[1]);
72
73   Comps.clear();
74   Comps.push_back(LineEditor::Completion("fee", "int fee()"));
75   Comps.push_back(LineEditor::Completion("fi", "int fi()"));
76   Comps.push_back(LineEditor::Completion("foe", "int foe()"));
77   Comps.push_back(LineEditor::Completion("fum", "int fum()"));
78   LE->setListCompleter(TestListCompleter(Comps));
79   CA = LE->getCompletionAction("", 0);
80   EXPECT_EQ(LineEditor::CompletionAction::AK_Insert, CA.Kind);
81   EXPECT_EQ("f", CA.Text);
82 }