aboutsummaryrefslogtreecommitdiffstats
path: root/libs/minisat/SimpSolver.h
blob: 76d5aca1f01237ef3cdd8167c176bf03138ee87e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
/************************************************************************************[SimpSolver.h]
Copyright (c) 2006,      Niklas Een, Niklas Sorensson
Copyright (c) 2007-2010, Niklas Sorensson

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
associated documentation files (the "Software"), to deal in the Software without restriction,
including without limitation the rights to use, copy, modify, merge, publish, distribute,
sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or
substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT
NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT
OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
**************************************************************************************************/

#ifndef Minisat_SimpSolver_h
#define Minisat_SimpSolver_h

#include "Queue.h"
#include "Solver.h"


namespace Minisat {

//=================================================================================================


class SimpSolver : public Solver {
 public:
    // Constructor/Destructor:
    //
    SimpSolver();
    ~SimpSolver();

    // Problem specification:
    //
    Var     newVar    (lbool upol = l_Undef, bool dvar = true);
    void    releaseVar(Lit l);
    bool    addClause (const vec<Lit>& ps);
    bool    addEmptyClause();                // Add the empty clause to the solver.
    bool    addClause (Lit p);               // Add a unit clause to the solver.
    bool    addClause (Lit p, Lit q);        // Add a binary clause to the solver.
    bool    addClause (Lit p, Lit q, Lit r); // Add a ternary clause to the solver.
    bool    addClause (Lit p, Lit q, Lit r, Lit s); // Add a quaternary clause to the solver. 
    bool    addClause_(      vec<Lit>& ps);
    bool    substitute(Var v, Lit x);  // Replace all occurences of v with x (may cause a contradiction).

    // Variable mode:
    // 
    void    setFrozen (Var v, bool b); // If a variable is frozen it will not be eliminated.
    bool    isEliminated(Var v) const;

    // Alternative freeze interface (may replace 'setFrozen()'):
    void    freezeVar (Var v);         // Freeze one variable so it will not be eliminated.
    void    thaw      ();              // Thaw all frozen variables.


    // Solving:
    //
    bool    solve       (const vec<Lit>& assumps, bool do_simp = true, bool turn_off_simp = false);
    lbool   solveLimited(const vec<Lit>& assumps, bool do_simp = true, bool turn_off_simp = false);
    bool    solve       (                     bool do_simp = true, bool turn_off_simp = false);
    bool    solve       (Lit p       ,        bool do_simp = true, bool turn_off_simp = false);       
    bool    solve       (Lit p, Lit q,        bool do_simp = true, bool turn_off_simp = false);
    bool    solve       (Lit p, Lit q, Lit r, bool do_simp = true, bool turn_off_simp = false);
    bool    eliminate   (bool turn_off_elim = false);  // Perform variable elimination based simplification. 

    // Memory managment:
    //
    virtual void garbageCollect();


    // Generate a (possibly simplified) DIMACS file:
    //
#if 0
    void    toDimacs  (const char* file, const vec<Lit>& assumps);
    void    toDimacs  (const char* file);
    void    toDimacs  (const char* file, Lit p);
    void    toDimacs  (const char* file, Lit p, Lit q);
    void    toDimacs  (const char* file, Lit p, Lit q, Lit r);
#endif

    // Mode of operation:
    //
    int     grow;              // Allow a variable elimination step to grow by a number of clauses (default to zero).
    int     clause_lim;        // Variables are not eliminated if it produces a resolvent with a length above this limit.
                               // -1 means no limit.
    int     subsumption_lim;   // Do not check if subsumption against a clause larger than this. -1 means no limit.
    double  simp_garbage_frac; // A different limit for when to issue a GC during simplification (Also see 'garbage_frac').

    bool    use_asymm;         // Shrink clauses by asymmetric branching.
    bool    use_rcheck;        // Check if a clause is already implied. Prett costly, and subsumes subsumptions :)
    bool    use_elim;          // Perform variable elimination.
    bool    extend_model;      // Flag to indicate whether the user needs to look at the full model.

    // Statistics:
    //
    int     merges;
    int     asymm_lits;
    int     eliminated_vars;

 protected:

    // Helper structures:
    //
    struct ElimLt {
        const LMap<int>& n_occ;
        explicit ElimLt(const LMap<int>& no) : n_occ(no) {}

        // TODO: are 64-bit operations here noticably bad on 32-bit platforms? Could use a saturating
        // 32-bit implementation instead then, but this will have to do for now.
        uint64_t cost  (Var x)        const { return (uint64_t)n_occ[mkLit(x)] * (uint64_t)n_occ[~mkLit(x)]; }
        bool operator()(Var x, Var y) const { return cost(x) < cost(y); }
        
        // TODO: investigate this order alternative more.
        // bool operator()(Var x, Var y) const { 
        //     int c_x = cost(x);
        //     int c_y = cost(y);
        //     return c_x < c_y || c_x == c_y && x < y; }
    };

    struct ClauseDeleted {
        const ClauseAllocator& ca;
        explicit ClauseDeleted(const ClauseAllocator& _ca) : ca(_ca) {}
        bool operator()(const CRef& cr) const { return ca[cr].mark() == 1; } };

    // Solver state:
    //
    int                 elimorder;
    bool                use_simplification;
    Var                 max_simp_var;        // Max variable at the point simplification was turned off.
    vec<uint32_t>       elimclauses;
    VMap<char>          touched;
    OccLists<Var, vec<CRef>, ClauseDeleted>
                        occurs;
    LMap<int>           n_occ;
    Heap<Var,ElimLt>    elim_heap;
    Queue<CRef>         subsumption_queue;
    VMap<char>          frozen;
    vec<Var>            frozen_vars;
    VMap<char>          eliminated;
    int                 bwdsub_assigns;
    int                 n_touched;

    // Temporaries:
    //
    CRef                bwdsub_tmpunit;

    // Main internal methods:
    //
    lbool         solve_                   (bool do_simp = true, bool turn_off_simp = false);
    bool          asymm                    (Var v, CRef cr);
    bool          asymmVar                 (Var v);
    void          updateElimHeap           (Var v);
    void          gatherTouchedClauses     ();
    bool          merge                    (const Clause& _ps, const Clause& _qs, Var v, vec<Lit>& out_clause);
    bool          merge                    (const Clause& _ps, const Clause& _qs, Var v, int& size);
    bool          backwardSubsumptionCheck (bool verbose = false);
    bool          eliminateVar             (Var v);
    void          extendModel              ();

    void          removeClause             (CRef cr);
    bool          strengthenClause         (CRef cr, Lit l);
    bool          implied                  (const vec<Lit>& c);
    void          relocAll                 (ClauseAllocator& to);
};


//=================================================================================================
// Implementation of inline methods:


inline bool SimpSolver::isEliminated (Var v) const { return eliminated[v]; }
inline void SimpSolver::updateElimHeap(Var v) {
    assert(use_simplification);
    // if (!frozen[v] && !isEliminated(v) && value(v) == l_Undef)
    if (elim_heap.inHeap(v) || (!frozen[v] && !isEliminated(v) && value(v) == l_Undef))
        elim_heap.update(v); }


inline bool SimpSolver::addClause    (const vec<Lit>& ps)    { ps.copyTo(add_tmp); return addClause_(add_tmp); }
inline bool SimpSolver::addEmptyClause()                     { add_tmp.clear(); return addClause_(add_tmp); }
inline bool SimpSolver::addClause    (Lit p)                 { add_tmp.clear(); add_tmp.push(p); return addClause_(add_tmp); }
inline bool SimpSolver::addClause    (Lit p, Lit q)          { add_tmp.clear(); add_tmp.push(p); add_tmp.push(q); return addClause_(add_tmp); }
inline bool SimpSolver::addClause    (Lit p, Lit q, Lit r)   { add_tmp.clear(); add_tmp.push(p); add_tmp.push(q); add_tmp.push(r); return addClause_(add_tmp); }
inline bool SimpSolver::addClause    (Lit p, Lit q, Lit r, Lit s){ add_tmp.clear(); add_tmp.push(p); add_tmp.push(q); add_tmp.push(r); add_tmp.push(s); return addClause_(add_tmp); }
inline void SimpSolver::setFrozen    (Var v, bool b) { frozen[v] = (char)b; if (use_simplification && !b) { updateElimHeap(v); } }

inline void SimpSolver::freezeVar(Var v){
    if (!frozen[v]){
        frozen[v] = 1;
        frozen_vars.push(v); 
    } }

inline void SimpSolver::thaw(){
    for (int i = 0; i < frozen_vars.size(); i++){
        Var v = frozen_vars[i];
        frozen[v] = 0;
        if (use_simplification)
            updateElimHeap(v);
    }
    frozen_vars.clear(); }

inline bool SimpSolver::solve        (                     bool do_simp, bool turn_off_simp)  { budgetOff(); assumptions.clear(); return solve_(do_simp, turn_off_simp) == l_True; }
inline bool SimpSolver::solve        (Lit p       ,        bool do_simp, bool turn_off_simp)  { budgetOff(); assumptions.clear(); assumptions.push(p); return solve_(do_simp, turn_off_simp) == l_True; }
inline bool SimpSolver::solve        (Lit p, Lit q,        bool do_simp, bool turn_off_simp)  { budgetOff(); assumptions.clear(); assumptions.push(p); assumptions.push(q); return solve_(do_simp, turn_off_simp) == l_True; }
inline bool SimpSolver::solve        (Lit p, Lit q, Lit r, bool do_simp, bool turn_off_simp)  { budgetOff(); assumptions.clear(); assumptions.push(p); assumptions.push(q); assumptions.push(r); return solve_(do_simp, turn_off_simp) == l_True; }
inline bool SimpSolver::solve        (const vec<Lit>& assumps, bool do_simp, bool turn_off_simp){ 
    budgetOff(); assumps.copyTo(assumptions); return solve_(do_simp, turn_off_simp) == l_True; }

inline lbool SimpSolver::solveLimited (const vec<Lit>& assumps, bool do_simp, bool turn_off_simp){ 
    assumps.copyTo(assumptions); return solve_(do_simp, turn_off_simp); }

//=================================================================================================
}

#endif
href='#n1561'>1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644
// Copyright 2007, Google Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
//     * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//     * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
//     * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Author: wan@google.com (Zhanyong Wan)

// Google Mock - a framework for writing C++ mock classes.
//
// This file tests the spec builder syntax.

#include "gmock/gmock-spec-builders.h"

#include <ostream>  // NOLINT
#include <sstream>
#include <string>

#include "gmock/gmock.h"
#include "gmock/internal/gmock-port.h"
#include "gtest/gtest.h"
#include "gtest/gtest-spi.h"
#include "gtest/internal/gtest-port.h"

namespace testing {
namespace internal {

// Helper class for testing the Expectation class template.
class ExpectationTester {
 public:
  // Sets the call count of the given expectation to the given number.
  void SetCallCount(int n, ExpectationBase* exp) {
    exp->call_count_ = n;
  }
};

}  // namespace internal
}  // namespace testing

namespace {

using testing::_;
using testing::AnyNumber;
using testing::AtLeast;
using testing::AtMost;
using testing::Between;
using testing::Cardinality;
using testing::CardinalityInterface;
using testing::ContainsRegex;
using testing::Const;
using testing::DoAll;
using testing::DoDefault;
using testing::Eq;
using testing::Expectation;
using testing::ExpectationSet;
using testing::GMOCK_FLAG(verbose);
using testing::Gt;
using testing::InSequence;
using testing::Invoke;
using testing::InvokeWithoutArgs;
using testing::IsNotSubstring;
using testing::IsSubstring;
using testing::Lt;
using testing::Message;
using testing::Mock;
using testing::NaggyMock;
using testing::Ne;
using testing::Return;
using testing::Sequence;
using testing::SetArgPointee;
using testing::internal::ExpectationTester;
using testing::internal::FormatFileLocation;
using testing::internal::kErrorVerbosity;
using testing::internal::kInfoVerbosity;
using testing::internal::kWarningVerbosity;
using testing::internal::linked_ptr;
using testing::internal::string;

#if GTEST_HAS_STREAM_REDIRECTION
using testing::HasSubstr;
using testing::internal::CaptureStdout;
using testing::internal::GetCapturedStdout;
#endif

class Incomplete;

class MockIncomplete {
 public:
  // This line verifies that a mock method can take a by-reference
  // argument of an incomplete type.
  MOCK_METHOD1(ByRefFunc, void(const Incomplete& x));
};

// Tells Google Mock how to print a value of type Incomplete.
void PrintTo(const Incomplete& x, ::std::ostream* os);

TEST(MockMethodTest, CanInstantiateWithIncompleteArgType) {
  // Even though this mock class contains a mock method that takes
  // by-reference an argument whose type is incomplete, we can still
  // use the mock, as long as Google Mock knows how to print the
  // argument.
  MockIncomplete incomplete;
  EXPECT_CALL(incomplete, ByRefFunc(_))
      .Times(AnyNumber());
}

// The definition of the printer for the argument type doesn't have to
// be visible where the mock is used.
void PrintTo(const Incomplete& /* x */, ::std::ostream* os) {
  *os << "incomplete";
}

class Result {};

// A type that's not default constructible.
class NonDefaultConstructible {
 public:
  explicit NonDefaultConstructible(int /* dummy */) {}
};

class MockA {
 public:
  MockA() {}

  MOCK_METHOD1(DoA, void(int n));
  MOCK_METHOD1(ReturnResult, Result(int n));
  MOCK_METHOD0(ReturnNonDefaultConstructible, NonDefaultConstructible());
  MOCK_METHOD2(Binary, bool(int x, int y));
  MOCK_METHOD2(ReturnInt, int(int x, int y));

 private:
  GTEST_DISALLOW_COPY_AND_ASSIGN_(MockA);
};

class MockB {
 public:
  MockB() {}

  MOCK_CONST_METHOD0(DoB, int());  // NOLINT
  MOCK_METHOD1(DoB, int(int n));  // NOLINT

 private:
  GTEST_DISALLOW_COPY_AND_ASSIGN_(MockB);
};

class ReferenceHoldingMock {
 public:
  ReferenceHoldingMock() {}

  MOCK_METHOD1(AcceptReference, void(linked_ptr<MockA>*));

 private:
  GTEST_DISALLOW_COPY_AND_ASSIGN_(ReferenceHoldingMock);
};

// Tests that EXPECT_CALL and ON_CALL compile in a presence of macro
// redefining a mock method name. This could happen, for example, when
// the tested code #includes Win32 API headers which define many APIs
// as macros, e.g. #define TextOut TextOutW.

#define Method MethodW

class CC {
 public:
  virtual ~CC() {}
  virtual int Method() = 0;
};
class MockCC : public CC {
 public:
  MockCC() {}

  MOCK_METHOD0(Method, int());

 private:
  GTEST_DISALLOW_COPY_AND_ASSIGN_(MockCC);
};

// Tests that a method with expanded name compiles.
TEST(OnCallSyntaxTest, CompilesWithMethodNameExpandedFromMacro) {
  MockCC cc;
  ON_CALL(cc, Method());
}

// Tests that the method with expanded name not only compiles but runs
// and returns a correct value, too.
TEST(OnCallSyntaxTest, WorksWithMethodNameExpandedFromMacro) {
  MockCC cc;
  ON_CALL(cc, Method()).WillByDefault(Return(42));
  EXPECT_EQ(42, cc.Method());
}

// Tests that a method with expanded name compiles.
TEST(ExpectCallSyntaxTest, CompilesWithMethodNameExpandedFromMacro) {
  MockCC cc;
  EXPECT_CALL(cc, Method());
  cc.Method();
}

// Tests that it works, too.
TEST(ExpectCallSyntaxTest, WorksWithMethodNameExpandedFromMacro) {
  MockCC cc;
  EXPECT_CALL(cc, Method()).WillOnce(Return(42));
  EXPECT_EQ(42, cc.Method());
}

#undef Method  // Done with macro redefinition tests.

// Tests that ON_CALL evaluates its arguments exactly once as promised
// by Google Mock.
TEST(OnCallSyntaxTest, EvaluatesFirstArgumentOnce) {
  MockA a;
  MockA* pa = &a;

  ON_CALL(*pa++, DoA(_));
  EXPECT_EQ(&a + 1, pa);
}

TEST(OnCallSyntaxTest, EvaluatesSecondArgumentOnce) {
  MockA a;
  int n = 0;

  ON_CALL(a, DoA(n++));
  EXPECT_EQ(1, n);
}

// Tests that the syntax of ON_CALL() is enforced at run time.

TEST(OnCallSyntaxTest, WithIsOptional) {
  MockA a;

  ON_CALL(a, DoA(5))
      .WillByDefault(Return());
  ON_CALL(a, DoA(_))
      .With(_)
      .WillByDefault(Return());
}

TEST(OnCallSyntaxTest, WithCanAppearAtMostOnce) {
  MockA a;

  EXPECT_NONFATAL_FAILURE({  // NOLINT
    ON_CALL(a, ReturnResult(_))
        .With(_)
        .With(_)
        .WillByDefault(Return(Result()));
  }, ".With() cannot appear more than once in an ON_CALL()");
}

TEST(OnCallSyntaxTest, WillByDefaultIsMandatory) {
  MockA a;

  EXPECT_DEATH_IF_SUPPORTED({
    ON_CALL(a, DoA(5));
    a.DoA(5);
  }, "");
}

TEST(OnCallSyntaxTest, WillByDefaultCanAppearAtMostOnce) {
  MockA a;

  EXPECT_NONFATAL_FAILURE({  // NOLINT
    ON_CALL(a, DoA(5))
        .WillByDefault(Return())
        .WillByDefault(Return());
  }, ".WillByDefault() must appear exactly once in an ON_CALL()");
}

// Tests that EXPECT_CALL evaluates its arguments exactly once as
// promised by Google Mock.
TEST(ExpectCallSyntaxTest, EvaluatesFirstArgumentOnce) {
  MockA a;
  MockA* pa = &a;

  EXPECT_CALL(*pa++, DoA(_));
  a.DoA(0);
  EXPECT_EQ(&a + 1, pa);
}

TEST(ExpectCallSyntaxTest, EvaluatesSecondArgumentOnce) {
  MockA a;
  int n = 0;

  EXPECT_CALL(a, DoA(n++));
  a.DoA(0);
  EXPECT_EQ(1, n);
}

// Tests that the syntax of EXPECT_CALL() is enforced at run time.

TEST(ExpectCallSyntaxTest, WithIsOptional) {
  MockA a;

  EXPECT_CALL(a, DoA(5))
      .Times(0);
  EXPECT_CALL(a, DoA(6))
      .With(_)
      .Times(0);
}

TEST(ExpectCallSyntaxTest, WithCanAppearAtMostOnce) {
  MockA a;

  EXPECT_NONFATAL_FAILURE({  // NOLINT
    EXPECT_CALL(a, DoA(6))
        .With(_)
        .With(_);
  }, ".With() cannot appear more than once in an EXPECT_CALL()");

  a.DoA(6);
}

TEST(ExpectCallSyntaxTest, WithMustBeFirstClause) {
  MockA a;

  EXPECT_NONFATAL_FAILURE({  // NOLINT
    EXPECT_CALL(a, DoA(1))
        .Times(1)
        .With(_);
  }, ".With() must be the first clause in an EXPECT_CALL()");

  a.DoA(1);

  EXPECT_NONFATAL_FAILURE({  // NOLINT
    EXPECT_CALL(a, DoA(2))
        .WillOnce(Return())
        .With(_);
  }, ".With() must be the first clause in an EXPECT_CALL()");

  a.DoA(2);
}

TEST(ExpectCallSyntaxTest, TimesCanBeInferred) {
  MockA a;

  EXPECT_CALL(a, DoA(1))
      .WillOnce(Return());

  EXPECT_CALL(a, DoA(2))
      .WillOnce(Return())
      .WillRepeatedly(Return());

  a.DoA(1);
  a.DoA(2);
  a.DoA(2);
}

TEST(ExpectCallSyntaxTest, TimesCanAppearAtMostOnce) {
  MockA a;

  EXPECT_NONFATAL_FAILURE({  // NOLINT
    EXPECT_CALL(a, DoA(1))
        .Times(1)
        .Times(2);
  }, ".Times() cannot appear more than once in an EXPECT_CALL()");

  a.DoA(1);
  a.DoA(1);
}

TEST(ExpectCallSyntaxTest, TimesMustBeBeforeInSequence) {
  MockA a;
  Sequence s;

  EXPECT_NONFATAL_FAILURE({  // NOLINT
    EXPECT_CALL(a, DoA(1))
        .InSequence(s)
        .Times(1);
  }, ".Times() cannot appear after ");

  a.DoA(1);
}

TEST(ExpectCallSyntaxTest, InSequenceIsOptional) {
  MockA a;
  Sequence s;

  EXPECT_CALL(a, DoA(1));
  EXPECT_CALL(a, DoA(2))
      .InSequence(s);

  a.DoA(1);
  a.DoA(2);
}

TEST(ExpectCallSyntaxTest, InSequenceCanAppearMultipleTimes) {
  MockA a;
  Sequence s1, s2;

  EXPECT_CALL(a, DoA(1))
      .InSequence(s1, s2)
      .InSequence(s1);

  a.DoA(1);
}

TEST(ExpectCallSyntaxTest, InSequenceMustBeBeforeAfter) {
  MockA a;
  Sequence s;

  Expectation e = EXPECT_CALL(a, DoA(1))
      .Times(AnyNumber());
  EXPECT_NONFATAL_FAILURE({  // NOLINT
    EXPECT_CALL(a, DoA(2))
        .After(e)
        .InSequence(s);
  }, ".InSequence() cannot appear after ");

  a.DoA(2);
}

TEST(ExpectCallSyntaxTest, InSequenceMustBeBeforeWillOnce) {
  MockA a;
  Sequence s;

  EXPECT_NONFATAL_FAILURE({  // NOLINT
    EXPECT_CALL(a, DoA(1))
        .WillOnce(Return())
        .InSequence(s);
  }, ".InSequence() cannot appear after ");

  a.DoA(1);
}

TEST(ExpectCallSyntaxTest, AfterMustBeBeforeWillOnce) {
  MockA a;

  Expectation e = EXPECT_CALL(a, DoA(1));
  EXPECT_NONFATAL_FAILURE({
    EXPECT_CALL(a, DoA(2))
        .WillOnce(Return())
        .After(e);
  }, ".After() cannot appear after ");

  a.DoA(1);
  a.DoA(2);
}

TEST(ExpectCallSyntaxTest, WillIsOptional) {
  MockA a;

  EXPECT_CALL(a, DoA(1));
  EXPECT_CALL(a, DoA(2))
      .WillOnce(Return());

  a.DoA(1);
  a.DoA(2);
}

TEST(ExpectCallSyntaxTest, WillCanAppearMultipleTimes) {
  MockA a;

  EXPECT_CALL(a, DoA(1))
      .Times(AnyNumber())
      .WillOnce(Return())
      .WillOnce(Return())
      .WillOnce(Return());
}

TEST(ExpectCallSyntaxTest, WillMustBeBeforeWillRepeatedly) {
  MockA a;

  EXPECT_NONFATAL_FAILURE({  // NOLINT
    EXPECT_CALL(a, DoA(1))
        .WillRepeatedly(Return())
        .WillOnce(Return());
  }, ".WillOnce() cannot appear after ");

  a.DoA(1);
}

TEST(ExpectCallSyntaxTest, WillRepeatedlyIsOptional) {
  MockA a;

  EXPECT_CALL(a, DoA(1))
      .WillOnce(Return());
  EXPECT_CALL(a, DoA(2))
      .WillOnce(Return())
      .WillRepeatedly(Return());

  a.DoA(1);
  a.DoA(2);
  a.DoA(2);
}

TEST(ExpectCallSyntaxTest, WillRepeatedlyCannotAppearMultipleTimes) {
  MockA a;

  EXPECT_NONFATAL_FAILURE({  // NOLINT
    EXPECT_CALL(a, DoA(1))
        .WillRepeatedly(Return())
        .WillRepeatedly(Return());
  }, ".WillRepeatedly() cannot appear more than once in an "
     "EXPECT_CALL()");
}

TEST(ExpectCallSyntaxTest, WillRepeatedlyMustBeBeforeRetiresOnSaturation) {
  MockA a;

  EXPECT_NONFATAL_FAILURE({  // NOLINT
    EXPECT_CALL(a, DoA(1))
        .RetiresOnSaturation()
        .WillRepeatedly(Return());
  }, ".WillRepeatedly() cannot appear after ");
}

TEST(ExpectCallSyntaxTest, RetiresOnSaturationIsOptional) {
  MockA a;

  EXPECT_CALL(a, DoA(1));
  EXPECT_CALL(a, DoA(1))
      .RetiresOnSaturation();

  a.DoA(1);
  a.DoA(1);
}

TEST(ExpectCallSyntaxTest, RetiresOnSaturationCannotAppearMultipleTimes) {
  MockA a;

  EXPECT_NONFATAL_FAILURE({  // NOLINT
    EXPECT_CALL(a, DoA(1))
        .RetiresOnSaturation()
        .RetiresOnSaturation();
  }, ".RetiresOnSaturation() cannot appear more than once");

  a.DoA(1);
}

TEST(ExpectCallSyntaxTest, DefaultCardinalityIsOnce) {
  {
    MockA a;
    EXPECT_CALL(a, DoA(1));
    a.DoA(1);
  }
  EXPECT_NONFATAL_FAILURE({  // NOLINT
    MockA a;
    EXPECT_CALL(a, DoA(1));
  }, "to be called once");
  EXPECT_NONFATAL_FAILURE({  // NOLINT
    MockA a;
    EXPECT_CALL(a, DoA(1));
    a.DoA(1);
    a.DoA(1);
  }, "to be called once");
}

#if GTEST_HAS_STREAM_REDIRECTION

// Tests that Google Mock doesn't print a warning when the number of
// WillOnce() is adequate.
TEST(ExpectCallSyntaxTest, DoesNotWarnOnAdequateActionCount) {
  CaptureStdout();
  {
    MockB b;

    // It's always fine to omit WillOnce() entirely.
    EXPECT_CALL(b, DoB())
        .Times(0);
    EXPECT_CALL(b, DoB(1))
        .Times(AtMost(1));
    EXPECT_CALL(b, DoB(2))
        .Times(1)
        .WillRepeatedly(Return(1));

    // It's fine for the number of WillOnce()s to equal the upper bound.
    EXPECT_CALL(b, DoB(3))
        .Times(Between(1, 2))
        .WillOnce(Return(1))
        .WillOnce(Return(2));

    // It's fine for the number of WillOnce()s to be smaller than the
    // upper bound when there is a WillRepeatedly().
    EXPECT_CALL(b, DoB(4))
        .Times(AtMost(3))
        .WillOnce(Return(1))
        .WillRepeatedly(Return(2));

    // Satisfies the above expectations.
    b.DoB(2);
    b.DoB(3);
  }
  EXPECT_STREQ("", GetCapturedStdout().c_str());
}

// Tests that Google Mock warns on having too many actions in an
// expectation compared to its cardinality.
TEST(ExpectCallSyntaxTest, WarnsOnTooManyActions) {
  CaptureStdout();
  {
    MockB b;

    // Warns when the number of WillOnce()s is larger than the upper bound.
    EXPECT_CALL(b, DoB())
        .Times(0)
        .WillOnce(Return(1));  // #1
    EXPECT_CALL(b, DoB())
        .Times(AtMost(1))
        .WillOnce(Return(1))
        .WillOnce(Return(2));  // #2
    EXPECT_CALL(b, DoB(1))
        .Times(1)
        .WillOnce(Return(1))
        .WillOnce(Return(2))
        .RetiresOnSaturation();  // #3

    // Warns when the number of WillOnce()s equals the upper bound and
    // there is a WillRepeatedly().
    EXPECT_CALL(b, DoB())
        .Times(0)
        .WillRepeatedly(Return(1));  // #4
    EXPECT_CALL(b, DoB(2))
        .Times(1)
        .WillOnce(Return(1))
        .WillRepeatedly(Return(2));  // #5

    // Satisfies the above expectations.
    b.DoB(1);
    b.DoB(2);
  }
  const std::string output = GetCapturedStdout();
  EXPECT_PRED_FORMAT2(
      IsSubstring,
      "Too many actions specified in EXPECT_CALL(b, DoB())...\n"
      "Expected to be never called, but has 1 WillOnce().",
      output);  // #1
  EXPECT_PRED_FORMAT2(
      IsSubstring,
      "Too many actions specified in EXPECT_CALL(b, DoB())...\n"
      "Expected to be called at most once, "
      "but has 2 WillOnce()s.",
      output);  // #2
  EXPECT_PRED_FORMAT2(
      IsSubstring,
      "Too many actions specified in EXPECT_CALL(b, DoB(1))...\n"
      "Expected to be called once, but has 2 WillOnce()s.",
      output);  // #3
  EXPECT_PRED_FORMAT2(
      IsSubstring,
      "Too many actions specified in EXPECT_CALL(b, DoB())...\n"
      "Expected to be never called, but has 0 WillOnce()s "
      "and a WillRepeatedly().",
      output);  // #4
  EXPECT_PRED_FORMAT2(
      IsSubstring,
      "Too many actions specified in EXPECT_CALL(b, DoB(2))...\n"
      "Expected to be called once, but has 1 WillOnce() "
      "and a WillRepeatedly().",
      output);  // #5
}

// Tests that Google Mock warns on having too few actions in an
// expectation compared to its cardinality.
TEST(ExpectCallSyntaxTest, WarnsOnTooFewActions) {
  MockB b;

  EXPECT_CALL(b, DoB())
      .Times(Between(2, 3))
      .WillOnce(Return(1));

  CaptureStdout();
  b.DoB();
  const std::string output = GetCapturedStdout();
  EXPECT_PRED_FORMAT2(
      IsSubstring,
      "Too few actions specified in EXPECT_CALL(b, DoB())...\n"
      "Expected to be called between 2 and 3 times, "
      "but has only 1 WillOnce().",
      output);
  b.DoB();
}

#endif  // GTEST_HAS_STREAM_REDIRECTION

// Tests the semantics of ON_CALL().

// Tests that the built-in default action is taken when no ON_CALL()
// is specified.
TEST(OnCallTest, TakesBuiltInDefaultActionWhenNoOnCall) {
  MockB b;
  EXPECT_CALL(b, DoB());

  EXPECT_EQ(0, b.DoB());
}

// Tests that the built-in default action is taken when no ON_CALL()
// matches the invocation.
TEST(OnCallTest, TakesBuiltInDefaultActionWhenNoOnCallMatches) {
  MockB b;
  ON_CALL(b, DoB(1))
      .WillByDefault(Return(1));
  EXPECT_CALL(b, DoB(_));

  EXPECT_EQ(0, b.DoB(2));
}

// Tests that the last matching ON_CALL() action is taken.
TEST(OnCallTest, PicksLastMatchingOnCall) {
  MockB b;
  ON_CALL(b, DoB(_))
      .WillByDefault(Return(3));
  ON_CALL(b, DoB(2))
      .WillByDefault(Return(2));
  ON_CALL(b, DoB(1))
      .WillByDefault(Return(1));
  EXPECT_CALL(b, DoB(_));

  EXPECT_EQ(2, b.DoB(2));
}

// Tests the semantics of EXPECT_CALL().

// Tests that any call is allowed when no EXPECT_CALL() is specified.
TEST(ExpectCallTest, AllowsAnyCallWhenNoSpec) {
  MockB b;
  EXPECT_CALL(b, DoB());
  // There is no expectation on DoB(int).

  b.DoB();

  // DoB(int) can be called any number of times.
  b.DoB(1);
  b.DoB(2);
}

// Tests that the last matching EXPECT_CALL() fires.
TEST(ExpectCallTest, PicksLastMatchingExpectCall) {
  MockB b;
  EXPECT_CALL(b, DoB(_))
      .WillRepeatedly(Return(2));
  EXPECT_CALL(b, DoB(1))
      .WillRepeatedly(Return(1));

  EXPECT_EQ(1, b.DoB(1));
}

// Tests lower-bound violation.
TEST(ExpectCallTest, CatchesTooFewCalls) {
  EXPECT_NONFATAL_FAILURE({  // NOLINT
    MockB b;
    EXPECT_CALL(b, DoB(5))
        .Times(AtLeast(2));

    b.DoB(5);
  }, "Actual function call count doesn't match EXPECT_CALL(b, DoB(5))...\n"
     "         Expected: to be called at least twice\n"
     "           Actual: called once - unsatisfied and active");
}

// Tests that the cardinality can be inferred when no Times(...) is
// specified.
TEST(ExpectCallTest, InfersCardinalityWhenThereIsNoWillRepeatedly) {
  {
    MockB b;
    EXPECT_CALL(b, DoB())
        .WillOnce(Return(1))
        .WillOnce(Return(2));

    EXPECT_EQ(1, b.DoB());
    EXPECT_EQ(2, b.DoB());
  }

  EXPECT_NONFATAL_FAILURE({  // NOLINT
    MockB b;
    EXPECT_CALL(b, DoB())
        .WillOnce(Return(1))
        .WillOnce(Return(2));

    EXPECT_EQ(1, b.DoB());
  }, "to be called twice");

  {  // NOLINT
    MockB b;
    EXPECT_CALL(b, DoB())
        .WillOnce(Return(1))
        .WillOnce(Return(2));

    EXPECT_EQ(1, b.DoB());
    EXPECT_EQ(2, b.DoB());
    EXPECT_NONFATAL_FAILURE(b.DoB(), "to be called twice");
  }
}

TEST(ExpectCallTest, InfersCardinality1WhenThereIsWillRepeatedly) {
  {
    MockB b;
    EXPECT_CALL(b, DoB())
        .WillOnce(Return(1))
        .WillRepeatedly(Return(2));

    EXPECT_EQ(1, b.DoB());
  }

  {  // NOLINT
    MockB b;
    EXPECT_CALL(b, DoB())
        .WillOnce(Return(1))
        .WillRepeatedly(Return(2));

    EXPECT_EQ(1, b.DoB());
    EXPECT_EQ(2, b.DoB());
    EXPECT_EQ(2, b.DoB());
  }

  EXPECT_NONFATAL_FAILURE({  // NOLINT
    MockB b;
    EXPECT_CALL(b, DoB())
        .WillOnce(Return(1))
        .WillRepeatedly(Return(2));
  }, "to be called at least once");
}

// Tests that the n-th action is taken for the n-th matching
// invocation.
TEST(ExpectCallTest, NthMatchTakesNthAction) {
  MockB b;
  EXPECT_CALL(b, DoB())
      .WillOnce(Return(1))
      .WillOnce(Return(2))
      .WillOnce(Return(3));

  EXPECT_EQ(1, b.DoB());
  EXPECT_EQ(2, b.DoB());
  EXPECT_EQ(3, b.DoB());
}

// Tests that the WillRepeatedly() action is taken when the WillOnce(...)
// list is exhausted.
TEST(ExpectCallTest, TakesRepeatedActionWhenWillListIsExhausted) {
  MockB b;
  EXPECT_CALL(b, DoB())
      .WillOnce(Return(1))
      .WillRepeatedly(Return(2));

  EXPECT_EQ(1, b.DoB());
  EXPECT_EQ(2, b.DoB());
  EXPECT_EQ(2, b.DoB());
}

#if GTEST_HAS_STREAM_REDIRECTION

// Tests that the default action is taken when the WillOnce(...) list is
// exhausted and there is no WillRepeatedly().
TEST(ExpectCallTest, TakesDefaultActionWhenWillListIsExhausted) {
  MockB b;
  EXPECT_CALL(b, DoB(_))
      .Times(1);
  EXPECT_CALL(b, DoB())
      .Times(AnyNumber())
      .WillOnce(Return(1))
      .WillOnce(Return(2));

  CaptureStdout();
  EXPECT_EQ(0, b.DoB(1));  // Shouldn't generate a warning as the
                           // expectation has no action clause at all.
  EXPECT_EQ(1, b.DoB());
  EXPECT_EQ(2, b.DoB());
  const std::string output1 = GetCapturedStdout();
  EXPECT_STREQ("", output1.c_str());

  CaptureStdout();
  EXPECT_EQ(0, b.DoB());
  EXPECT_EQ(0, b.DoB());
  const std::string output2 = GetCapturedStdout();
  EXPECT_THAT(output2.c_str(),
              HasSubstr("Actions ran out in EXPECT_CALL(b, DoB())...\n"
                        "Called 3 times, but only 2 WillOnce()s are specified"
                        " - returning default value."));
  EXPECT_THAT(output2.c_str(),
              HasSubstr("Actions ran out in EXPECT_CALL(b, DoB())...\n"
                        "Called 4 times, but only 2 WillOnce()s are specified"
                        " - returning default value."));
}

TEST(FunctionMockerMessageTest, ReportsExpectCallLocationForExhausedActions) {
  MockB b;
  std::string expect_call_location = FormatFileLocation(__FILE__, __LINE__ + 1);
  EXPECT_CALL(b, DoB()).Times(AnyNumber()).WillOnce(Return(1));

  EXPECT_EQ(1, b.DoB());

  CaptureStdout();
  EXPECT_EQ(0, b.DoB());
  const std::string output = GetCapturedStdout();
  // The warning message should contain the call location.
  EXPECT_PRED_FORMAT2(IsSubstring, expect_call_location, output);
}

TEST(FunctionMockerMessageTest,
     ReportsDefaultActionLocationOfUninterestingCallsForNaggyMock) {
  std::string on_call_location;
  CaptureStdout();
  {
    NaggyMock<MockB> b;
    on_call_location = FormatFileLocation(__FILE__, __LINE__ + 1);
    ON_CALL(b, DoB(_)).WillByDefault(Return(0));
    b.DoB(0);
  }
  EXPECT_PRED_FORMAT2(IsSubstring, on_call_location, GetCapturedStdout());
}

#endif  // GTEST_HAS_STREAM_REDIRECTION

// Tests that an uninteresting call performs the default action.
TEST(UninterestingCallTest, DoesDefaultAction) {
  // When there is an ON_CALL() statement, the action specified by it
  // should be taken.
  MockA a;
  ON_CALL(a, Binary(_, _))
      .WillByDefault(Return(true));
  EXPECT_TRUE(a.Binary(1, 2));

  // When there is no ON_CALL(), the default value for the return type
  // should be returned.
  MockB b;
  EXPECT_EQ(0, b.DoB());
}

// Tests that an unexpected call performs the default action.
TEST(UnexpectedCallTest, DoesDefaultAction) {
  // When there is an ON_CALL() statement, the action specified by it
  // should be taken.
  MockA a;
  ON_CALL(a, Binary(_, _))
      .WillByDefault(Return(true));
  EXPECT_CALL(a, Binary(0, 0));
  a.Binary(0, 0);
  bool result = false;
  EXPECT_NONFATAL_FAILURE(result = a.Binary(1, 2),
                          "Unexpected mock function call");
  EXPECT_TRUE(result);

  // When there is no ON_CALL(), the default value for the return type
  // should be returned.
  MockB b;
  EXPECT_CALL(b, DoB(0))
      .Times(0);
  int n = -1;
  EXPECT_NONFATAL_FAILURE(n = b.DoB(1),
                          "Unexpected mock function call");
  EXPECT_EQ(0, n);
}

// Tests that when an unexpected void function generates the right
// failure message.
TEST(UnexpectedCallTest, GeneratesFailureForVoidFunction) {
  // First, tests the message when there is only one EXPECT_CALL().
  MockA a1;
  EXPECT_CALL(a1, DoA(1));
  a1.DoA(1);
  // Ideally we should match the failure message against a regex, but
  // EXPECT_NONFATAL_FAILURE doesn't support that, so we test for
  // multiple sub-strings instead.
  EXPECT_NONFATAL_FAILURE(
      a1.DoA(9),
      "Unexpected mock function call - returning directly.\n"
      "    Function call: DoA(9)\n"
      "Google Mock tried the following 1 expectation, but it didn't match:");
  EXPECT_NONFATAL_FAILURE(
      a1.DoA(9),
      "  Expected arg #0: is equal to 1\n"
      "           Actual: 9\n"
      "         Expected: to be called once\n"
      "           Actual: called once - saturated and active");

  // Next, tests the message when there are more than one EXPECT_CALL().
  MockA a2;
  EXPECT_CALL(a2, DoA(1));
  EXPECT_CALL(a2, DoA(3));
  a2.DoA(1);
  EXPECT_NONFATAL_FAILURE(
      a2.DoA(2),
      "Unexpected mock function call - returning directly.\n"
      "    Function call: DoA(2)\n"
      "Google Mock tried the following 2 expectations, but none matched:");
  EXPECT_NONFATAL_FAILURE(
      a2.DoA(2),
      "tried expectation #0: EXPECT_CALL(a2, DoA(1))...\n"
      "  Expected arg #0: is equal to 1\n"
      "           Actual: 2\n"
      "         Expected: to be called once\n"
      "           Actual: called once - saturated and active");
  EXPECT_NONFATAL_FAILURE(
      a2.DoA(2),
      "tried expectation #1: EXPECT_CALL(a2, DoA(3))...\n"
      "  Expected arg #0: is equal to 3\n"
      "           Actual: 2\n"
      "         Expected: to be called once\n"
      "           Actual: never called - unsatisfied and active");
  a2.DoA(3);
}

// Tests that an unexpected non-void function generates the right
// failure message.
TEST(UnexpectedCallTest, GeneartesFailureForNonVoidFunction) {
  MockB b1;
  EXPECT_CALL(b1, DoB(1));
  b1.DoB(1);
  EXPECT_NONFATAL_FAILURE(
      b1.DoB(2),
      "Unexpected mock function call - returning default value.\n"
      "    Function call: DoB(2)\n"
      "          Returns: 0\n"
      "Google Mock tried the following 1 expectation, but it didn't match:");
  EXPECT_NONFATAL_FAILURE(
      b1.DoB(2),
      "  Expected arg #0: is equal to 1\n"
      "           Actual: 2\n"
      "         Expected: to be called once\n"
      "           Actual: called once - saturated and active");
}

// Tests that Google Mock explains that an retired expectation doesn't
// match the call.
TEST(UnexpectedCallTest, RetiredExpectation) {
  MockB b;
  EXPECT_CALL(b, DoB(1))
      .RetiresOnSaturation();

  b.DoB(1);
  EXPECT_NONFATAL_FAILURE(
      b.DoB(1),
      "         Expected: the expectation is active\n"
      "           Actual: it is retired");
}

// Tests that Google Mock explains that an expectation that doesn't
// match the arguments doesn't match the call.
TEST(UnexpectedCallTest, UnmatchedArguments) {
  MockB b;
  EXPECT_CALL(b, DoB(1));

  EXPECT_NONFATAL_FAILURE(
      b.DoB(2),
      "  Expected arg #0: is equal to 1\n"
      "           Actual: 2\n");
  b.DoB(1);
}

// Tests that Google Mock explains that an expectation with
// unsatisfied pre-requisites doesn't match the call.
TEST(UnexpectedCallTest, UnsatisifiedPrerequisites) {
  Sequence s1, s2;
  MockB b;
  EXPECT_CALL(b, DoB(1))
      .InSequence(s1);
  EXPECT_CALL(b, DoB(2))
      .Times(AnyNumber())
      .InSequence(s1);
  EXPECT_CALL(b, DoB(3))
      .InSequence(s2);
  EXPECT_CALL(b, DoB(4))
      .InSequence(s1, s2);

  ::testing::TestPartResultArray failures;
  {
    ::testing::ScopedFakeTestPartResultReporter reporter(&failures);
    b.DoB(4);
    // Now 'failures' contains the Google Test failures generated by
    // the above statement.
  }

  // There should be one non-fatal failure.
  ASSERT_EQ(1, failures.size());
  const ::testing::TestPartResult& r = failures.GetTestPartResult(0);
  EXPECT_EQ(::testing::TestPartResult::kNonFatalFailure, r.type());

  // Verifies that the failure message contains the two unsatisfied
  // pre-requisites but not the satisfied one.
#if GTEST_USES_PCRE
  EXPECT_THAT(r.message(), ContainsRegex(
      // PCRE has trouble using (.|\n) to match any character, but
      // supports the (?s) prefix for using . to match any character.
      "(?s)the following immediate pre-requisites are not satisfied:\n"
      ".*: pre-requisite #0\n"
      ".*: pre-requisite #1"));
#elif GTEST_USES_POSIX_RE
  EXPECT_THAT(r.message(), ContainsRegex(
      // POSIX RE doesn't understand the (?s) prefix, but has no trouble
      // with (.|\n).
      "the following immediate pre-requisites are not satisfied:\n"
      "(.|\n)*: pre-requisite #0\n"
      "(.|\n)*: pre-requisite #1"));
#else
  // We can only use Google Test's own simple regex.
  EXPECT_THAT(r.message(), ContainsRegex(
      "the following immediate pre-requisites are not satisfied:"));
  EXPECT_THAT(r.message(), ContainsRegex(": pre-requisite #0"));
  EXPECT_THAT(r.message(), ContainsRegex(": pre-requisite #1"));
#endif  // GTEST_USES_PCRE

  b.DoB(1);
  b.DoB(3);
  b.DoB(4);
}

TEST(UndefinedReturnValueTest,
     ReturnValueIsMandatoryWhenNotDefaultConstructible) {
  MockA a;
  // TODO(wan@google.com): We should really verify the output message,
  // but we cannot yet due to that EXPECT_DEATH only captures stderr
  // while Google Mock logs to stdout.
#if GTEST_HAS_EXCEPTIONS
  EXPECT_ANY_THROW(a.ReturnNonDefaultConstructible());
#else
  EXPECT_DEATH_IF_SUPPORTED(a.ReturnNonDefaultConstructible(), "");
#endif
}

// Tests that an excessive call (one whose arguments match the
// matchers but is called too many times) performs the default action.
TEST(ExcessiveCallTest, DoesDefaultAction) {
  // When there is an ON_CALL() statement, the action specified by it
  // should be taken.
  MockA a;
  ON_CALL(a, Binary(_, _))
      .WillByDefault(Return(true));
  EXPECT_CALL(a, Binary(0, 0));
  a.Binary(0, 0);
  bool result = false;
  EXPECT_NONFATAL_FAILURE(result = a.Binary(0, 0),
                          "Mock function called more times than expected");
  EXPECT_TRUE(result);

  // When there is no ON_CALL(), the default value for the return type
  // should be returned.
  MockB b;
  EXPECT_CALL(b, DoB(0))
      .Times(0);
  int n = -1;
  EXPECT_NONFATAL_FAILURE(n = b.DoB(0),
                          "Mock function called more times than expected");
  EXPECT_EQ(0, n);
}

// Tests that when a void function is called too many times,
// the failure message contains the argument values.
TEST(ExcessiveCallTest, GeneratesFailureForVoidFunction) {
  MockA a;
  EXPECT_CALL(a, DoA(_))
      .Times(0);
  EXPECT_NONFATAL_FAILURE(
      a.DoA(9),
      "Mock function called more times than expected - returning directly.\n"
      "    Function call: DoA(9)\n"
      "         Expected: to be never called\n"
      "           Actual: called once - over-saturated and active");
}

// Tests that when a non-void function is called too many times, the
// failure message contains the argument values and the return value.
TEST(ExcessiveCallTest, GeneratesFailureForNonVoidFunction) {
  MockB b;
  EXPECT_CALL(b, DoB(_));
  b.DoB(1);
  EXPECT_NONFATAL_FAILURE(
      b.DoB(2),
      "Mock function called more times than expected - "
      "returning default value.\n"
      "    Function call: DoB(2)\n"
      "          Returns: 0\n"
      "         Expected: to be called once\n"
      "           Actual: called twice - over-saturated and active");
}

// Tests using sequences.

TEST(InSequenceTest, AllExpectationInScopeAreInSequence) {
  MockA a;
  {
    InSequence dummy;

    EXPECT_CALL(a, DoA(1));
    EXPECT_CALL(a, DoA(2));
  }

  EXPECT_NONFATAL_FAILURE({  // NOLINT
    a.DoA(2);
  }, "Unexpected mock function call");

  a.DoA(1);
  a.DoA(2);
}

TEST(InSequenceTest, NestedInSequence) {
  MockA a;
  {
    InSequence dummy;

    EXPECT_CALL(a, DoA(1));
    {
      InSequence dummy2;

      EXPECT_CALL(a, DoA(2));
      EXPECT_CALL(a, DoA(3));
    }
  }

  EXPECT_NONFATAL_FAILURE({  // NOLINT
    a.DoA(1);
    a.DoA(3);
  }, "Unexpected mock function call");

  a.DoA(2);
  a.DoA(3);
}

TEST(InSequenceTest, ExpectationsOutOfScopeAreNotAffected) {
  MockA a;
  {
    InSequence dummy;

    EXPECT_CALL(a, DoA(1));
    EXPECT_CALL(a, DoA(2));
  }
  EXPECT_CALL(a, DoA(3));

  EXPECT_NONFATAL_FAILURE({  // NOLINT
    a.DoA(2);
  }, "Unexpected mock function call");

  a.DoA(3);
  a.DoA(1);
  a.DoA(2);
}

// Tests that any order is allowed when no sequence is used.
TEST(SequenceTest, AnyOrderIsOkByDefault) {
  {
    MockA a;
    MockB b;

    EXPECT_CALL(a, DoA(1));
    EXPECT_CALL(b, DoB())
        .Times(AnyNumber());

    a.DoA(1);
    b.DoB();
  }

  {  // NOLINT
    MockA a;
    MockB b;

    EXPECT_CALL(a, DoA(1));
    EXPECT_CALL(b, DoB())
        .Times(AnyNumber());

    b.DoB();
    a.DoA(1);
  }
}

// Tests that the calls must be in strict order when a complete order
// is specified.
TEST(SequenceTest, CallsMustBeInStrictOrderWhenSaidSo1) {
  MockA a;
  ON_CALL(a, ReturnResult(_))
      .WillByDefault(Return(Result()));

  Sequence s;
  EXPECT_CALL(a, ReturnResult(1))
      .InSequence(s);
  EXPECT_CALL(a, ReturnResult(2))
      .InSequence(s);
  EXPECT_CALL(a, ReturnResult(3))
      .InSequence(s);

  a.ReturnResult(1);

  // May only be called after a.ReturnResult(2).
  EXPECT_NONFATAL_FAILURE(a.ReturnResult(3), "Unexpected mock function call");

  a.ReturnResult(2);
  a.ReturnResult(3);
}

// Tests that the calls must be in strict order when a complete order
// is specified.
TEST(SequenceTest, CallsMustBeInStrictOrderWhenSaidSo2) {
  MockA a;
  ON_CALL(a, ReturnResult(_))
      .WillByDefault(Return(Result()));

  Sequence s;
  EXPECT_CALL(a, ReturnResult(1))
      .InSequence(s);
  EXPECT_CALL(a, ReturnResult(2))
      .InSequence(s);

  // May only be called after a.ReturnResult(1).
  EXPECT_NONFATAL_FAILURE(a.ReturnResult(2), "Unexpected mock function call");

  a.ReturnResult(1);
  a.ReturnResult(2);
}

// Tests specifying a DAG using multiple sequences.
class PartialOrderTest : public testing::Test {
 protected:
  PartialOrderTest() {
    ON_CALL(a_, ReturnResult(_))
        .WillByDefault(Return(Result()));

    // Specifies this partial ordering:
    //
    // a.ReturnResult(1) ==>
    //                       a.ReturnResult(2) * n  ==>  a.ReturnResult(3)
    // b.DoB() * 2       ==>
    Sequence x, y;
    EXPECT_CALL(a_, ReturnResult(1))
        .InSequence(x);
    EXPECT_CALL(b_, DoB())
        .Times(2)
        .InSequence(y);
    EXPECT_CALL(a_, ReturnResult(2))
        .Times(AnyNumber())
        .InSequence(x, y);
    EXPECT_CALL(a_, ReturnResult(3))
        .InSequence(x);
  }

  MockA a_;
  MockB b_;
};

TEST_F(PartialOrderTest, CallsMustConformToSpecifiedDag1) {
  a_.ReturnResult(1);
  b_.DoB();

  // May only be called after the second DoB().
  EXPECT_NONFATAL_FAILURE(a_.ReturnResult(2), "Unexpected mock function call");

  b_.DoB();
  a_.ReturnResult(3);
}

TEST_F(PartialOrderTest, CallsMustConformToSpecifiedDag2) {
  // May only be called after ReturnResult(1).
  EXPECT_NONFATAL_FAILURE(a_.ReturnResult(2), "Unexpected mock function call");

  a_.ReturnResult(1);
  b_.DoB();
  b_.DoB();
  a_.ReturnResult(3);
}

TEST_F(PartialOrderTest, CallsMustConformToSpecifiedDag3) {
  // May only be called last.
  EXPECT_NONFATAL_FAILURE(a_.ReturnResult(3), "Unexpected mock function call");

  a_.ReturnResult(1);
  b_.DoB();
  b_.DoB();
  a_.ReturnResult(3);
}

TEST_F(PartialOrderTest, CallsMustConformToSpecifiedDag4) {
  a_.ReturnResult(1);
  b_.DoB();
  b_.DoB();
  a_.ReturnResult(3);

  // May only be called before ReturnResult(3).
  EXPECT_NONFATAL_FAILURE(a_.ReturnResult(2), "Unexpected mock function call");
}

TEST(SequenceTest, Retirement) {
  MockA a;
  Sequence s;

  EXPECT_CALL(a, DoA(1))
      .InSequence(s);
  EXPECT_CALL(a, DoA(_))
      .InSequence(s)
      .RetiresOnSaturation();
  EXPECT_CALL(a, DoA(1))
      .InSequence(s);

  a.DoA(1);
  a.DoA(2);
  a.DoA(1);
}

// Tests Expectation.

TEST(ExpectationTest, ConstrutorsWork) {
  MockA a;
  Expectation e1;  // Default ctor.

  // Ctor from various forms of EXPECT_CALL.
  Expectation e2 = EXPECT_CALL(a, DoA(2));
  Expectation e3 = EXPECT_CALL(a, DoA(3)).With(_);
  {
    Sequence s;
    Expectation e4 = EXPECT_CALL(a, DoA(4)).Times(1);
    Expectation e5 = EXPECT_CALL(a, DoA(5)).InSequence(s);
  }
  Expectation e6 = EXPECT_CALL(a, DoA(6)).After(e2);
  Expectation e7 = EXPECT_CALL(a, DoA(7)).WillOnce(Return());
  Expectation e8 = EXPECT_CALL(a, DoA(8)).WillRepeatedly(Return());
  Expectation e9 = EXPECT_CALL(a, DoA(9)).RetiresOnSaturation();

  Expectation e10 = e2;  // Copy ctor.

  EXPECT_THAT(e1, Ne(e2));
  EXPECT_THAT(e2, Eq(e10));

  a.DoA(2);
  a.DoA(3);
  a.DoA(4);
  a.DoA(5);
  a.DoA(6);
  a.DoA(7);
  a.DoA(8);
  a.DoA(9);
}

TEST(ExpectationTest, AssignmentWorks) {
  MockA a;
  Expectation e1;
  Expectation e2 = EXPECT_CALL(a, DoA(1));

  EXPECT_THAT(e1, Ne(e2));

  e1 = e2;
  EXPECT_THAT(e1, Eq(e2));

  a.DoA(1);
}

// Tests ExpectationSet.

TEST(ExpectationSetTest, MemberTypesAreCorrect) {
  ::testing::StaticAssertTypeEq<Expectation, ExpectationSet::value_type>();
}

TEST(ExpectationSetTest, ConstructorsWork) {
  MockA a;

  Expectation e1;
  const Expectation e2;
  ExpectationSet es1;  // Default ctor.
  ExpectationSet es2 = EXPECT_CALL(a, DoA(1));  // Ctor from EXPECT_CALL.
  ExpectationSet es3 = e1;  // Ctor from Expectation.
  ExpectationSet es4(e1);   // Ctor from Expectation; alternative syntax.
  ExpectationSet es5 = e2;  // Ctor from const Expectation.
  ExpectationSet es6(e2);   // Ctor from const Expectation; alternative syntax.
  ExpectationSet es7 = es2;  // Copy ctor.

  EXPECT_EQ(0, es1.size());
  EXPECT_EQ(1, es2.size());
  EXPECT_EQ(1, es3.size());
  EXPECT_EQ(1, es4.size());
  EXPECT_EQ(1, es5.size());
  EXPECT_EQ(1, es6.size());
  EXPECT_EQ(1, es7.size());

  EXPECT_THAT(es3, Ne(es2));
  EXPECT_THAT(es4, Eq(es3));
  EXPECT_THAT(es5, Eq(es4));
  EXPECT_THAT(es6, Eq(es5));
  EXPECT_THAT(es7, Eq(es2));
  a.DoA(1);
}

TEST(ExpectationSetTest, AssignmentWorks) {
  ExpectationSet es1;
  ExpectationSet es2 = Expectation();

  es1 = es2;
  EXPECT_EQ(1, es1.size());
  EXPECT_THAT(*(es1.begin()), Eq(Expectation()));
  EXPECT_THAT(es1, Eq(es2));
}

TEST(ExpectationSetTest, InsertionWorks) {
  ExpectationSet es1;
  Expectation e1;
  es1 += e1;
  EXPECT_EQ(1, es1.size());
  EXPECT_THAT(*(es1.begin()), Eq(e1));

  MockA a;
  Expectation e2 = EXPECT_CALL(a, DoA(1));
  es1 += e2;
  EXPECT_EQ(2, es1.size());

  ExpectationSet::const_iterator it1 = es1.begin();
  ExpectationSet::const_iterator it2 = it1;
  ++it2;
  EXPECT_TRUE(*it1 == e1 || *it2 == e1);  // e1 must be in the set.
  EXPECT_TRUE(*it1 == e2 || *it2 == e2);  // e2 must be in the set too.
  a.DoA(1);
}

TEST(ExpectationSetTest, SizeWorks) {
  ExpectationSet es;
  EXPECT_EQ(0, es.size());

  es += Expectation();
  EXPECT_EQ(1, es.size());

  MockA a;
  es += EXPECT_CALL(a, DoA(1));
  EXPECT_EQ(2, es.size());

  a.DoA(1);
}

TEST(ExpectationSetTest, IsEnumerable) {
  ExpectationSet es;
  EXPECT_TRUE(es.begin() == es.end());

  es += Expectation();
  ExpectationSet::const_iterator it = es.begin();
  EXPECT_TRUE(it != es.end());
  EXPECT_THAT(*it, Eq(Expectation()));
  ++it;
  EXPECT_TRUE(it== es.end());
}

// Tests the .After() clause.

TEST(AfterTest, SucceedsWhenPartialOrderIsSatisfied) {
  MockA a;
  ExpectationSet es;
  es += EXPECT_CALL(a, DoA(1));
  es += EXPECT_CALL(a, DoA(2));
  EXPECT_CALL(a, DoA(3))
      .After(es);

  a.DoA(1);
  a.DoA(2);
  a.DoA(3);
}

TEST(AfterTest, SucceedsWhenTotalOrderIsSatisfied) {
  MockA a;
  MockB b;
  // The following also verifies that const Expectation objects work
  // too.  Do not remove the const modifiers.
  const Expectation e1 = EXPECT_CALL(a, DoA(1));
  const Expectation e2 = EXPECT_CALL(b, DoB())
      .Times(2)
      .After(e1);
  EXPECT_CALL(a, DoA(2)).After(e2);

  a.DoA(1);
  b.DoB();
  b.DoB();
  a.DoA(2);
}

// Calls must be in strict order when specified so using .After().
TEST(AfterTest, CallsMustBeInStrictOrderWhenSpecifiedSo1) {
  MockA a;
  MockB b;

  // Define ordering:
  //   a.DoA(1) ==> b.DoB() ==> a.DoA(2)
  Expectation e1 = EXPECT_CALL(a, DoA(1));
  Expectation e2 = EXPECT_CALL(b, DoB())
      .After(e1);
  EXPECT_CALL(a, DoA(2))
      .After(e2);

  a.DoA(1);

  // May only be called after DoB().
  EXPECT_NONFATAL_FAILURE(a.DoA(2), "Unexpected mock function call");

  b.DoB();
  a.DoA(2);
}

// Calls must be in strict order when specified so using .After().
TEST(AfterTest, CallsMustBeInStrictOrderWhenSpecifiedSo2) {
  MockA a;
  MockB b;

  // Define ordering:
  //   a.DoA(1) ==> b.DoB() * 2 ==> a.DoA(2)
  Expectation e1 = EXPECT_CALL(a, DoA(1));
  Expectation e2 = EXPECT_CALL(b, DoB())
      .Times(2)
      .After(e1);
  EXPECT_CALL(a, DoA(2))
      .After(e2);

  a.DoA(1);
  b.DoB();

  // May only be called after the second DoB().
  EXPECT_NONFATAL_FAILURE(a.DoA(2), "Unexpected mock function call");

  b.DoB();
  a.DoA(2);
}

// Calls must satisfy the partial order when specified so.
TEST(AfterTest, CallsMustSatisfyPartialOrderWhenSpecifiedSo) {
  MockA a;
  ON_CALL(a, ReturnResult(_))
      .WillByDefault(Return(Result()));

  // Define ordering:
  //   a.DoA(1) ==>
  //   a.DoA(2) ==> a.ReturnResult(3)
  Expectation e = EXPECT_CALL(a, DoA(1));
  const ExpectationSet es = EXPECT_CALL(a, DoA(2));
  EXPECT_CALL(a, ReturnResult(3))
      .After(e, es);

  // May only be called last.
  EXPECT_NONFATAL_FAILURE(a.ReturnResult(3), "Unexpected mock function call");

  a.DoA(2);
  a.DoA(1);
  a.ReturnResult(3);
}

// Calls must satisfy the partial order when specified so.
TEST(AfterTest, CallsMustSatisfyPartialOrderWhenSpecifiedSo2) {
  MockA a;

  // Define ordering:
  //   a.DoA(1) ==>
  //   a.DoA(2) ==> a.DoA(3)
  Expectation e = EXPECT_CALL(a, DoA(1));
  const ExpectationSet es = EXPECT_CALL(a, DoA(2));
  EXPECT_CALL(a, DoA(3))
      .After(e, es);

  a.DoA(2);

  // May only be called last.
  EXPECT_NONFATAL_FAILURE(a.DoA(3), "Unexpected mock function call");

  a.DoA(1);
  a.DoA(3);
}

// .After() can be combined with .InSequence().
TEST(AfterTest, CanBeUsedWithInSequence) {
  MockA a;
  Sequence s;
  Expectation e = EXPECT_CALL(a, DoA(1));
  EXPECT_CALL(a, DoA(2)).InSequence(s);
  EXPECT_CALL(a, DoA(3))
      .InSequence(s)
      .After(e);

  a.DoA(1);

  // May only be after DoA(2).
  EXPECT_NONFATAL_FAILURE(a.DoA(3), "Unexpected mock function call");

  a.DoA(2);
  a.DoA(3);
}

// .After() can be called multiple times.
TEST(AfterTest, CanBeCalledManyTimes) {
  MockA a;
  Expectation e1 = EXPECT_CALL(a, DoA(1));
  Expectation e2 = EXPECT_CALL(a, DoA(2));
  Expectation e3 = EXPECT_CALL(a, DoA(3));
  EXPECT_CALL(a, DoA(4))
      .After(e1)
      .After(e2)
      .After(e3);

  a.DoA(3);
  a.DoA(1);
  a.DoA(2);
  a.DoA(4);
}

// .After() accepts up to 5 arguments.
TEST(AfterTest, AcceptsUpToFiveArguments) {
  MockA a;
  Expectation e1 = EXPECT_CALL(a, DoA(1));
  Expectation e2 = EXPECT_CALL(a, DoA(2));
  Expectation e3 = EXPECT_CALL(a, DoA(3));
  ExpectationSet es1 = EXPECT_CALL(a, DoA(4));
  ExpectationSet es2 = EXPECT_CALL(a, DoA(5));
  EXPECT_CALL(a, DoA(6))
      .After(e1, e2, e3, es1, es2);

  a.DoA(5);
  a.DoA(2);
  a.DoA(4);
  a.DoA(1);
  a.DoA(3);
  a.DoA(6);
}

// .After() allows input to contain duplicated Expectations.
TEST(AfterTest, AcceptsDuplicatedInput) {
  MockA a;
  ON_CALL(a, ReturnResult(_))
      .WillByDefault(Return(Result()));

  // Define ordering:
  //   DoA(1) ==>
  //   DoA(2) ==> ReturnResult(3)
  Expectation e1 = EXPECT_CALL(a, DoA(1));
  Expectation e2 = EXPECT_CALL(a, DoA(2));
  ExpectationSet es;
  es += e1;
  es += e2;
  EXPECT_CALL(a, ReturnResult(3))
      .After(e1, e2, es, e1);

  a.DoA(1);

  // May only be after DoA(2).
  EXPECT_NONFATAL_FAILURE(a.ReturnResult(3), "Unexpected mock function call");

  a.DoA(2);
  a.ReturnResult(3);
}

// An Expectation added to an ExpectationSet after it has been used in
// an .After() has no effect.
TEST(AfterTest, ChangesToExpectationSetHaveNoEffectAfterwards) {
  MockA a;
  ExpectationSet es1 = EXPECT_CALL(a, DoA(1));
  Expectation e2 = EXPECT_CALL(a, DoA(2));
  EXPECT_CALL(a, DoA(3))
      .After(es1);
  es1 += e2;

  a.DoA(1);
  a.DoA(3);
  a.DoA(2);
}

// Tests that Google Mock correctly handles calls to mock functions
// after a mock object owning one of their pre-requisites has died.

// Tests that calls that satisfy the original spec are successful.
TEST(DeletingMockEarlyTest, Success1) {
  MockB* const b1 = new MockB;
  MockA* const a = new MockA;
  MockB* const b2 = new MockB;

  {
    InSequence dummy;
    EXPECT_CALL(*b1, DoB(_))
        .WillOnce(Return(1));
    EXPECT_CALL(*a, Binary(_, _))
        .Times(AnyNumber())
        .WillRepeatedly(Return(true));
    EXPECT_CALL(*b2, DoB(_))
        .Times(AnyNumber())
        .WillRepeatedly(Return(2));
  }

  EXPECT_EQ(1, b1->DoB(1));
  delete b1;
  // a's pre-requisite has died.
  EXPECT_TRUE(a->Binary(0, 1));
  delete b2;
  // a's successor has died.
  EXPECT_TRUE(a->Binary(1, 2));
  delete a;
}

// Tests that calls that satisfy the original spec are successful.
TEST(DeletingMockEarlyTest, Success2) {
  MockB* const b1 = new MockB;
  MockA* const a = new MockA;
  MockB* const b2 = new MockB;

  {
    InSequence dummy;
    EXPECT_CALL(*b1, DoB(_))
        .WillOnce(Return(1));
    EXPECT_CALL(*a, Binary(_, _))
        .Times(AnyNumber());
    EXPECT_CALL(*b2, DoB(_))
        .Times(AnyNumber())
        .WillRepeatedly(Return(2));
  }

  delete a;  // a is trivially satisfied.
  EXPECT_EQ(1, b1->DoB(1));
  EXPECT_EQ(2, b2->DoB(2));
  delete b1;
  delete b2;
}

// Tests that it's OK to delete a mock object itself in its action.

// Suppresses warning on unreferenced formal parameter in MSVC with
// -W4.
#ifdef _MSC_VER
# pragma warning(push)
# pragma warning(disable:4100)
#endif

ACTION_P(Delete, ptr) { delete ptr; }

#ifdef _MSC_VER
# pragma warning(pop)
#endif

TEST(DeletingMockEarlyTest, CanDeleteSelfInActionReturningVoid) {
  MockA* const a = new MockA;
  EXPECT_CALL(*a, DoA(_)).WillOnce(Delete(a));
  a->DoA(42);  // This will cause a to be deleted.
}

TEST(DeletingMockEarlyTest, CanDeleteSelfInActionReturningValue) {
  MockA* const a = new MockA;
  EXPECT_CALL(*a, ReturnResult(_))
      .WillOnce(DoAll(Delete(a), Return(Result())));
  a->ReturnResult(42);  // This will cause a to be deleted.
}

// Tests that calls that violate the original spec yield failures.
TEST(DeletingMockEarlyTest, Failure1) {
  MockB* const b1 = new MockB;
  MockA* const a = new MockA;
  MockB* const b2 = new MockB;

  {
    InSequence dummy;
    EXPECT_CALL(*b1, DoB(_))
        .WillOnce(Return(1));
    EXPECT_CALL(*a, Binary(_, _))
        .Times(AnyNumber());
    EXPECT_CALL(*b2, DoB(_))
        .Times(AnyNumber())
        .WillRepeatedly(Return(2));
  }

  delete a;  // a is trivially satisfied.
  EXPECT_NONFATAL_FAILURE({
    b2->DoB(2);
  }, "Unexpected mock function call");
  EXPECT_EQ(1, b1->DoB(1));