gmock_doctor.py 16.5 KB
Newer Older
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
#!/usr/bin/python2.4
#
# Copyright 2008, 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.

"""Converts gcc errors in code using Google Mock to plain English."""

__author__ = 'wan@google.com (Zhanyong Wan)'

import re
import sys

39
_VERSION = '1.0.3'
40
41
42
43
44
45
46
47
48

_COMMON_GMOCK_SYMBOLS = [
    # Matchers
    '_',
    'A',
    'AddressSatisfies',
    'AllOf',
    'An',
    'AnyOf',
49
50
    'ContainerEq',
    'Contains',
51
52
    'ContainsRegex',
    'DoubleEq',
53
54
    'ElementsAre',
    'ElementsAreArray',
55
56
57
58
59
60
61
    'EndsWith',
    'Eq',
    'Field',
    'FloatEq',
    'Ge',
    'Gt',
    'HasSubstr',
62
    'IsInitializedProto',
63
64
65
    'Le',
    'Lt',
    'MatcherCast',
66
    'Matches',
67
    'MatchesRegex',
68
69
    'NanSensitiveDoubleEq',
    'NanSensitiveFloatEq',
70
71
72
73
74
75
    'Ne',
    'Not',
    'NotNull',
    'Pointee',
    'Property',
    'Ref',
76
77
    'ResultOf',
    'SafeMatcherCast',
78
79
80
81
82
83
84
    'StartsWith',
    'StrCaseEq',
    'StrCaseNe',
    'StrEq',
    'StrNe',
    'Truly',
    'TypedEq',
85
    'Value',
86
87

    # Actions
88
    'Assign',
89
    'ByRef',
90
    'DeleteArg',
91
92
93
94
95
96
97
    'DoAll',
    'DoDefault',
    'IgnoreResult',
    'Invoke',
    'InvokeArgument',
    'InvokeWithoutArgs',
    'Return',
98
    'ReturnNew',
99
100
    'ReturnNull',
    'ReturnRef',
101
102
    'SaveArg',
    'SetArgReferee',
103
104
    'SetArgumentPointee',
    'SetArrayArgument',
105
106
107
    'SetErrnoAndReturn',
    'Throw',
    'WithArg',
108
    'WithArgs',
109
    'WithoutArgs',
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126

    # Cardinalities
    'AnyNumber',
    'AtLeast',
    'AtMost',
    'Between',
    'Exactly',

    # Sequences
    'InSequence',
    'Sequence',

    # Misc
    'DefaultValue',
    'Mock',
    ]

127
128
129
# Regex for matching source file path and line number in gcc's errors.
_FILE_LINE_RE = r'(?P<file>.*):(?P<line>\d+):\s+'

130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151

def _FindAllMatches(regex, s):
  """Generates all matches of regex in string s."""

  r = re.compile(regex)
  return r.finditer(s)


def _GenericDiagnoser(short_name, long_name, regex, diagnosis, msg):
  """Diagnoses the given disease by pattern matching.

  Args:
    short_name: Short name of the disease.
    long_name:  Long name of the disease.
    regex:      Regex for matching the symptoms.
    diagnosis:  Pattern for formatting the diagnosis.
    msg:        Gcc's error messages.
  Yields:
    Tuples of the form
      (short name of disease, long name of disease, diagnosis).
  """

152
  diagnosis = '%(file)s:%(line)s:' + diagnosis
153
154
155
156
157
158
159
160
  for m in _FindAllMatches(regex, msg):
    yield (short_name, long_name, diagnosis % m.groupdict())


def _NeedToReturnReferenceDiagnoser(msg):
  """Diagnoses the NRR disease, given the error messages by gcc."""

  regex = (r'In member function \'testing::internal::ReturnAction<R>.*\n'
161
           + _FILE_LINE_RE + r'instantiated from here\n'
162
           r'.*gmock-actions\.h.*error: creating array with negative size')
163
  diagnosis = """
164
165
166
167
168
169
170
171
172
You are using an Return() action in a function that returns a reference.
Please use ReturnRef() instead."""
  return _GenericDiagnoser('NRR', 'Need to Return Reference',
                           regex, diagnosis, msg)


def _NeedToReturnSomethingDiagnoser(msg):
  """Diagnoses the NRS disease, given the error messages by gcc."""

173
  regex = (_FILE_LINE_RE +
174
           r'(instantiated from here\n.'
175
           r'*gmock.*actions\.h.*error: void value not ignored)'
176
           r'|(error: control reaches end of non-void function)')
177
  diagnosis = """
178
You are using an action that returns void, but it needs to return
179
180
*something*.  Please tell it *what* to return.  Perhaps you can use
the pattern DoAll(some_action, Return(some_value))?"""
181
182
183
184
185
186
187
  return _GenericDiagnoser('NRS', 'Need to Return Something',
                           regex, diagnosis, msg)


def _NeedToReturnNothingDiagnoser(msg):
  """Diagnoses the NRN disease, given the error messages by gcc."""

188
  regex = (_FILE_LINE_RE + r'instantiated from here\n'
189
190
           r'.*gmock-actions\.h.*error: return-statement with a value, '
           r'in function returning \'void\'')
191
  diagnosis = """
192
193
194
195
196
197
198
199
200
201
202
203
You are using an action that returns *something*, but it needs to return
void.  Please use a void-returning action instead.

All actions but the last in DoAll(...) must return void.  Perhaps you need
to re-arrange the order of actions in a DoAll(), if you are using one?"""
  return _GenericDiagnoser('NRN', 'Need to Return Nothing',
                           regex, diagnosis, msg)


def _IncompleteByReferenceArgumentDiagnoser(msg):
  """Diagnoses the IBRA disease, given the error messages by gcc."""

204
  regex = (_FILE_LINE_RE + r'instantiated from here\n'
205
206
           r'.*gmock-printers\.h.*error: invalid application of '
           r'\'sizeof\' to incomplete type \'(?P<type>.*)\'')
207
  diagnosis = """
208
209
210
211
212
213
214
215
216
217
218
In order to mock this function, Google Mock needs to see the definition
of type "%(type)s" - declaration alone is not enough.  Either #include
the header that defines it, or change the argument to be passed
by pointer."""
  return _GenericDiagnoser('IBRA', 'Incomplete By-Reference Argument Type',
                           regex, diagnosis, msg)


def _OverloadedFunctionMatcherDiagnoser(msg):
  """Diagnoses the OFM disease, given the error messages by gcc."""

219
  regex = (_FILE_LINE_RE + r'error: no matching function for '
220
           r'call to \'Truly\(<unresolved overloaded function type>\)')
221
  diagnosis = """
222
223
224
225
226
227
228
229
230
231
232
233
234
235
The argument you gave to Truly() is an overloaded function.  Please tell
gcc which overloaded version you want to use.

For example, if you want to use the version whose signature is
  bool Foo(int n);
you should write
  Truly(static_cast<bool (*)(int n)>(Foo))"""
  return _GenericDiagnoser('OFM', 'Overloaded Function Matcher',
                           regex, diagnosis, msg)


def _OverloadedFunctionActionDiagnoser(msg):
  """Diagnoses the OFA disease, given the error messages by gcc."""

236
  regex = (_FILE_LINE_RE + r'error: no matching function for call to \'Invoke\('
237
           r'<unresolved overloaded function type>')
238
  diagnosis = """
239
240
241
242
243
244
245
246
247
248
249
250
251
252
You are passing an overloaded function to Invoke().  Please tell gcc
which overloaded version you want to use.

For example, if you want to use the version whose signature is
  bool MyFunction(int n, double x);
you should write something like
  Invoke(static_cast<bool (*)(int n, double x)>(MyFunction))"""
  return _GenericDiagnoser('OFA', 'Overloaded Function Action',
                           regex, diagnosis, msg)


def _OverloadedMethodActionDiagnoser1(msg):
  """Diagnoses the OMA disease, given the error messages by gcc."""

253
  regex = (_FILE_LINE_RE + r'error: '
254
255
           r'.*no matching function for call to \'Invoke\(.*, '
           r'unresolved overloaded function type>')
256
  diagnosis = """
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
The second argument you gave to Invoke() is an overloaded method.  Please
tell gcc which overloaded version you want to use.

For example, if you want to use the version whose signature is
  class Foo {
    ...
    bool Bar(int n, double x);
  };
you should write something like
  Invoke(foo, static_cast<bool (Foo::*)(int n, double x)>(&Foo::Bar))"""
  return _GenericDiagnoser('OMA', 'Overloaded Method Action',
                           regex, diagnosis, msg)


def _MockObjectPointerDiagnoser(msg):
  """Diagnoses the MOP disease, given the error messages by gcc."""

274
  regex = (_FILE_LINE_RE + r'error: request for member '
275
276
           r'\'gmock_(?P<method>.+)\' in \'(?P<mock_object>.+)\', '
           r'which is of non-class type \'(.*::)*(?P<class_name>.+)\*\'')
277
  diagnosis = """
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
The first argument to ON_CALL() and EXPECT_CALL() must be a mock *object*,
not a *pointer* to it.  Please write '*(%(mock_object)s)' instead of
'%(mock_object)s' as your first argument.

For example, given the mock class:

  class %(class_name)s : public ... {
    ...
    MOCK_METHOD0(%(method)s, ...);
  };

and the following mock instance:

  %(class_name)s* mock_ptr = ...

you should use the EXPECT_CALL like this:

  EXPECT_CALL(*mock_ptr, %(method)s(...));"""
  return _GenericDiagnoser('MOP', 'Mock Object Pointer',
                           regex, diagnosis, msg)


def _OverloadedMethodActionDiagnoser2(msg):
  """Diagnoses the OMA disease, given the error messages by gcc."""

303
  regex = (_FILE_LINE_RE + r'error: no matching function for '
304
           r'call to \'Invoke\(.+, <unresolved overloaded function type>\)')
305
  diagnosis = """
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
The second argument you gave to Invoke() is an overloaded method.  Please
tell gcc which overloaded version you want to use.

For example, if you want to use the version whose signature is
  class Foo {
    ...
    bool Bar(int n, double x);
  };
you should write something like
  Invoke(foo, static_cast<bool (Foo::*)(int n, double x)>(&Foo::Bar))"""
  return _GenericDiagnoser('OMA', 'Overloaded Method Action',
                           regex, diagnosis, msg)


def _NeedToUseSymbolDiagnoser(msg):
  """Diagnoses the NUS disease, given the error messages by gcc."""

323
  regex = (_FILE_LINE_RE + r'error: \'(?P<symbol>.+)\' '
324
           r'(was not declared in this scope|has not been declared)')
325
  diagnosis = """
326
327
328
329
330
331
332
333
334
335
'%(symbol)s' is defined by Google Mock in the testing namespace.
Did you forget to write
  using testing::%(symbol)s;
?"""
  for m in _FindAllMatches(regex, msg):
    symbol = m.groupdict()['symbol']
    if symbol in _COMMON_GMOCK_SYMBOLS:
      yield ('NUS', 'Need to Use Symbol', diagnosis % m.groupdict())


336
337
338
def _NeedToUseReturnNullDiagnoser(msg):
  """Diagnoses the NRNULL disease, given the error messages by gcc."""

339
  regex = (_FILE_LINE_RE + r'instantiated from here\n'
340
341
           r'.*gmock-actions\.h.*error: invalid conversion from '
           r'\'long int\' to \'(?P<type>.+\*)')
342
  diagnosis = """
343
344
345
346
347
348
349
You are probably calling Return(NULL) and the compiler isn't sure how to turn
NULL into a %(type)s*. Use ReturnNull() instead.
Note: the line number may be off; please fix all instances of Return(NULL)."""
  return _GenericDiagnoser('NRNULL', 'Need to use ReturnNull',
                           regex, diagnosis, msg)


350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
_TTB_DIAGNOSIS = """
In a mock class template, types or typedefs defined in the base class
template are *not* automatically visible.  This is how C++ works.  Before
you can use a type or typedef named %(type)s defined in base class Base<T>, you
need to make it visible.  One way to do it is:

  typedef typename Base<T>::%(type)s %(type)s;"""


def _TypeInTemplatedBaseDiagnoser1(msg):
  """Diagnoses the TTB disease, given the error messages by gcc.

  This version works when the type is used as the mock function's return
  type.
  """

  regex = (r'In member function \'int .*\n' + _FILE_LINE_RE +
           r'error: a function call cannot appear in a constant-expression')
  diagnosis = _TTB_DIAGNOSIS % {'type': 'Foo'}
  return _GenericDiagnoser('TTB', 'Type in Template Base',
                           regex, diagnosis, msg)


def _TypeInTemplatedBaseDiagnoser2(msg):
  """Diagnoses the TTB disease, given the error messages by gcc.

  This version works when the type is used as the mock function's sole
  parameter type.
  """

  regex = (r'In member function \'int .*\n'
           + _FILE_LINE_RE +
           r'error: \'(?P<type>.+)\' was not declared in this scope\n'
           r'.*error: template argument 1 is invalid\n')
  return _GenericDiagnoser('TTB', 'Type in Template Base',
                           regex, _TTB_DIAGNOSIS, msg)


def _TypeInTemplatedBaseDiagnoser3(msg):
  """Diagnoses the TTB disease, given the error messages by gcc.

  This version works when the type is used as a parameter of a mock
  function that has multiple parameters.
  """

  regex = (r'error: expected `;\' before \'::\' token\n'
           + _FILE_LINE_RE +
           r'error: \'(?P<type>.+)\' was not declared in this scope\n'
           r'.*error: template argument 1 is invalid\n'
           r'.*error: \'.+\' was not declared in this scope')
  return _GenericDiagnoser('TTB', 'Type in Template Base',
                           regex, _TTB_DIAGNOSIS, msg)


404
405
406
def _WrongMockMethodMacroDiagnoser(msg):
  """Diagnoses the WMM disease, given the error messages by gcc."""

407
  regex = (_FILE_LINE_RE +
408
409
           r'.*this_method_does_not_take_(?P<wrong_args>\d+)_argument.*\n'
           r'.*\n'
410
411
           r'.*candidates are.*FunctionMocker<[^>]+A(?P<args>\d+)\)>')
  diagnosis = """
412
413
414
You are using MOCK_METHOD%(wrong_args)s to define a mock method that has
%(args)s arguments. Use MOCK_METHOD%(args)s (or MOCK_CONST_METHOD%(args)s,
MOCK_METHOD%(args)s_T, MOCK_CONST_METHOD%(args)s_T as appropriate) instead."""
415
  return _GenericDiagnoser('WMM', 'Wrong MOCK_METHODn Macro',
416
417
418
                           regex, diagnosis, msg)


419
420
421
422
423
424
425
426
427
428
429
430
def _WrongParenPositionDiagnoser(msg):
  """Diagnoses the WPP disease, given the error messages by gcc."""

  regex = (_FILE_LINE_RE +
           r'error:.*testing::internal::MockSpec<.* has no member named \''
           r'(?P<method>\w+)\'')
  diagnosis = """
The closing parenthesis of ON_CALL or EXPECT_CALL should be *before*
".%(method)s".  For example, you should write:
  EXPECT_CALL(my_mock, Foo(_)).%(method)s(...);
instead of:
  EXPECT_CALL(my_mock, Foo(_).%(method)s(...));"""
431
  return _GenericDiagnoser('WPP', 'Wrong Parenthesis Position',
432
433
                           regex, diagnosis, msg)

434

435
436
437
438
439
440
_DIAGNOSERS = [
    _IncompleteByReferenceArgumentDiagnoser,
    _MockObjectPointerDiagnoser,
    _NeedToReturnNothingDiagnoser,
    _NeedToReturnReferenceDiagnoser,
    _NeedToReturnSomethingDiagnoser,
441
    _NeedToUseReturnNullDiagnoser,
442
443
444
445
446
    _NeedToUseSymbolDiagnoser,
    _OverloadedFunctionActionDiagnoser,
    _OverloadedFunctionMatcherDiagnoser,
    _OverloadedMethodActionDiagnoser1,
    _OverloadedMethodActionDiagnoser2,
447
448
449
    _TypeInTemplatedBaseDiagnoser1,
    _TypeInTemplatedBaseDiagnoser2,
    _TypeInTemplatedBaseDiagnoser3,
450
    _WrongMockMethodMacroDiagnoser,
451
    _WrongParenPositionDiagnoser,
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
    ]


def Diagnose(msg):
  """Generates all possible diagnoses given the gcc error message."""

  for diagnoser in _DIAGNOSERS:
    for diagnosis in diagnoser(msg):
      yield '[%s - %s]\n%s' % diagnosis


def main():
  print ('Google Mock Doctor v%s - '
         'diagnoses problems in code using Google Mock.' % _VERSION)

  if sys.stdin.isatty():
    print ('Please copy and paste the compiler errors here.  Press c-D when '
           'you are done:')
  else:
    print 'Waiting for compiler errors on stdin . . .'

  msg = sys.stdin.read().strip()
  diagnoses = list(Diagnose(msg))
  count = len(diagnoses)
  if not count:
    print '\nGcc complained:'
    print '8<------------------------------------------------------------'
    print msg
    print '------------------------------------------------------------>8'
    print """
Uh-oh, I'm not smart enough to figure out what the problem is. :-(
However...
If you send your source code and gcc's error messages to
googlemock@googlegroups.com, you can be helped and I can get smarter --
win-win for us!"""
  else:
    print '------------------------------------------------------------'
    print 'Your code appears to have the following',
    if count > 1:
      print '%s diseases:' % (count,)
    else:
      print 'disease:'
    i = 0
    for d in diagnoses:
      i += 1
      if count > 1:
        print '\n#%s:' % (i,)
      print d
    print """
How did I do?  If you think I'm wrong or unhelpful, please send your
source code and gcc's error messages to googlemock@googlegroups.com.  Then
you can be helped and I can get smarter -- I promise I won't be upset!"""


if __name__ == '__main__':
  main()