1/**
2 * Copyright (c) Glow Contributors. See CONTRIBUTORS file.
3 *
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
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
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.
15 */
16
17#include "glow/Testing/StrCheck.h"
18#include "gtest/gtest.h"
19
20using glow::StrCheck;
21
22StrCheck &StrCheck::check(llvm::StringRef needle) {
23 size_t found = input_.find(needle.str(), pos_);
24 return found != std::string::npos ? match(found, needle.size())
25 : fail("not found: check", needle);
26}
27
28StrCheck &StrCheck::sameln(llvm::StringRef needle) {
29 size_t found = input_.find(needle.str(), pos_);
30 return found < findEol() ? match(found, needle.size())
31 : fail("not found: sameln", needle);
32}
33
34StrCheck &StrCheck::nextln(llvm::StringRef needle) {
35 size_t eol = findEol();
36 size_t found = input_.find(needle.str(), eol);
37 return found < findEol(eol) ? match(found, needle.size())
38 : fail("not found: nextln", needle);
39}
40
41StrCheck &StrCheck::no(llvm::StringRef needle) {
42 nos_.push_back(needle.str());
43 return *this;
44}
45
46StrCheck &StrCheck::match(size_t at, size_t size) {
47 // We have a positive match. Check if any of the no()'s appeared between
48 // `pos_` and `at`.
49 for (const auto &no : nos_) {
50 if (pos_ + no.size() > at)
51 continue;
52 if (input_.find(no, pos_) <= at - no.size())
53 fail("matched not", no);
54 }
55 nos_.clear();
56
57 pos_ = at + size;
58 return *this;
59}
60
61StrCheck &StrCheck::fail(const char *msg, llvm::StringRef needle) {
62 errors_ += ">>> ";
63 errors_ += msg;
64 errors_ += "(\"";
65 errors_ += needle;
66 errors_ += "\")\n";
67 return *this;
68}
69
70size_t StrCheck::findEol(size_t p) const {
71 size_t eol = input_.find('\n', p);
72 return eol == std::string::npos ? input_.size() : eol + 1;
73}
74
75size_t StrCheck::findEol() const { return findEol(pos_); }
76
77StrCheck::operator testing::AssertionResult() {
78 if (*this)
79 return testing::AssertionSuccess();
80 else
81 return testing::AssertionFailure() << "Failed StrCheck in:\n"
82 << input_ << '\n'
83 << errors_;
84}
85
86StrCheck::operator bool() {
87 // Match up to the end of the input to make sure we catch any trailing no()'s.
88 match(input_.size(), 0);
89 return errors_.empty();
90}
91