xref: /aosp_15_r20/external/cronet/base/test/bind.cc (revision 6777b5387eb2ff775bb5750e3f5d96f37fb7352b)
1 // Copyright 2019 The Chromium Authors
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4 
5 #include "base/test/bind.h"
6 
7 #include <string>
8 #include <string_view>
9 
10 #include "base/functional/bind.h"
11 #include "base/functional/callback.h"
12 #include "base/location.h"
13 #include "testing/gtest/include/gtest/gtest.h"
14 
15 namespace base {
16 namespace {
17 
18 // A helper class for MakeExpectedRunClosure() that fails if it is
19 // destroyed without Run() having been called.  This class may be used
20 // from multiple threads as long as Run() is called at most once
21 // before destruction.
22 class RunChecker {
23  public:
RunChecker(const Location & location,std::string_view message,bool is_repeating)24   explicit RunChecker(const Location& location,
25                       std::string_view message,
26                       bool is_repeating)
27       : location_(location), message_(message), is_repeating_(is_repeating) {}
28 
~RunChecker()29   ~RunChecker() {
30     if (!called_) {
31       ADD_FAILURE_AT(location_.file_name(), location_.line_number())
32           << message_;
33     }
34   }
35 
Run()36   void Run() {
37     DCHECK(is_repeating_ || !called_);
38     called_ = true;
39   }
40 
41  private:
42   const Location location_;
43   const std::string message_;
44   const bool is_repeating_;
45   bool called_ = false;
46 };
47 
48 }  // namespace
49 
MakeExpectedRunClosure(const Location & location,std::string_view message)50 OnceClosure MakeExpectedRunClosure(const Location& location,
51                                    std::string_view message) {
52   return BindOnce(&RunChecker::Run,
53                   Owned(new RunChecker(location, message, false)));
54 }
55 
MakeExpectedRunAtLeastOnceClosure(const Location & location,std::string_view message)56 RepeatingClosure MakeExpectedRunAtLeastOnceClosure(const Location& location,
57                                                    std::string_view message) {
58   return BindRepeating(&RunChecker::Run,
59                        Owned(new RunChecker(location, message, true)));
60 }
61 
MakeExpectedNotRunClosure(const Location & location,std::string_view message)62 RepeatingClosure MakeExpectedNotRunClosure(const Location& location,
63                                            std::string_view message) {
64   return BindRepeating(
65       [](const Location& location, std::string_view message) {
66         ADD_FAILURE_AT(location.file_name(), location.line_number()) << message;
67       },
68       location, std::string(message));
69 }
70 
71 }  // namespace base
72