gmock_class_test.py 13.7 KB
Newer Older
1
2
#!/usr/bin/env python
#
misterg's avatar
misterg committed
3
4
# Copyright 2009 Neal Norwitz All Rights Reserved.
# Portions Copyright 2009 Google Inc. All Rights Reserved.
5
#
misterg's avatar
misterg committed
6
7
8
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
9
#
misterg's avatar
misterg committed
10
#      http://www.apache.org/licenses/LICENSE-2.0
11
#
misterg's avatar
misterg committed
12
13
14
15
16
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
17
18
19
20
21
22
23
24

"""Tests for gmock.scripts.generator.cpp.gmock_class."""

import os
import sys
import unittest

# Allow the cpp imports below to work when run as a standalone script.
25
sys.path.append(os.path.join(os.path.dirname(__file__), '..'))
26
27
28
29
30
31

from cpp import ast
from cpp import gmock_class


class TestCase(unittest.TestCase):
mhermas's avatar
mhermas committed
32
    """Helper class that adds assert methods."""
33

mhermas's avatar
mhermas committed
34
35
36
37
    @staticmethod
    def StripLeadingWhitespace(lines):
        """Strip leading whitespace in each line in 'lines'."""
        return '\n'.join([s.lstrip() for s in lines.split('\n')])
38

mhermas's avatar
mhermas committed
39
40
41
    def assertEqualIgnoreLeadingWhitespace(self, expected_lines, lines):
        """Specialized assert that ignores the indent level."""
        self.assertEqual(expected_lines, self.StripLeadingWhitespace(lines))
42
43
44
45


class GenerateMethodsTest(TestCase):

mhermas's avatar
mhermas committed
46
47
48
49
50
51
52
53
54
55
56
57
    @staticmethod
    def GenerateMethodSource(cpp_source):
        """Convert C++ source to Google Mock output source lines."""
        method_source_lines = []
        # <test> is a pseudo-filename, it is not read or written.
        builder = ast.BuilderFromSource(cpp_source, '<test>')
        ast_list = list(builder.Generate())
        gmock_class._GenerateMethods(method_source_lines, cpp_source, ast_list[0])
        return '\n'.join(method_source_lines)

    def testSimpleMethod(self):
        source = """
58
59
60
61
class Foo {
 public:
  virtual int Bar();
};
62
"""
mhermas's avatar
mhermas committed
63
64
65
        self.assertEqualIgnoreLeadingWhitespace(
            'MOCK_METHOD0(Bar,\nint());',
            self.GenerateMethodSource(source))
66

mhermas's avatar
mhermas committed
67
68
    def testSimpleConstructorsAndDestructor(self):
        source = """
69
70
71
72
73
74
75
76
77
78
class Foo {
 public:
  Foo();
  Foo(int x);
  Foo(const Foo& f);
  Foo(Foo&& f);
  ~Foo();
  virtual int Bar() = 0;
};
"""
mhermas's avatar
mhermas committed
79
80
81
82
        # The constructors and destructor should be ignored.
        self.assertEqualIgnoreLeadingWhitespace(
            'MOCK_METHOD0(Bar,\nint());',
            self.GenerateMethodSource(source))
83

mhermas's avatar
mhermas committed
84
85
    def testVirtualDestructor(self):
        source = """
86
87
88
89
90
91
class Foo {
 public:
  virtual ~Foo();
  virtual int Bar() = 0;
};
"""
mhermas's avatar
mhermas committed
92
93
94
95
        # The destructor should be ignored.
        self.assertEqualIgnoreLeadingWhitespace(
            'MOCK_METHOD0(Bar,\nint());',
            self.GenerateMethodSource(source))
96

mhermas's avatar
mhermas committed
97
98
    def testExplicitlyDefaultedConstructorsAndDestructor(self):
        source = """
99
100
101
102
103
104
105
106
107
class Foo {
 public:
  Foo() = default;
  Foo(const Foo& f) = default;
  Foo(Foo&& f) = default;
  ~Foo() = default;
  virtual int Bar() = 0;
};
"""
mhermas's avatar
mhermas committed
108
109
110
111
        # The constructors and destructor should be ignored.
        self.assertEqualIgnoreLeadingWhitespace(
            'MOCK_METHOD0(Bar,\nint());',
            self.GenerateMethodSource(source))
112

mhermas's avatar
mhermas committed
113
114
    def testExplicitlyDeletedConstructorsAndDestructor(self):
        source = """
115
116
117
118
119
120
121
122
123
class Foo {
 public:
  Foo() = delete;
  Foo(const Foo& f) = delete;
  Foo(Foo&& f) = delete;
  ~Foo() = delete;
  virtual int Bar() = 0;
};
"""
mhermas's avatar
mhermas committed
124
125
126
127
        # The constructors and destructor should be ignored.
        self.assertEqualIgnoreLeadingWhitespace(
            'MOCK_METHOD0(Bar,\nint());',
            self.GenerateMethodSource(source))
128

mhermas's avatar
mhermas committed
129
130
    def testSimpleOverrideMethod(self):
        source = """
131
132
133
134
class Foo {
 public:
  int Bar() override;
};
135
"""
mhermas's avatar
mhermas committed
136
137
138
        self.assertEqualIgnoreLeadingWhitespace(
            'MOCK_METHOD0(Bar,\nint());',
            self.GenerateMethodSource(source))
139

mhermas's avatar
mhermas committed
140
141
    def testSimpleConstMethod(self):
        source = """
142
143
144
145
146
class Foo {
 public:
  virtual void Bar(bool flag) const;
};
"""
mhermas's avatar
mhermas committed
147
148
149
        self.assertEqualIgnoreLeadingWhitespace(
            'MOCK_CONST_METHOD1(Bar,\nvoid(bool flag));',
            self.GenerateMethodSource(source))
150

mhermas's avatar
mhermas committed
151
152
    def testExplicitVoid(self):
        source = """
vladlosev's avatar
vladlosev committed
153
154
155
156
157
class Foo {
 public:
  virtual int Bar(void);
};
"""
mhermas's avatar
mhermas committed
158
159
160
        self.assertEqualIgnoreLeadingWhitespace(
            'MOCK_METHOD0(Bar,\nint(void));',
            self.GenerateMethodSource(source))
vladlosev's avatar
vladlosev committed
161

mhermas's avatar
mhermas committed
162
163
    def testStrangeNewlineInParameter(self):
        source = """
164
165
166
167
168
169
class Foo {
 public:
  virtual void Bar(int
a) = 0;
};
"""
mhermas's avatar
mhermas committed
170
171
172
        self.assertEqualIgnoreLeadingWhitespace(
            'MOCK_METHOD1(Bar,\nvoid(int a));',
            self.GenerateMethodSource(source))
173

mhermas's avatar
mhermas committed
174
175
    def testDefaultParameters(self):
        source = """
vladlosev's avatar
vladlosev committed
176
177
178
179
180
class Foo {
 public:
  virtual void Bar(int a, char c = 'x') = 0;
};
"""
mhermas's avatar
mhermas committed
181
182
183
        self.assertEqualIgnoreLeadingWhitespace(
            'MOCK_METHOD2(Bar,\nvoid(int a, char c ));',
            self.GenerateMethodSource(source))
vladlosev's avatar
vladlosev committed
184

mhermas's avatar
mhermas committed
185
186
    def testMultipleDefaultParameters(self):
        source = """
vladlosev's avatar
vladlosev committed
187
188
class Foo {
 public:
mhermas's avatar
mhermas committed
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
  virtual void Bar(
        int a = 42, 
        char c = 'x', 
        const int* const p = nullptr, 
        const std::string& s = "42",
        char tab[] = {'4','2'},
        int const *& rp = aDefaultPointer) = 0;
};
"""
        self.assertEqualIgnoreLeadingWhitespace(
            "MOCK_METHOD7(Bar,\n"
            "void(int a , char c , const int* const p , const std::string& s , char tab[] , int const *& rp ));",
            self.GenerateMethodSource(source))

    def testConstDefaultParameter(self):
        source = """
class Test {
 public:
  virtual bool Bar(const int test_arg = 42) = 0;
};
"""
        expected = 'MOCK_METHOD1(Bar,\nbool(const int test_arg ));'
        self.assertEqualIgnoreLeadingWhitespace(
            expected, self.GenerateMethodSource(source))

    def testConstRefDefaultParameter(self):
        source = """
class Test {
 public:
  virtual bool Bar(const std::string& test_arg = "42" ) = 0;
vladlosev's avatar
vladlosev committed
219
220
};
"""
mhermas's avatar
mhermas committed
221
222
223
        expected = 'MOCK_METHOD1(Bar,\nbool(const std::string& test_arg ));'
        self.assertEqualIgnoreLeadingWhitespace(
            expected, self.GenerateMethodSource(source))
vladlosev's avatar
vladlosev committed
224

mhermas's avatar
mhermas committed
225
226
    def testRemovesCommentsWhenDefaultsArePresent(self):
        source = """
vladlosev's avatar
vladlosev committed
227
228
229
230
231
232
class Foo {
 public:
  virtual void Bar(int a = 42 /* a comment */,
                   char /* other comment */ c= 'x') = 0;
};
"""
mhermas's avatar
mhermas committed
233
234
235
        self.assertEqualIgnoreLeadingWhitespace(
            'MOCK_METHOD2(Bar,\nvoid(int a , char c));',
            self.GenerateMethodSource(source))
vladlosev's avatar
vladlosev committed
236

mhermas's avatar
mhermas committed
237
238
    def testDoubleSlashCommentsInParameterListAreRemoved(self):
        source = """
239
240
241
242
243
244
245
class Foo {
 public:
  virtual void Bar(int a,  // inline comments should be elided.
                   int b   // inline comments should be elided.
                   ) const = 0;
};
"""
mhermas's avatar
mhermas committed
246
247
248
        self.assertEqualIgnoreLeadingWhitespace(
            'MOCK_CONST_METHOD2(Bar,\nvoid(int a, int b));',
            self.GenerateMethodSource(source))
249

mhermas's avatar
mhermas committed
250
251
252
253
254
    def testCStyleCommentsInParameterListAreNotRemoved(self):
        # NOTE(nnorwitz): I'm not sure if it's the best behavior to keep these
        # comments.  Also note that C style comments after the last parameter
        # are still elided.
        source = """
255
256
257
258
259
class Foo {
 public:
  virtual const string& Bar(int /* keeper */, int b);
};
"""
mhermas's avatar
mhermas committed
260
261
262
        self.assertEqualIgnoreLeadingWhitespace(
            'MOCK_METHOD2(Bar,\nconst string&(int , int b));',
            self.GenerateMethodSource(source))
263

mhermas's avatar
mhermas committed
264
265
    def testArgsOfTemplateTypes(self):
        source = """
266
267
268
269
class Foo {
 public:
  virtual int Bar(const vector<int>& v, map<int, string>* output);
};"""
mhermas's avatar
mhermas committed
270
271
272
273
        self.assertEqualIgnoreLeadingWhitespace(
            'MOCK_METHOD2(Bar,\n'
            'int(const vector<int>& v, map<int, string>* output));',
            self.GenerateMethodSource(source))
274

mhermas's avatar
mhermas committed
275
276
    def testReturnTypeWithOneTemplateArg(self):
        source = """
277
278
279
280
class Foo {
 public:
  virtual vector<int>* Bar(int n);
};"""
mhermas's avatar
mhermas committed
281
282
283
        self.assertEqualIgnoreLeadingWhitespace(
            'MOCK_METHOD1(Bar,\nvector<int>*(int n));',
            self.GenerateMethodSource(source))
284

mhermas's avatar
mhermas committed
285
286
    def testReturnTypeWithManyTemplateArgs(self):
        source = """
287
288
289
290
class Foo {
 public:
  virtual map<int, string> Bar();
};"""
mhermas's avatar
mhermas committed
291
292
293
294
295
296
297
298
299
300
301
        # Comparing the comment text is brittle - we'll think of something
        # better in case this gets annoying, but for now let's keep it simple.
        self.assertEqualIgnoreLeadingWhitespace(
            '// The following line won\'t really compile, as the return\n'
            '// type has multiple template arguments.  To fix it, use a\n'
            '// typedef for the return type.\n'
            'MOCK_METHOD0(Bar,\nmap<int, string>());',
            self.GenerateMethodSource(source))

    def testSimpleMethodInTemplatedClass(self):
        source = """
302
303
304
305
306
307
template<class T>
class Foo {
 public:
  virtual int Bar();
};
"""
mhermas's avatar
mhermas committed
308
309
310
        self.assertEqualIgnoreLeadingWhitespace(
            'MOCK_METHOD0_T(Bar,\nint());',
            self.GenerateMethodSource(source))
311

mhermas's avatar
mhermas committed
312
313
    def testPointerArgWithoutNames(self):
        source = """
314
315
316
317
class Foo {
  virtual int Bar(C*);
};
"""
mhermas's avatar
mhermas committed
318
319
320
        self.assertEqualIgnoreLeadingWhitespace(
            'MOCK_METHOD1(Bar,\nint(C*));',
            self.GenerateMethodSource(source))
321

mhermas's avatar
mhermas committed
322
323
    def testReferenceArgWithoutNames(self):
        source = """
324
325
326
327
class Foo {
  virtual int Bar(C&);
};
"""
mhermas's avatar
mhermas committed
328
329
330
        self.assertEqualIgnoreLeadingWhitespace(
            'MOCK_METHOD1(Bar,\nint(C&));',
            self.GenerateMethodSource(source))
331

mhermas's avatar
mhermas committed
332
333
    def testArrayArgWithoutNames(self):
        source = """
334
335
336
337
class Foo {
  virtual int Bar(C[]);
};
"""
mhermas's avatar
mhermas committed
338
339
340
        self.assertEqualIgnoreLeadingWhitespace(
            'MOCK_METHOD1(Bar,\nint(C[]));',
            self.GenerateMethodSource(source))
341

342
343
344

class GenerateMocksTest(TestCase):

mhermas's avatar
mhermas committed
345
346
347
348
349
350
351
352
353
354
355
356
    @staticmethod
    def GenerateMocks(cpp_source):
        """Convert C++ source to complete Google Mock output source."""
        # <test> is a pseudo-filename, it is not read or written.
        filename = '<test>'
        builder = ast.BuilderFromSource(cpp_source, filename)
        ast_list = list(builder.Generate())
        lines = gmock_class._GenerateMocks(filename, cpp_source, ast_list, None)
        return '\n'.join(lines)

    def testNamespaces(self):
        source = """
357
358
359
360
361
362
363
364
365
366
367
368
namespace Foo {
namespace Bar { class Forward; }
namespace Baz {

class Test {
 public:
  virtual void Foo();
};

}  // namespace Baz
}  // namespace Foo
"""
mhermas's avatar
mhermas committed
369
        expected = """\
370
371
372
373
374
375
376
377
378
379
380
381
namespace Foo {
namespace Baz {

class MockTest : public Test {
public:
MOCK_METHOD0(Foo,
void());
};

}  // namespace Baz
}  // namespace Foo
"""
mhermas's avatar
mhermas committed
382
383
        self.assertEqualIgnoreLeadingWhitespace(
            expected, self.GenerateMocks(source))
384

mhermas's avatar
mhermas committed
385
386
    def testClassWithStorageSpecifierMacro(self):
        source = """
387
388
389
390
391
class STORAGE_SPECIFIER Test {
 public:
  virtual void Foo();
};
"""
mhermas's avatar
mhermas committed
392
        expected = """\
393
394
395
396
397
398
class MockTest : public Test {
public:
MOCK_METHOD0(Foo,
void());
};
"""
mhermas's avatar
mhermas committed
399
400
        self.assertEqualIgnoreLeadingWhitespace(
            expected, self.GenerateMocks(source))
401

mhermas's avatar
mhermas committed
402
403
    def testTemplatedForwardDeclaration(self):
        source = """
404
405
406
407
408
409
template <class T> class Forward;  // Forward declaration should be ignored.
class Test {
 public:
  virtual void Foo();
};
"""
mhermas's avatar
mhermas committed
410
        expected = """\
411
412
413
414
415
416
class MockTest : public Test {
public:
MOCK_METHOD0(Foo,
void());
};
"""
mhermas's avatar
mhermas committed
417
418
        self.assertEqualIgnoreLeadingWhitespace(
            expected, self.GenerateMocks(source))
419

mhermas's avatar
mhermas committed
420
421
    def testTemplatedClass(self):
        source = """
422
423
424
425
426
427
template <typename S, typename T>
class Test {
 public:
  virtual void Foo();
};
"""
mhermas's avatar
mhermas committed
428
        expected = """\
429
430
431
432
433
434
435
template <typename T0, typename T1>
class MockTest : public Test<T0, T1> {
public:
MOCK_METHOD0_T(Foo,
void());
};
"""
mhermas's avatar
mhermas committed
436
437
        self.assertEqualIgnoreLeadingWhitespace(
            expected, self.GenerateMocks(source))
438

mhermas's avatar
mhermas committed
439
440
    def testTemplateInATemplateTypedef(self):
        source = """
441
442
443
444
445
446
class Test {
 public:
  typedef std::vector<std::list<int>> FooType;
  virtual void Bar(const FooType& test_arg);
};
"""
mhermas's avatar
mhermas committed
447
        expected = """\
448
449
450
451
452
453
class MockTest : public Test {
public:
MOCK_METHOD1(Bar,
void(const FooType& test_arg));
};
"""
mhermas's avatar
mhermas committed
454
455
        self.assertEqualIgnoreLeadingWhitespace(
            expected, self.GenerateMocks(source))
456

mhermas's avatar
mhermas committed
457
458
    def testTemplateInATemplateTypedefWithComma(self):
        source = """
459
460
461
462
463
464
465
class Test {
 public:
  typedef std::function<void(
      const vector<std::list<int>>&, int> FooType;
  virtual void Bar(const FooType& test_arg);
};
"""
mhermas's avatar
mhermas committed
466
        expected = """\
467
468
469
470
471
class MockTest : public Test {
public:
MOCK_METHOD1(Bar,
void(const FooType& test_arg));
};
472
"""
mhermas's avatar
mhermas committed
473
474
        self.assertEqualIgnoreLeadingWhitespace(
            expected, self.GenerateMocks(source))
475

mhermas's avatar
mhermas committed
476
477
    def testEnumType(self):
        source = """
478
479
class Test {
 public:
Abseil Team's avatar
Abseil Team committed
480
481
482
483
  enum Bar {
    BAZ, QUX, QUUX, QUUUX
  };
  virtual void Foo();
484
485
};
"""
mhermas's avatar
mhermas committed
486
        expected = """\
487
488
class MockTest : public Test {
public:
Abseil Team's avatar
Abseil Team committed
489
490
491
492
MOCK_METHOD0(Foo,
void());
};
"""
mhermas's avatar
mhermas committed
493
494
        self.assertEqualIgnoreLeadingWhitespace(
            expected, self.GenerateMocks(source))
Abseil Team's avatar
Abseil Team committed
495

mhermas's avatar
mhermas committed
496
497
    def testEnumClassType(self):
        source = """
Abseil Team's avatar
Abseil Team committed
498
499
500
501
502
503
504
505
class Test {
 public:
  enum class Bar {
    BAZ, QUX, QUUX, QUUUX
  };
  virtual void Foo();
};
"""
mhermas's avatar
mhermas committed
506
        expected = """\
Abseil Team's avatar
Abseil Team committed
507
508
509
510
511
512
class MockTest : public Test {
public:
MOCK_METHOD0(Foo,
void());
};
"""
mhermas's avatar
mhermas committed
513
514
        self.assertEqualIgnoreLeadingWhitespace(
            expected, self.GenerateMocks(source))
Abseil Team's avatar
Abseil Team committed
515

mhermas's avatar
mhermas committed
516
517
    def testStdFunction(self):
        source = """
Abseil Team's avatar
Abseil Team committed
518
519
520
521
522
523
524
525
526
527
class Test {
 public:
  Test(std::function<int(std::string)> foo) : foo_(foo) {}

  virtual std::function<int(std::string)> foo();

 private:
  std::function<int(std::string)> foo_;
};
"""
mhermas's avatar
mhermas committed
528
        expected = """\
Abseil Team's avatar
Abseil Team committed
529
530
531
532
class MockTest : public Test {
public:
MOCK_METHOD0(foo,
std::function<int (std::string)>());
533
};
534
"""
mhermas's avatar
mhermas committed
535
536
537
        self.assertEqualIgnoreLeadingWhitespace(
            expected, self.GenerateMocks(source))

538

539
if __name__ == '__main__':
mhermas's avatar
mhermas committed
540
    unittest.main()