You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@mesos.apache.org by be...@apache.org on 2011/06/05 10:45:35 UTC
svn commit: r1132109 [19/26] - in /incubator/mesos/trunk: ./ src/common/
src/configurator/ src/master/ src/sched/ src/slave/ src/tests/
third_party/gmock-1.5.0/ third_party/gmock-1.5.0/build-aux/
third_party/gmock-1.5.0/fused-src/ third_party/gmock-1.5...
Added: incubator/mesos/trunk/third_party/gmock-1.5.0/scripts/generator/cpp/gmock_class.py
URL: http://svn.apache.org/viewvc/incubator/mesos/trunk/third_party/gmock-1.5.0/scripts/generator/cpp/gmock_class.py?rev=1132109&view=auto
==============================================================================
--- incubator/mesos/trunk/third_party/gmock-1.5.0/scripts/generator/cpp/gmock_class.py (added)
+++ incubator/mesos/trunk/third_party/gmock-1.5.0/scripts/generator/cpp/gmock_class.py Sun Jun 5 08:45:22 2011
@@ -0,0 +1,178 @@
+#!/usr/bin/env python
+#
+# Copyright 2008 Google Inc. All Rights Reserved.
+#
+# 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
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# 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.
+
+"""Generate Google Mock classes from base classes.
+
+This program will read in a C++ source file and output the Google Mock
+classes for the specified classes. If no class is specified, all
+classes in the source file are emitted.
+
+Usage:
+ gmock_class.py header-file.h [ClassName]...
+
+Output is sent to stdout.
+"""
+
+__author__ = 'nnorwitz@google.com (Neal Norwitz)'
+
+
+import os
+import re
+import sets
+import sys
+
+from cpp import ast
+from cpp import utils
+
+_VERSION = (1, 0, 1) # The version of this script.
+# How many spaces to indent. Can set me with the INDENT environment variable.
+_INDENT = 2
+
+
+def _GenerateMethods(output_lines, source, class_node):
+ function_type = ast.FUNCTION_VIRTUAL | ast.FUNCTION_PURE_VIRTUAL
+ ctor_or_dtor = ast.FUNCTION_CTOR | ast.FUNCTION_DTOR
+
+ for node in class_node.body:
+ # We only care about virtual functions.
+ if (isinstance(node, ast.Function) and
+ node.modifiers & function_type and
+ not node.modifiers & ctor_or_dtor):
+ # Pick out all the elements we need from the original function.
+ const = ''
+ if node.modifiers & ast.FUNCTION_CONST:
+ const = 'CONST_'
+ return_type = 'void'
+ if node.return_type:
+ # Add modifiers like 'const'.
+ modifiers = ''
+ if node.return_type.modifiers:
+ modifiers = ' '.join(node.return_type.modifiers) + ' '
+ return_type = modifiers + node.return_type.name
+ if node.return_type.pointer:
+ return_type += '*'
+ if node.return_type.reference:
+ return_type += '&'
+ prefix = 'MOCK_%sMETHOD%d' % (const, len(node.parameters))
+ args = ''
+ if node.parameters:
+ # Get the full text of the parameters from the start
+ # of the first parameter to the end of the last parameter.
+ start = node.parameters[0].start
+ end = node.parameters[-1].end
+ # Remove // comments.
+ args_strings = re.sub(r'//.*', '', source[start:end])
+ # Condense multiple spaces and eliminate newlines putting the
+ # parameters together on a single line. Ensure there is a
+ # space in an argument which is split by a newline without
+ # intervening whitespace, e.g.: int\nBar
+ args = re.sub(' +', ' ', args_strings.replace('\n', ' '))
+
+ # Create the prototype.
+ indent = ' ' * _INDENT
+ line = ('%s%s(%s,\n%s%s(%s));' %
+ (indent, prefix, node.name, indent*3, return_type, args))
+ output_lines.append(line)
+
+
+def _GenerateMocks(filename, source, ast_list, desired_class_names):
+ processed_class_names = sets.Set()
+ lines = []
+ for node in ast_list:
+ if (isinstance(node, ast.Class) and node.body and
+ # desired_class_names being None means that all classes are selected.
+ (not desired_class_names or node.name in desired_class_names)):
+ class_name = node.name
+ processed_class_names.add(class_name)
+ class_node = node
+ # Add namespace before the class.
+ if class_node.namespace:
+ lines.extend(['namespace %s {' % n for n in class_node.namespace]) # }
+ lines.append('')
+
+ # Add the class prolog.
+ lines.append('class Mock%s : public %s {' % (class_name, class_name)) # }
+ lines.append('%spublic:' % (' ' * (_INDENT // 2)))
+
+ # Add all the methods.
+ _GenerateMethods(lines, source, class_node)
+
+ # Close the class.
+ if lines:
+ # If there are no virtual methods, no need for a public label.
+ if len(lines) == 2:
+ del lines[-1]
+
+ # Only close the class if there really is a class.
+ lines.append('};')
+ lines.append('') # Add an extra newline.
+
+ # Close the namespace.
+ if class_node.namespace:
+ for i in range(len(class_node.namespace)-1, -1, -1):
+ lines.append('} // namespace %s' % class_node.namespace[i])
+ lines.append('') # Add an extra newline.
+
+ if desired_class_names:
+ missing_class_name_list = list(desired_class_names - processed_class_names)
+ if missing_class_name_list:
+ missing_class_name_list.sort()
+ sys.stderr.write('Class(es) not found in %s: %s\n' %
+ (filename, ', '.join(missing_class_name_list)))
+ elif not processed_class_names:
+ sys.stderr.write('No class found in %s\n' % filename)
+
+ return lines
+
+
+def main(argv=sys.argv):
+ if len(argv) < 2:
+ sys.stderr.write('Google Mock Class Generator v%s\n\n' %
+ '.'.join(map(str, _VERSION)))
+ sys.stderr.write(__doc__)
+ return 1
+
+ global _INDENT
+ try:
+ _INDENT = int(os.environ['INDENT'])
+ except KeyError:
+ pass
+ except:
+ sys.stderr.write('Unable to use indent of %s\n' % os.environ.get('INDENT'))
+
+ filename = argv[1]
+ desired_class_names = None # None means all classes in the source file.
+ if len(argv) >= 3:
+ desired_class_names = sets.Set(argv[2:])
+ source = utils.ReadFile(filename)
+ if source is None:
+ return 1
+
+ builder = ast.BuilderFromSource(source, filename)
+ try:
+ entire_ast = filter(None, builder.Generate())
+ except KeyboardInterrupt:
+ return
+ except:
+ # An error message was already printed since we couldn't parse.
+ pass
+ else:
+ lines = _GenerateMocks(filename, source, entire_ast, desired_class_names)
+ sys.stdout.write('\n'.join(lines))
+
+
+if __name__ == '__main__':
+ main(sys.argv)
Propchange: incubator/mesos/trunk/third_party/gmock-1.5.0/scripts/generator/cpp/gmock_class.py
------------------------------------------------------------------------------
svn:executable = *
Added: incubator/mesos/trunk/third_party/gmock-1.5.0/scripts/generator/cpp/keywords.py
URL: http://svn.apache.org/viewvc/incubator/mesos/trunk/third_party/gmock-1.5.0/scripts/generator/cpp/keywords.py?rev=1132109&view=auto
==============================================================================
--- incubator/mesos/trunk/third_party/gmock-1.5.0/scripts/generator/cpp/keywords.py (added)
+++ incubator/mesos/trunk/third_party/gmock-1.5.0/scripts/generator/cpp/keywords.py Sun Jun 5 08:45:22 2011
@@ -0,0 +1,59 @@
+#!/usr/bin/env python
+#
+# Copyright 2007 Neal Norwitz
+# Portions Copyright 2007 Google Inc.
+#
+# 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
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# 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.
+
+"""C++ keywords and helper utilities for determining keywords."""
+
+__author__ = 'nnorwitz@google.com (Neal Norwitz)'
+
+
+try:
+ # Python 3.x
+ import builtins
+except ImportError:
+ # Python 2.x
+ import __builtin__ as builtins
+
+
+if not hasattr(builtins, 'set'):
+ # Nominal support for Python 2.3.
+ from sets import Set as set
+
+
+TYPES = set('bool char int long short double float void wchar_t unsigned signed'.split())
+TYPE_MODIFIERS = set('auto register const inline extern static virtual volatile mutable'.split())
+ACCESS = set('public protected private friend'.split())
+
+CASTS = set('static_cast const_cast dynamic_cast reinterpret_cast'.split())
+
+OTHERS = set('true false asm class namespace using explicit this operator sizeof'.split())
+OTHER_TYPES = set('new delete typedef struct union enum typeid typename template'.split())
+
+CONTROL = set('case switch default if else return goto'.split())
+EXCEPTION = set('try catch throw'.split())
+LOOP = set('while do for break continue'.split())
+
+ALL = TYPES | TYPE_MODIFIERS | ACCESS | CASTS | OTHERS | OTHER_TYPES | CONTROL | EXCEPTION | LOOP
+
+
+def IsKeyword(token):
+ return token in ALL
+
+def IsBuiltinType(token):
+ if token in ('virtual', 'inline'):
+ # These only apply to methods, they can't be types by themselves.
+ return False
+ return token in TYPES or token in TYPE_MODIFIERS
Propchange: incubator/mesos/trunk/third_party/gmock-1.5.0/scripts/generator/cpp/keywords.py
------------------------------------------------------------------------------
svn:executable = *
Added: incubator/mesos/trunk/third_party/gmock-1.5.0/scripts/generator/cpp/tokenize.py
URL: http://svn.apache.org/viewvc/incubator/mesos/trunk/third_party/gmock-1.5.0/scripts/generator/cpp/tokenize.py?rev=1132109&view=auto
==============================================================================
--- incubator/mesos/trunk/third_party/gmock-1.5.0/scripts/generator/cpp/tokenize.py (added)
+++ incubator/mesos/trunk/third_party/gmock-1.5.0/scripts/generator/cpp/tokenize.py Sun Jun 5 08:45:22 2011
@@ -0,0 +1,287 @@
+#!/usr/bin/env python
+#
+# Copyright 2007 Neal Norwitz
+# Portions Copyright 2007 Google Inc.
+#
+# 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
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# 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.
+
+"""Tokenize C++ source code."""
+
+__author__ = 'nnorwitz@google.com (Neal Norwitz)'
+
+
+try:
+ # Python 3.x
+ import builtins
+except ImportError:
+ # Python 2.x
+ import __builtin__ as builtins
+
+
+import sys
+
+from cpp import utils
+
+
+if not hasattr(builtins, 'set'):
+ # Nominal support for Python 2.3.
+ from sets import Set as set
+
+
+# Add $ as a valid identifier char since so much code uses it.
+_letters = 'abcdefghijklmnopqrstuvwxyz'
+VALID_IDENTIFIER_CHARS = set(_letters + _letters.upper() + '_0123456789$')
+HEX_DIGITS = set('0123456789abcdefABCDEF')
+INT_OR_FLOAT_DIGITS = set('01234567890eE-+')
+
+
+# C++0x string preffixes.
+_STR_PREFIXES = set(('R', 'u8', 'u8R', 'u', 'uR', 'U', 'UR', 'L', 'LR'))
+
+
+# Token types.
+UNKNOWN = 'UNKNOWN'
+SYNTAX = 'SYNTAX'
+CONSTANT = 'CONSTANT'
+NAME = 'NAME'
+PREPROCESSOR = 'PREPROCESSOR'
+
+# Where the token originated from. This can be used for backtracking.
+# It is always set to WHENCE_STREAM in this code.
+WHENCE_STREAM, WHENCE_QUEUE = range(2)
+
+
+class Token(object):
+ """Data container to represent a C++ token.
+
+ Tokens can be identifiers, syntax char(s), constants, or
+ pre-processor directives.
+
+ start contains the index of the first char of the token in the source
+ end contains the index of the last char of the token in the source
+ """
+
+ def __init__(self, token_type, name, start, end):
+ self.token_type = token_type
+ self.name = name
+ self.start = start
+ self.end = end
+ self.whence = WHENCE_STREAM
+
+ def __str__(self):
+ if not utils.DEBUG:
+ return 'Token(%r)' % self.name
+ return 'Token(%r, %s, %s)' % (self.name, self.start, self.end)
+
+ __repr__ = __str__
+
+
+def _GetString(source, start, i):
+ i = source.find('"', i+1)
+ while source[i-1] == '\\':
+ # Count the trailing backslashes.
+ backslash_count = 1
+ j = i - 2
+ while source[j] == '\\':
+ backslash_count += 1
+ j -= 1
+ # When trailing backslashes are even, they escape each other.
+ if (backslash_count % 2) == 0:
+ break
+ i = source.find('"', i+1)
+ return i + 1
+
+
+def _GetChar(source, start, i):
+ # NOTE(nnorwitz): may not be quite correct, should be good enough.
+ i = source.find("'", i+1)
+ while source[i-1] == '\\':
+ # Need to special case '\\'.
+ if (i - 2) > start and source[i-2] == '\\':
+ break
+ i = source.find("'", i+1)
+ # Try to handle unterminated single quotes (in a #if 0 block).
+ if i < 0:
+ i = start
+ return i + 1
+
+
+def GetTokens(source):
+ """Returns a sequence of Tokens.
+
+ Args:
+ source: string of C++ source code.
+
+ Yields:
+ Token that represents the next token in the source.
+ """
+ # Cache various valid character sets for speed.
+ valid_identifier_chars = VALID_IDENTIFIER_CHARS
+ hex_digits = HEX_DIGITS
+ int_or_float_digits = INT_OR_FLOAT_DIGITS
+ int_or_float_digits2 = int_or_float_digits | set('.')
+
+ # Only ignore errors while in a #if 0 block.
+ ignore_errors = False
+ count_ifs = 0
+
+ i = 0
+ end = len(source)
+ while i < end:
+ # Skip whitespace.
+ while i < end and source[i].isspace():
+ i += 1
+ if i >= end:
+ return
+
+ token_type = UNKNOWN
+ start = i
+ c = source[i]
+ if c.isalpha() or c == '_': # Find a string token.
+ token_type = NAME
+ while source[i] in valid_identifier_chars:
+ i += 1
+ # String and character constants can look like a name if
+ # they are something like L"".
+ if (source[i] == "'" and (i - start) == 1 and
+ source[start:i] in 'uUL'):
+ # u, U, and L are valid C++0x character preffixes.
+ token_type = CONSTANT
+ i = _GetChar(source, start, i)
+ elif source[i] == "'" and source[start:i] in _STR_PREFIXES:
+ token_type = CONSTANT
+ i = _GetString(source, start, i)
+ elif c == '/' and source[i+1] == '/': # Find // comments.
+ i = source.find('\n', i)
+ if i == -1: # Handle EOF.
+ i = end
+ continue
+ elif c == '/' and source[i+1] == '*': # Find /* comments. */
+ i = source.find('*/', i) + 2
+ continue
+ elif c in ':+-<>&|*=': # : or :: (plus other chars).
+ token_type = SYNTAX
+ i += 1
+ new_ch = source[i]
+ if new_ch == c:
+ i += 1
+ elif c == '-' and new_ch == '>':
+ i += 1
+ elif new_ch == '=':
+ i += 1
+ elif c in '()[]{}~!?^%;/.,': # Handle single char tokens.
+ token_type = SYNTAX
+ i += 1
+ if c == '.' and source[i].isdigit():
+ token_type = CONSTANT
+ i += 1
+ while source[i] in int_or_float_digits:
+ i += 1
+ # Handle float suffixes.
+ for suffix in ('l', 'f'):
+ if suffix == source[i:i+1].lower():
+ i += 1
+ break
+ elif c.isdigit(): # Find integer.
+ token_type = CONSTANT
+ if c == '0' and source[i+1] in 'xX':
+ # Handle hex digits.
+ i += 2
+ while source[i] in hex_digits:
+ i += 1
+ else:
+ while source[i] in int_or_float_digits2:
+ i += 1
+ # Handle integer (and float) suffixes.
+ for suffix in ('ull', 'll', 'ul', 'l', 'f', 'u'):
+ size = len(suffix)
+ if suffix == source[i:i+size].lower():
+ i += size
+ break
+ elif c == '"': # Find string.
+ token_type = CONSTANT
+ i = _GetString(source, start, i)
+ elif c == "'": # Find char.
+ token_type = CONSTANT
+ i = _GetChar(source, start, i)
+ elif c == '#': # Find pre-processor command.
+ token_type = PREPROCESSOR
+ got_if = source[i:i+3] == '#if' and source[i+3:i+4].isspace()
+ if got_if:
+ count_ifs += 1
+ elif source[i:i+6] == '#endif':
+ count_ifs -= 1
+ if count_ifs == 0:
+ ignore_errors = False
+
+ # TODO(nnorwitz): handle preprocessor statements (\ continuations).
+ while 1:
+ i1 = source.find('\n', i)
+ i2 = source.find('//', i)
+ i3 = source.find('/*', i)
+ i4 = source.find('"', i)
+ # NOTE(nnorwitz): doesn't handle comments in #define macros.
+ # Get the first important symbol (newline, comment, EOF/end).
+ i = min([x for x in (i1, i2, i3, i4, end) if x != -1])
+
+ # Handle #include "dir//foo.h" properly.
+ if source[i] == '"':
+ i = source.find('"', i+1) + 1
+ assert i > 0
+ continue
+ # Keep going if end of the line and the line ends with \.
+ if not (i == i1 and source[i-1] == '\\'):
+ if got_if:
+ condition = source[start+4:i].lstrip()
+ if (condition.startswith('0') or
+ condition.startswith('(0)')):
+ ignore_errors = True
+ break
+ i += 1
+ elif c == '\\': # Handle \ in code.
+ # This is different from the pre-processor \ handling.
+ i += 1
+ continue
+ elif ignore_errors:
+ # The tokenizer seems to be in pretty good shape. This
+ # raise is conditionally disabled so that bogus code
+ # in an #if 0 block can be handled. Since we will ignore
+ # it anyways, this is probably fine. So disable the
+ # exception and return the bogus char.
+ i += 1
+ else:
+ sys.stderr.write('Got invalid token in %s @ %d token:%s: %r\n' %
+ ('?', i, c, source[i-10:i+10]))
+ raise RuntimeError('unexpected token')
+
+ if i <= 0:
+ print('Invalid index, exiting now.')
+ return
+ yield Token(token_type, source[start:i], start, i)
+
+
+if __name__ == '__main__':
+ def main(argv):
+ """Driver mostly for testing purposes."""
+ for filename in argv[1:]:
+ source = utils.ReadFile(filename)
+ if source is None:
+ continue
+
+ for token in GetTokens(source):
+ print('%-12s: %s' % (token.token_type, token.name))
+ # print('\r%6.2f%%' % (100.0 * index / token.end),)
+ sys.stdout.write('\n')
+
+
+ main(sys.argv)
Propchange: incubator/mesos/trunk/third_party/gmock-1.5.0/scripts/generator/cpp/tokenize.py
------------------------------------------------------------------------------
svn:executable = *
Added: incubator/mesos/trunk/third_party/gmock-1.5.0/scripts/generator/cpp/utils.py
URL: http://svn.apache.org/viewvc/incubator/mesos/trunk/third_party/gmock-1.5.0/scripts/generator/cpp/utils.py?rev=1132109&view=auto
==============================================================================
--- incubator/mesos/trunk/third_party/gmock-1.5.0/scripts/generator/cpp/utils.py (added)
+++ incubator/mesos/trunk/third_party/gmock-1.5.0/scripts/generator/cpp/utils.py Sun Jun 5 08:45:22 2011
@@ -0,0 +1,41 @@
+#!/usr/bin/env python
+#
+# Copyright 2007 Neal Norwitz
+# Portions Copyright 2007 Google Inc.
+#
+# 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
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# 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.
+
+"""Generic utilities for C++ parsing."""
+
+__author__ = 'nnorwitz@google.com (Neal Norwitz)'
+
+
+import sys
+
+
+# Set to True to see the start/end token indices.
+DEBUG = True
+
+
+def ReadFile(filename, print_error=True):
+ """Returns the contents of a file."""
+ try:
+ fp = open(filename)
+ try:
+ return fp.read()
+ finally:
+ fp.close()
+ except IOError:
+ if print_error:
+ print('Error reading %s: %s' % (filename, sys.exc_info()[1]))
+ return None
Propchange: incubator/mesos/trunk/third_party/gmock-1.5.0/scripts/generator/cpp/utils.py
------------------------------------------------------------------------------
svn:executable = *
Added: incubator/mesos/trunk/third_party/gmock-1.5.0/scripts/generator/gmock_gen.py
URL: http://svn.apache.org/viewvc/incubator/mesos/trunk/third_party/gmock-1.5.0/scripts/generator/gmock_gen.py?rev=1132109&view=auto
==============================================================================
--- incubator/mesos/trunk/third_party/gmock-1.5.0/scripts/generator/gmock_gen.py (added)
+++ incubator/mesos/trunk/third_party/gmock-1.5.0/scripts/generator/gmock_gen.py Sun Jun 5 08:45:22 2011
@@ -0,0 +1,31 @@
+#!/usr/bin/env python
+#
+# Copyright 2008 Google Inc. All Rights Reserved.
+#
+# 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
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# 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.
+
+"""Driver for starting up Google Mock class generator."""
+
+__author__ = 'nnorwitz@google.com (Neal Norwitz)'
+
+import os
+import sys
+
+if __name__ == '__main__':
+ # Add the directory of this script to the path so we can import gmock_class.
+ sys.path.append(os.path.dirname(__file__))
+
+ from cpp import gmock_class
+ # Fix the docstring in case they require the usage.
+ gmock_class.__doc__ = gmock_class.__doc__.replace('gmock_class.py', __file__)
+ gmock_class.main()
Propchange: incubator/mesos/trunk/third_party/gmock-1.5.0/scripts/generator/gmock_gen.py
------------------------------------------------------------------------------
svn:executable = *
Copied: incubator/mesos/trunk/third_party/gmock-1.5.0/scripts/gmock-config.in (from r1132108, incubator/mesos/trunk/third_party/gtest-1.5.0/scripts/gtest-config.in)
URL: http://svn.apache.org/viewvc/incubator/mesos/trunk/third_party/gmock-1.5.0/scripts/gmock-config.in?p2=incubator/mesos/trunk/third_party/gmock-1.5.0/scripts/gmock-config.in&p1=incubator/mesos/trunk/third_party/gtest-1.5.0/scripts/gtest-config.in&r1=1132108&r2=1132109&rev=1132109&view=diff
==============================================================================
--- incubator/mesos/trunk/third_party/gtest-1.5.0/scripts/gtest-config.in (original)
+++ incubator/mesos/trunk/third_party/gmock-1.5.0/scripts/gmock-config.in Sun Jun 5 08:45:22 2011
@@ -6,7 +6,7 @@ version="@PACKAGE_VERSION@"
show_usage()
{
- echo "Usage: gtest-config [OPTIONS...]"
+ echo "Usage: gmock-config [OPTIONS...]"
}
show_help()
@@ -14,11 +14,11 @@ show_help()
show_usage
cat <<\EOF
-The `gtest-config' script provides access to the necessary compile and linking
-flags to connect with Google C++ Testing Framework, both in a build prior to
+The `gmock-config' script provides access to the necessary compile and linking
+flags to connect with Google C++ Mocking Framework, both in a build prior to
installation, and on the system proper after installation. The installation
overrides may be issued in combination with any other queries, but will only
-affect installation queries if called on a built but not installed gtest. The
+affect installation queries if called on a built but not installed gmock. The
installation queries may not be issued with any other types of queries, and
only one installation query may be made at a time. The version queries and
compiler flag queries may be combined as desired but not mixed. Different
@@ -28,17 +28,17 @@ versions must be specified as a sequence
Compiler flag queries output the union of the sets of flags when combined.
Examples:
- gtest-config --min-version=1.0 || echo "Insufficient Google Test version."
+ gmock-config --min-version=1.0 || echo "Insufficient Google Mock version."
- g++ $(gtest-config --cppflags --cxxflags) -o foo.o -c foo.cpp
- g++ $(gtest-config --ldflags --libs) -o foo foo.o
+ g++ $(gmock-config --cppflags --cxxflags) -o foo.o -c foo.cpp
+ g++ $(gmock-config --ldflags --libs) -o foo foo.o
- # When using a built but not installed Google Test:
- g++ $(../../my_gtest_build/scripts/gtest-config ...) ...
+ # When using a built but not installed Google Mock:
+ g++ $(../../my_gmock_build/scripts/gmock-config ...) ...
- # When using an installed Google Test, but with installation overrides:
- export GTEST_PREFIX="/opt"
- g++ $(gtest-config --libdir="/opt/lib64" ...) ...
+ # When using an installed Google Mock, but with installation overrides:
+ export GMOCK_PREFIX="/opt"
+ g++ $(gmock-config --libdir="/opt/lib64" ...) ...
Help:
--usage brief usage information
@@ -55,7 +55,7 @@ Compiler flag queries output the union o
--exec-prefix executable installation prefix
--libdir library installation directory
--includedir header file installation directory
- --version the version of the Google Test installation
+ --version the version of the Google Mock installation
Version Queries:
--min-version=VERSION return 0 if the version is at least VERSION
@@ -151,10 +151,10 @@ while test $# -gt 0; do
--help) show_help; exit 0;;
# Installation overrides
- --prefix=*) GTEST_PREFIX=${1#--prefix=};;
- --exec-prefix=*) GTEST_EXEC_PREFIX=${1#--exec-prefix=};;
- --libdir=*) GTEST_LIBDIR=${1#--libdir=};;
- --includedir=*) GTEST_INCLUDEDIR=${1#--includedir=};;
+ --prefix=*) GMOCK_PREFIX=${1#--prefix=};;
+ --exec-prefix=*) GMOCK_EXEC_PREFIX=${1#--exec-prefix=};;
+ --libdir=*) GMOCK_LIBDIR=${1#--libdir=};;
+ --includedir=*) GMOCK_INCLUDEDIR=${1#--includedir=};;
# Installation queries
--prefix|--exec-prefix|--libdir|--includedir|--version)
@@ -193,15 +193,17 @@ done
# These have defaults filled in by the configure script but can also be
# overridden by environment variables or command line parameters.
-prefix="${GTEST_PREFIX:-@prefix@}"
-exec_prefix="${GTEST_EXEC_PREFIX:-@exec_prefix@}"
-libdir="${GTEST_LIBDIR:-@libdir@}"
-includedir="${GTEST_INCLUDEDIR:-@includedir@}"
+prefix="${GMOCK_PREFIX:-@prefix@}"
+exec_prefix="${GMOCK_EXEC_PREFIX:-@exec_prefix@}"
+libdir="${GMOCK_LIBDIR:-@libdir@}"
+includedir="${GMOCK_INCLUDEDIR:-@includedir@}"
# We try and detect if our binary is not located at its installed location. If
# it's not, we provide variables pointing to the source and build tree rather
-# than to the install tree. This allows building against a just-built gtest
-# rather than an installed gtest.
+# than to the install tree. We also locate Google Test using the configured
+# gtest-config script rather than searching the PATH and our bindir for one.
+# This allows building against a just-built gmock rather than an installed
+# gmock.
bindir="@bindir@"
this_relative_bindir=`dirname $0`
this_bindir=`cd ${this_relative_bindir}; pwd -P`
@@ -214,25 +216,52 @@ if test "${this_bindir}" = "${this_bindi
# TODO(chandlerc@google.com): This is a dangerous dependency on libtool, we
# should work to remove it, and/or remove libtool altogether, replacing it
# with direct references to the library and a link path.
- gtest_libs="${build_dir}/lib/libgtest.la @PTHREAD_CFLAGS@ @PTHREAD_LIBS@"
- gtest_ldflags=""
+ gmock_libs="${build_dir}/lib/libgtest.la"
+ gmock_ldflags=""
# We provide hooks to include from either the source or build dir, where the
# build dir is always preferred. This will potentially allow us to write
# build rules for generated headers and have them automatically be preferred
# over provided versions.
- gtest_cppflags="-I${build_dir}/include -I${src_dir}/include"
- gtest_cxxflags="@PTHREAD_CFLAGS@"
+ gmock_cppflags="-I${build_dir}/include -I${src_dir}/include"
+ gmock_cxxflags=""
+
+ # Directly invoke the gtest-config script used during the build process.
+ gtest_config="@GTEST_CONFIG@"
else
- # We're using an installed gtest, although it may be staged under some
+ # We're using an installed gmock, although it may be staged under some
# prefix. Assume (as our own libraries do) that we can resolve the prefix,
# and are present in the dynamic link paths.
- gtest_ldflags="-L${libdir}"
- gtest_libs="-l${name} @PTHREAD_CFLAGS@ @PTHREAD_LIBS@"
- gtest_cppflags="-I${includedir}"
- gtest_cxxflags="@PTHREAD_CFLAGS@"
+ gmock_ldflags="-L${libdir}"
+ gmock_libs="-l${name}"
+ gmock_cppflags="-I${includedir}"
+ gmock_cxxflags=""
+
+ # We also prefer any gtest-config script installed in our prefix. Lacking
+ # one, we look in the PATH for one.
+ gtest_config="${bindir}/gtest-config"
+ if test ! -x "${gtest_config}"; then
+ gtest_config=`which gtest-config`
+ fi
fi
+# Ensure that we have located a Google Test to link against.
+if ! test -x "${gtest_config}"; then
+ echo "Unable to locate Google Test, check your Google Mock configuration" \
+ "and installation" >&2
+ exit 1
+elif ! "${gtest_config}" "--exact-version=@GTEST_VERSION@"; then
+ echo "The Google Test found is not the same version as Google Mock was " \
+ "built against" >&2
+ exit 1
+fi
+
+# Add the necessary Google Test bits into the various flag variables
+gmock_cppflags="${gmock_cppflags} `${gtest_config} --cppflags`"
+gmock_cxxflags="${gmock_cxxflags} `${gtest_config} --cxxflags`"
+gmock_ldflags="${gmock_ldflags} `${gtest_config} --ldflags`"
+gmock_libs="${gmock_libs} `${gtest_config} --libs`"
+
# Do an installation query if requested.
if test -n "$do_query"; then
case $do_query in
@@ -265,10 +294,10 @@ fi
# Do the output in the correct order so that these can be used in-line of
# a compiler invocation.
output=""
-test "$echo_cppflags" = "yes" && output="$output $gtest_cppflags"
-test "$echo_cxxflags" = "yes" && output="$output $gtest_cxxflags"
-test "$echo_ldflags" = "yes" && output="$output $gtest_ldflags"
-test "$echo_libs" = "yes" && output="$output $gtest_libs"
+test "$echo_cppflags" = "yes" && output="$output $gmock_cppflags"
+test "$echo_cxxflags" = "yes" && output="$output $gmock_cxxflags"
+test "$echo_ldflags" = "yes" && output="$output $gmock_ldflags"
+test "$echo_libs" = "yes" && output="$output $gmock_libs"
echo $output
exit 0
Added: incubator/mesos/trunk/third_party/gmock-1.5.0/scripts/gmock_doctor.py
URL: http://svn.apache.org/viewvc/incubator/mesos/trunk/third_party/gmock-1.5.0/scripts/gmock_doctor.py?rev=1132109&view=auto
==============================================================================
--- incubator/mesos/trunk/third_party/gmock-1.5.0/scripts/gmock_doctor.py (added)
+++ incubator/mesos/trunk/third_party/gmock-1.5.0/scripts/gmock_doctor.py Sun Jun 5 08:45:22 2011
@@ -0,0 +1,519 @@
+#!/usr/bin/env python
+#
+# 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
+
+_VERSION = '1.0.3'
+
+_COMMON_GMOCK_SYMBOLS = [
+ # Matchers
+ '_',
+ 'A',
+ 'AddressSatisfies',
+ 'AllOf',
+ 'An',
+ 'AnyOf',
+ 'ContainerEq',
+ 'Contains',
+ 'ContainsRegex',
+ 'DoubleEq',
+ 'ElementsAre',
+ 'ElementsAreArray',
+ 'EndsWith',
+ 'Eq',
+ 'Field',
+ 'FloatEq',
+ 'Ge',
+ 'Gt',
+ 'HasSubstr',
+ 'IsInitializedProto',
+ 'Le',
+ 'Lt',
+ 'MatcherCast',
+ 'Matches',
+ 'MatchesRegex',
+ 'NanSensitiveDoubleEq',
+ 'NanSensitiveFloatEq',
+ 'Ne',
+ 'Not',
+ 'NotNull',
+ 'Pointee',
+ 'Property',
+ 'Ref',
+ 'ResultOf',
+ 'SafeMatcherCast',
+ 'StartsWith',
+ 'StrCaseEq',
+ 'StrCaseNe',
+ 'StrEq',
+ 'StrNe',
+ 'Truly',
+ 'TypedEq',
+ 'Value',
+
+ # Actions
+ 'Assign',
+ 'ByRef',
+ 'DeleteArg',
+ 'DoAll',
+ 'DoDefault',
+ 'IgnoreResult',
+ 'Invoke',
+ 'InvokeArgument',
+ 'InvokeWithoutArgs',
+ 'Return',
+ 'ReturnNew',
+ 'ReturnNull',
+ 'ReturnRef',
+ 'SaveArg',
+ 'SetArgReferee',
+ 'SetArgumentPointee',
+ 'SetArrayArgument',
+ 'SetErrnoAndReturn',
+ 'Throw',
+ 'WithArg',
+ 'WithArgs',
+ 'WithoutArgs',
+
+ # Cardinalities
+ 'AnyNumber',
+ 'AtLeast',
+ 'AtMost',
+ 'Between',
+ 'Exactly',
+
+ # Sequences
+ 'InSequence',
+ 'Sequence',
+
+ # Misc
+ 'DefaultValue',
+ 'Mock',
+ ]
+
+# Regex for matching source file path and line number in gcc's errors.
+_FILE_LINE_RE = r'(?P<file>.*):(?P<line>\d+):\s+'
+
+
+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).
+ """
+
+ diagnosis = '%(file)s:%(line)s:' + diagnosis
+ 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'
+ + _FILE_LINE_RE + r'instantiated from here\n'
+ r'.*gmock-actions\.h.*error: creating array with negative size')
+ diagnosis = """
+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."""
+
+ regex = (_FILE_LINE_RE +
+ r'(instantiated from here\n.'
+ r'*gmock.*actions\.h.*error: void value not ignored)'
+ r'|(error: control reaches end of non-void function)')
+ diagnosis = """
+You are using an action that returns void, but it needs to return
+*something*. Please tell it *what* to return. Perhaps you can use
+the pattern DoAll(some_action, Return(some_value))?"""
+ return _GenericDiagnoser('NRS', 'Need to Return Something',
+ regex, diagnosis, msg)
+
+
+def _NeedToReturnNothingDiagnoser(msg):
+ """Diagnoses the NRN disease, given the error messages by gcc."""
+
+ regex = (_FILE_LINE_RE + r'instantiated from here\n'
+ r'.*gmock-actions\.h.*error: instantiation of '
+ r'\'testing::internal::ReturnAction<R>::Impl<F>::value_\' '
+ r'as type \'void\'')
+ diagnosis = """
+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."""
+
+ regex = (_FILE_LINE_RE + r'instantiated from here\n'
+ r'.*gmock-printers\.h.*error: invalid application of '
+ r'\'sizeof\' to incomplete type \'(?P<type>.*)\'')
+ diagnosis = """
+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."""
+
+ regex = (_FILE_LINE_RE + r'error: no matching function for '
+ r'call to \'Truly\(<unresolved overloaded function type>\)')
+ diagnosis = """
+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."""
+
+ regex = (_FILE_LINE_RE + r'error: no matching function for call to \'Invoke\('
+ r'<unresolved overloaded function type>')
+ diagnosis = """
+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."""
+
+ regex = (_FILE_LINE_RE + r'error: '
+ r'.*no matching function for call to \'Invoke\(.*, '
+ r'unresolved overloaded function type>')
+ diagnosis = """
+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."""
+
+ regex = (_FILE_LINE_RE + r'error: request for member '
+ r'\'gmock_(?P<method>.+)\' in \'(?P<mock_object>.+)\', '
+ r'which is of non-class type \'(.*::)*(?P<class_name>.+)\*\'')
+ diagnosis = """
+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."""
+
+ regex = (_FILE_LINE_RE + r'error: no matching function for '
+ r'call to \'Invoke\(.+, <unresolved overloaded function type>\)')
+ diagnosis = """
+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."""
+
+ regex = (_FILE_LINE_RE + r'error: \'(?P<symbol>.+)\' '
+ r'(was not declared in this scope|has not been declared)')
+ diagnosis = """
+'%(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())
+
+
+def _NeedToUseReturnNullDiagnoser(msg):
+ """Diagnoses the NRNULL disease, given the error messages by gcc."""
+
+ regex = ('instantiated from \'testing::internal::ReturnAction<R>'
+ '::operator testing::Action<Func>\(\) const.*\n' +
+ _FILE_LINE_RE + r'instantiated from here\n'
+ r'.*error: no matching function for call to \'implicit_cast\('
+ r'long int&\)')
+ diagnosis = """
+You are probably calling Return(NULL) and the compiler isn't sure how to turn
+NULL into the right type. 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)
+
+
+_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.
+ """
+
+ gcc_4_3_1_regex = (
+ r'In member function \'int .*\n' + _FILE_LINE_RE +
+ r'error: a function call cannot appear in a constant-expression')
+ gcc_4_4_0_regex = (
+ r'error: a function call cannot appear in a constant-expression'
+ + _FILE_LINE_RE + r'error: template argument 1 is invalid\n')
+ diagnosis = _TTB_DIAGNOSIS % {'type': 'Foo'}
+ return (list(_GenericDiagnoser('TTB', 'Type in Template Base',
+ gcc_4_3_1_regex, diagnosis, msg)) +
+ list(_GenericDiagnoser('TTB', 'Type in Template Base',
+ gcc_4_4_0_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 = (_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)
+
+
+def _WrongMockMethodMacroDiagnoser(msg):
+ """Diagnoses the WMM disease, given the error messages by gcc."""
+
+ regex = (_FILE_LINE_RE +
+ r'.*this_method_does_not_take_(?P<wrong_args>\d+)_argument.*\n'
+ r'.*\n'
+ r'.*candidates are.*FunctionMocker<[^>]+A(?P<args>\d+)\)>')
+ diagnosis = """
+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."""
+ return _GenericDiagnoser('WMM', 'Wrong MOCK_METHODn Macro',
+ regex, diagnosis, msg)
+
+
+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(...));"""
+ return _GenericDiagnoser('WPP', 'Wrong Parenthesis Position',
+ regex, diagnosis, msg)
+
+
+_DIAGNOSERS = [
+ _IncompleteByReferenceArgumentDiagnoser,
+ _MockObjectPointerDiagnoser,
+ _NeedToReturnNothingDiagnoser,
+ _NeedToReturnReferenceDiagnoser,
+ _NeedToReturnSomethingDiagnoser,
+ _NeedToUseReturnNullDiagnoser,
+ _NeedToUseSymbolDiagnoser,
+ _OverloadedFunctionActionDiagnoser,
+ _OverloadedFunctionMatcherDiagnoser,
+ _OverloadedMethodActionDiagnoser1,
+ _OverloadedMethodActionDiagnoser2,
+ _TypeInTemplatedBaseDiagnoser1,
+ _TypeInTemplatedBaseDiagnoser2,
+ _TypeInTemplatedBaseDiagnoser3,
+ _WrongMockMethodMacroDiagnoser,
+ _WrongParenPositionDiagnoser,
+ ]
+
+
+def Diagnose(msg):
+ """Generates all possible diagnoses given the gcc error message."""
+
+ diagnoses = []
+ for diagnoser in _DIAGNOSERS:
+ for diag in diagnoser(msg):
+ diagnosis = '[%s - %s]\n%s' % diag
+ if not diagnosis in diagnoses:
+ diagnoses.append(diagnosis)
+ return diagnoses
+
+
+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 = 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()
Propchange: incubator/mesos/trunk/third_party/gmock-1.5.0/scripts/gmock_doctor.py
------------------------------------------------------------------------------
svn:executable = *
Copied: incubator/mesos/trunk/third_party/gmock-1.5.0/src/gmock-all.cc (from r1132108, incubator/mesos/trunk/third_party/gtest-1.5.0/test/gtest_uninitialized_test_.cc)
URL: http://svn.apache.org/viewvc/incubator/mesos/trunk/third_party/gmock-1.5.0/src/gmock-all.cc?p2=incubator/mesos/trunk/third_party/gmock-1.5.0/src/gmock-all.cc&p1=incubator/mesos/trunk/third_party/gtest-1.5.0/test/gtest_uninitialized_test_.cc&r1=1132108&r2=1132109&rev=1132109&view=diff
==============================================================================
--- incubator/mesos/trunk/third_party/gtest-1.5.0/test/gtest_uninitialized_test_.cc (original)
+++ incubator/mesos/trunk/third_party/gmock-1.5.0/src/gmock-all.cc Sun Jun 5 08:45:22 2011
@@ -28,16 +28,21 @@
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Author: wan@google.com (Zhanyong Wan)
+//
+// Google C++ Mocking Framework (Google Mock)
+//
+// This file #includes all Google Mock implementation .cc files. The
+// purpose is to allow a user to build Google Mock by compiling this
+// file alone.
-#include <gtest/gtest.h>
-
-TEST(DummyTest, Dummy) {
- // This test doesn't verify anything. We just need it to create a
- // realistic stage for testing the behavior of Google Test when
- // RUN_ALL_TESTS() is called without testing::InitGoogleTest() being
- // called first.
-}
+// This line ensures that gmock.h can be compiled on its own, even
+// when it's fused.
+#include <gmock/gmock.h>
-int main() {
- return RUN_ALL_TESTS();
-}
+// The following lines pull in the real gmock *.cc files.
+#include "src/gmock-cardinalities.cc"
+#include "src/gmock-internal-utils.cc"
+#include "src/gmock-matchers.cc"
+#include "src/gmock-printers.cc"
+#include "src/gmock-spec-builders.cc"
+#include "src/gmock.cc"
Added: incubator/mesos/trunk/third_party/gmock-1.5.0/src/gmock-cardinalities.cc
URL: http://svn.apache.org/viewvc/incubator/mesos/trunk/third_party/gmock-1.5.0/src/gmock-cardinalities.cc?rev=1132109&view=auto
==============================================================================
--- incubator/mesos/trunk/third_party/gmock-1.5.0/src/gmock-cardinalities.cc (added)
+++ incubator/mesos/trunk/third_party/gmock-1.5.0/src/gmock-cardinalities.cc Sun Jun 5 08:45:22 2011
@@ -0,0 +1,155 @@
+// 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 implements cardinalities.
+
+#include <gmock/gmock-cardinalities.h>
+
+#include <limits.h>
+#include <ostream> // NOLINT
+#include <sstream>
+#include <string>
+#include <gmock/internal/gmock-internal-utils.h>
+#include <gtest/gtest.h>
+
+namespace testing {
+
+namespace {
+
+// Implements the Between(m, n) cardinality.
+class BetweenCardinalityImpl : public CardinalityInterface {
+ public:
+ BetweenCardinalityImpl(int min, int max)
+ : min_(min >= 0 ? min : 0),
+ max_(max >= min_ ? max : min_) {
+ std::stringstream ss;
+ if (min < 0) {
+ ss << "The invocation lower bound must be >= 0, "
+ << "but is actually " << min << ".";
+ internal::Expect(false, __FILE__, __LINE__, ss.str());
+ } else if (max < 0) {
+ ss << "The invocation upper bound must be >= 0, "
+ << "but is actually " << max << ".";
+ internal::Expect(false, __FILE__, __LINE__, ss.str());
+ } else if (min > max) {
+ ss << "The invocation upper bound (" << max
+ << ") must be >= the invocation lower bound (" << min
+ << ").";
+ internal::Expect(false, __FILE__, __LINE__, ss.str());
+ }
+ }
+
+ // Conservative estimate on the lower/upper bound of the number of
+ // calls allowed.
+ virtual int ConservativeLowerBound() const { return min_; }
+ virtual int ConservativeUpperBound() const { return max_; }
+
+ virtual bool IsSatisfiedByCallCount(int call_count) const {
+ return min_ <= call_count && call_count <= max_ ;
+ }
+
+ virtual bool IsSaturatedByCallCount(int call_count) const {
+ return call_count >= max_;
+ }
+
+ virtual void DescribeTo(::std::ostream* os) const;
+ private:
+ const int min_;
+ const int max_;
+
+ GTEST_DISALLOW_COPY_AND_ASSIGN_(BetweenCardinalityImpl);
+};
+
+// Formats "n times" in a human-friendly way.
+inline internal::string FormatTimes(int n) {
+ if (n == 1) {
+ return "once";
+ } else if (n == 2) {
+ return "twice";
+ } else {
+ std::stringstream ss;
+ ss << n << " times";
+ return ss.str();
+ }
+}
+
+// Describes the Between(m, n) cardinality in human-friendly text.
+void BetweenCardinalityImpl::DescribeTo(::std::ostream* os) const {
+ if (min_ == 0) {
+ if (max_ == 0) {
+ *os << "never called";
+ } else if (max_ == INT_MAX) {
+ *os << "called any number of times";
+ } else {
+ *os << "called at most " << FormatTimes(max_);
+ }
+ } else if (min_ == max_) {
+ *os << "called " << FormatTimes(min_);
+ } else if (max_ == INT_MAX) {
+ *os << "called at least " << FormatTimes(min_);
+ } else {
+ // 0 < min_ < max_ < INT_MAX
+ *os << "called between " << min_ << " and " << max_ << " times";
+ }
+}
+
+} // Unnamed namespace
+
+// Describes the given call count to an ostream.
+void Cardinality::DescribeActualCallCountTo(int actual_call_count,
+ ::std::ostream* os) {
+ if (actual_call_count > 0) {
+ *os << "called " << FormatTimes(actual_call_count);
+ } else {
+ *os << "never called";
+ }
+}
+
+// Creates a cardinality that allows at least n calls.
+Cardinality AtLeast(int n) { return Between(n, INT_MAX); }
+
+// Creates a cardinality that allows at most n calls.
+Cardinality AtMost(int n) { return Between(0, n); }
+
+// Creates a cardinality that allows any number of calls.
+Cardinality AnyNumber() { return AtLeast(0); }
+
+// Creates a cardinality that allows between min and max calls.
+Cardinality Between(int min, int max) {
+ return Cardinality(new BetweenCardinalityImpl(min, max));
+}
+
+// Creates a cardinality that allows exactly n calls.
+Cardinality Exactly(int n) { return Between(n, n); }
+
+} // namespace testing
Added: incubator/mesos/trunk/third_party/gmock-1.5.0/src/gmock-internal-utils.cc
URL: http://svn.apache.org/viewvc/incubator/mesos/trunk/third_party/gmock-1.5.0/src/gmock-internal-utils.cc?rev=1132109&view=auto
==============================================================================
--- incubator/mesos/trunk/third_party/gmock-1.5.0/src/gmock-internal-utils.cc (added)
+++ incubator/mesos/trunk/third_party/gmock-1.5.0/src/gmock-internal-utils.cc Sun Jun 5 08:45:22 2011
@@ -0,0 +1,173 @@
+// 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 defines some utilities useful for implementing Google
+// Mock. They are subject to change without notice, so please DO NOT
+// USE THEM IN USER CODE.
+
+#include <gmock/internal/gmock-internal-utils.h>
+
+#include <ctype.h>
+#include <ostream> // NOLINT
+#include <string>
+#include <gmock/gmock.h>
+#include <gmock/internal/gmock-port.h>
+#include <gtest/gtest.h>
+
+namespace testing {
+namespace internal {
+
+// Converts an identifier name to a space-separated list of lower-case
+// words. Each maximum substring of the form [A-Za-z][a-z]*|\d+ is
+// treated as one word. For example, both "FooBar123" and
+// "foo_bar_123" are converted to "foo bar 123".
+string ConvertIdentifierNameToWords(const char* id_name) {
+ string result;
+ char prev_char = '\0';
+ for (const char* p = id_name; *p != '\0'; prev_char = *(p++)) {
+ // We don't care about the current locale as the input is
+ // guaranteed to be a valid C++ identifier name.
+ const bool starts_new_word = isupper(*p) ||
+ (!isalpha(prev_char) && islower(*p)) ||
+ (!isdigit(prev_char) && isdigit(*p));
+
+ if (isalnum(*p)) {
+ if (starts_new_word && result != "")
+ result += ' ';
+ result += static_cast<char>(tolower(*p));
+ }
+ }
+ return result;
+}
+
+// This class reports Google Mock failures as Google Test failures. A
+// user can define another class in a similar fashion if he intends to
+// use Google Mock with a testing framework other than Google Test.
+class GoogleTestFailureReporter : public FailureReporterInterface {
+ public:
+ virtual void ReportFailure(FailureType type, const char* file, int line,
+ const string& message) {
+ AssertHelper(type == FATAL ?
+ TestPartResult::kFatalFailure :
+ TestPartResult::kNonFatalFailure,
+ file,
+ line,
+ message.c_str()) = Message();
+ if (type == FATAL) {
+ posix::Abort();
+ }
+ }
+};
+
+// Returns the global failure reporter. Will create a
+// GoogleTestFailureReporter and return it the first time called.
+FailureReporterInterface* GetFailureReporter() {
+ // Points to the global failure reporter used by Google Mock. gcc
+ // guarantees that the following use of failure_reporter is
+ // thread-safe. We may need to add additional synchronization to
+ // protect failure_reporter if we port Google Mock to other
+ // compilers.
+ static FailureReporterInterface* const failure_reporter =
+ new GoogleTestFailureReporter();
+ return failure_reporter;
+}
+
+// Protects global resources (stdout in particular) used by Log().
+static GTEST_DEFINE_STATIC_MUTEX_(g_log_mutex);
+
+// Returns true iff a log with the given severity is visible according
+// to the --gmock_verbose flag.
+bool LogIsVisible(LogSeverity severity) {
+ if (GMOCK_FLAG(verbose) == kInfoVerbosity) {
+ // Always show the log if --gmock_verbose=info.
+ return true;
+ } else if (GMOCK_FLAG(verbose) == kErrorVerbosity) {
+ // Always hide it if --gmock_verbose=error.
+ return false;
+ } else {
+ // If --gmock_verbose is neither "info" nor "error", we treat it
+ // as "warning" (its default value).
+ return severity == WARNING;
+ }
+}
+
+// Prints the given message to stdout iff 'severity' >= the level
+// specified by the --gmock_verbose flag. If stack_frames_to_skip >=
+// 0, also prints the stack trace excluding the top
+// stack_frames_to_skip frames. In opt mode, any positive
+// stack_frames_to_skip is treated as 0, since we don't know which
+// function calls will be inlined by the compiler and need to be
+// conservative.
+void Log(LogSeverity severity, const string& message,
+ int stack_frames_to_skip) {
+ if (!LogIsVisible(severity))
+ return;
+
+ // Ensures that logs from different threads don't interleave.
+ MutexLock l(&g_log_mutex);
+
+ // "using ::std::cout;" doesn't work with Symbian's STLport, where cout is a
+ // macro.
+
+ if (severity == WARNING) {
+ // Prints a GMOCK WARNING marker to make the warnings easily searchable.
+ std::cout << "\nGMOCK WARNING:";
+ }
+ // Pre-pends a new-line to message if it doesn't start with one.
+ if (message.empty() || message[0] != '\n') {
+ std::cout << "\n";
+ }
+ std::cout << message;
+ if (stack_frames_to_skip >= 0) {
+#ifdef NDEBUG
+ // In opt mode, we have to be conservative and skip no stack frame.
+ const int actual_to_skip = 0;
+#else
+ // In dbg mode, we can do what the caller tell us to do (plus one
+ // for skipping this function's stack frame).
+ const int actual_to_skip = stack_frames_to_skip + 1;
+#endif // NDEBUG
+
+ // Appends a new-line to message if it doesn't end with one.
+ if (!message.empty() && *message.rbegin() != '\n') {
+ std::cout << "\n";
+ }
+ std::cout << "Stack trace:\n"
+ << ::testing::internal::GetCurrentOsStackTraceExceptTop(
+ ::testing::UnitTest::GetInstance(), actual_to_skip);
+ }
+ std::cout << ::std::flush;
+}
+
+} // namespace internal
+} // namespace testing
Added: incubator/mesos/trunk/third_party/gmock-1.5.0/src/gmock-matchers.cc
URL: http://svn.apache.org/viewvc/incubator/mesos/trunk/third_party/gmock-1.5.0/src/gmock-matchers.cc?rev=1132109&view=auto
==============================================================================
--- incubator/mesos/trunk/third_party/gmock-1.5.0/src/gmock-matchers.cc (added)
+++ incubator/mesos/trunk/third_party/gmock-1.5.0/src/gmock-matchers.cc Sun Jun 5 08:45:22 2011
@@ -0,0 +1,190 @@
+// 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 implements Matcher<const string&>, Matcher<string>, and
+// utilities for defining matchers.
+
+#include <gmock/gmock-matchers.h>
+#include <gmock/gmock-generated-matchers.h>
+
+#include <string.h>
+#include <sstream>
+#include <string>
+
+namespace testing {
+
+// Constructs a matcher that matches a const string& whose value is
+// equal to s.
+Matcher<const internal::string&>::Matcher(const internal::string& s) {
+ *this = Eq(s);
+}
+
+// Constructs a matcher that matches a const string& whose value is
+// equal to s.
+Matcher<const internal::string&>::Matcher(const char* s) {
+ *this = Eq(internal::string(s));
+}
+
+// Constructs a matcher that matches a string whose value is equal to s.
+Matcher<internal::string>::Matcher(const internal::string& s) { *this = Eq(s); }
+
+// Constructs a matcher that matches a string whose value is equal to s.
+Matcher<internal::string>::Matcher(const char* s) {
+ *this = Eq(internal::string(s));
+}
+
+namespace internal {
+
+// Utilities for validating and formatting description strings in the
+// MATCHER*() macros.
+
+// Returns the 0-based index of the given parameter in the
+// NULL-terminated parameter array; if the parameter is "*", returns
+// kTupleInterpolation; if it's not found in the list, returns
+// kInvalidInterpolation.
+int GetParamIndex(const char* param_names[], const string& param_name) {
+ if (param_name == "*")
+ return kTupleInterpolation;
+
+ for (int i = 0; param_names[i] != NULL; i++) {
+ if (param_name == param_names[i])
+ return i;
+ }
+ return kInvalidInterpolation;
+}
+
+// Helper function used by ValidateMatcherDescription() to format
+// error messages.
+string FormatMatcherDescriptionSyntaxError(const char* description,
+ const char* error_pos) {
+ ::std::stringstream ss;
+ ss << "Syntax error at index " << (error_pos - description)
+ << " in matcher description \"" << description << "\": ";
+ return ss.str();
+}
+
+// Parses a matcher description string and returns a vector of
+// interpolations that appear in the string; generates non-fatal
+// failures iff 'description' is an invalid matcher description.
+// 'param_names' is a NULL-terminated array of parameter names in the
+// order they appear in the MATCHER_P*() parameter list.
+Interpolations ValidateMatcherDescription(
+ const char* param_names[], const char* description) {
+ Interpolations interps;
+ for (const char* p = description; *p != '\0';) {
+ if (SkipPrefix("%%", &p)) {
+ interps.push_back(Interpolation(p - 2, p, kPercentInterpolation));
+ } else if (SkipPrefix("%(", &p)) {
+ const char* const q = strstr(p, ")s");
+ if (q == NULL) {
+ // TODO(wan@google.com): change the source file location in
+ // the failure to point to where the MATCHER*() macro is used.
+ ADD_FAILURE() << FormatMatcherDescriptionSyntaxError(description, p - 2)
+ << "an interpolation must end with \")s\", "
+ << "but \"" << (p - 2) << "\" does not.";
+ } else {
+ const string param_name(p, q);
+ const int param_index = GetParamIndex(param_names, param_name);
+ if (param_index == kInvalidInterpolation) {
+ ADD_FAILURE() << FormatMatcherDescriptionSyntaxError(description, p)
+ << "\"" << param_name
+ << "\" is an invalid parameter name.";
+ } else {
+ interps.push_back(Interpolation(p - 2, q + 2, param_index));
+ p = q + 2;
+ }
+ }
+ } else {
+ EXPECT_NE(*p, '%') << FormatMatcherDescriptionSyntaxError(description, p)
+ << "use \"%%\" instead of \"%\" to print \"%\".";
+ ++p;
+ }
+ }
+ return interps;
+}
+
+// Joins a vector of strings as if they are fields of a tuple; returns
+// the joined string.
+string JoinAsTuple(const Strings& fields) {
+ switch (fields.size()) {
+ case 0:
+ return "";
+ case 1:
+ return fields[0];
+ default:
+ string result = "(" + fields[0];
+ for (size_t i = 1; i < fields.size(); i++) {
+ result += ", ";
+ result += fields[i];
+ }
+ result += ")";
+ return result;
+ }
+}
+
+// Returns the actual matcher description, given the matcher name,
+// user-supplied description template string, interpolations in the
+// string, and the printed values of the matcher parameters.
+string FormatMatcherDescription(
+ const char* matcher_name, const char* description,
+ const Interpolations& interp, const Strings& param_values) {
+ string result;
+ if (*description == '\0') {
+ // When the user supplies an empty description, we calculate one
+ // from the matcher name.
+ result = ConvertIdentifierNameToWords(matcher_name);
+ if (param_values.size() >= 1)
+ result += " " + JoinAsTuple(param_values);
+ } else {
+ // The end position of the last interpolation.
+ const char* last_interp_end = description;
+ for (size_t i = 0; i < interp.size(); i++) {
+ result.append(last_interp_end, interp[i].start_pos);
+ const int param_index = interp[i].param_index;
+ if (param_index == kTupleInterpolation) {
+ result += JoinAsTuple(param_values);
+ } else if (param_index == kPercentInterpolation) {
+ result += '%';
+ } else if (param_index != kInvalidInterpolation) {
+ result += param_values[param_index];
+ }
+ last_interp_end = interp[i].end_pos;
+ }
+ result += last_interp_end;
+ }
+
+ return result;
+}
+
+} // namespace internal
+} // namespace testing
Added: incubator/mesos/trunk/third_party/gmock-1.5.0/src/gmock-printers.cc
URL: http://svn.apache.org/viewvc/incubator/mesos/trunk/third_party/gmock-1.5.0/src/gmock-printers.cc?rev=1132109&view=auto
==============================================================================
--- incubator/mesos/trunk/third_party/gmock-1.5.0/src/gmock-printers.cc (added)
+++ incubator/mesos/trunk/third_party/gmock-1.5.0/src/gmock-printers.cc Sun Jun 5 08:45:22 2011
@@ -0,0 +1,318 @@
+// 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 implements a universal value printer that can print a
+// value of any type T:
+//
+// void ::testing::internal::UniversalPrinter<T>::Print(value, ostream_ptr);
+//
+// It uses the << operator when possible, and prints the bytes in the
+// object otherwise. A user can override its behavior for a class
+// type Foo by defining either operator<<(::std::ostream&, const Foo&)
+// or void PrintTo(const Foo&, ::std::ostream*) in the namespace that
+// defines Foo.
+
+#include <gmock/gmock-printers.h>
+#include <ctype.h>
+#include <stdio.h>
+#include <ostream> // NOLINT
+#include <string>
+#include <gmock/internal/gmock-port.h>
+
+namespace testing {
+
+namespace {
+
+using ::std::ostream;
+
+#if GTEST_OS_WINDOWS_MOBILE // Windows CE does not define _snprintf_s.
+#define snprintf _snprintf
+#elif _MSC_VER >= 1400 // VC 8.0 and later deprecate snprintf and _snprintf.
+#define snprintf _snprintf_s
+#elif _MSC_VER
+#define snprintf _snprintf
+#endif // GTEST_OS_WINDOWS_MOBILE
+
+// Prints a segment of bytes in the given object.
+void PrintByteSegmentInObjectTo(const unsigned char* obj_bytes, size_t start,
+ size_t count, ostream* os) {
+ char text[5] = "";
+ for (size_t i = 0; i != count; i++) {
+ const size_t j = start + i;
+ if (i != 0) {
+ // Organizes the bytes into groups of 2 for easy parsing by
+ // human.
+ if ((j % 2) == 0) {
+ *os << " ";
+ }
+ }
+ snprintf(text, sizeof(text), "%02X", obj_bytes[j]);
+ *os << text;
+ }
+}
+
+// Prints the bytes in the given value to the given ostream.
+void PrintBytesInObjectToImpl(const unsigned char* obj_bytes, size_t count,
+ ostream* os) {
+ // Tells the user how big the object is.
+ *os << count << "-byte object <";
+
+ const size_t kThreshold = 132;
+ const size_t kChunkSize = 64;
+ // If the object size is bigger than kThreshold, we'll have to omit
+ // some details by printing only the first and the last kChunkSize
+ // bytes.
+ // TODO(wan): let the user control the threshold using a flag.
+ if (count < kThreshold) {
+ PrintByteSegmentInObjectTo(obj_bytes, 0, count, os);
+ } else {
+ PrintByteSegmentInObjectTo(obj_bytes, 0, kChunkSize, os);
+ *os << " ... ";
+ // Rounds up to 2-byte boundary.
+ const size_t resume_pos = (count - kChunkSize + 1)/2*2;
+ PrintByteSegmentInObjectTo(obj_bytes, resume_pos, count - resume_pos, os);
+ }
+ *os << ">";
+}
+
+} // namespace
+
+namespace internal2 {
+
+// Delegates to PrintBytesInObjectToImpl() to print the bytes in the
+// given object. The delegation simplifies the implementation, which
+// uses the << operator and thus is easier done outside of the
+// ::testing::internal namespace, which contains a << operator that
+// sometimes conflicts with the one in STL.
+void PrintBytesInObjectTo(const unsigned char* obj_bytes, size_t count,
+ ostream* os) {
+ PrintBytesInObjectToImpl(obj_bytes, count, os);
+}
+
+} // namespace internal2
+
+namespace internal {
+
+// Prints a wide char as a char literal without the quotes, escaping it
+// when necessary.
+static void PrintAsWideCharLiteralTo(wchar_t c, ostream* os) {
+ switch (c) {
+ case L'\0':
+ *os << "\\0";
+ break;
+ case L'\'':
+ *os << "\\'";
+ break;
+ case L'\?':
+ *os << "\\?";
+ break;
+ case L'\\':
+ *os << "\\\\";
+ break;
+ case L'\a':
+ *os << "\\a";
+ break;
+ case L'\b':
+ *os << "\\b";
+ break;
+ case L'\f':
+ *os << "\\f";
+ break;
+ case L'\n':
+ *os << "\\n";
+ break;
+ case L'\r':
+ *os << "\\r";
+ break;
+ case L'\t':
+ *os << "\\t";
+ break;
+ case L'\v':
+ *os << "\\v";
+ break;
+ default:
+ // Checks whether c is printable or not. Printable characters are in
+ // the range [0x20,0x7E].
+ // We test the value of c directly instead of calling isprint(), as
+ // isprint() is buggy on Windows mobile.
+ if (0x20 <= c && c <= 0x7E) {
+ *os << static_cast<char>(c);
+ } else {
+ // Buffer size enough for the maximum number of digits and \0.
+ char text[2 * sizeof(unsigned long) + 1] = "";
+ snprintf(text, sizeof(text), "%lX", static_cast<unsigned long>(c));
+ *os << "\\x" << text;
+ }
+ }
+}
+
+// Prints a char as if it's part of a string literal, escaping it when
+// necessary.
+static void PrintAsWideStringLiteralTo(wchar_t c, ostream* os) {
+ switch (c) {
+ case L'\'':
+ *os << "'";
+ break;
+ case L'"':
+ *os << "\\\"";
+ break;
+ default:
+ PrintAsWideCharLiteralTo(c, os);
+ }
+}
+
+// Prints a char as a char literal without the quotes, escaping it
+// when necessary.
+static void PrintAsCharLiteralTo(char c, ostream* os) {
+ PrintAsWideCharLiteralTo(static_cast<unsigned char>(c), os);
+}
+
+// Prints a char as if it's part of a string literal, escaping it when
+// necessary.
+static void PrintAsStringLiteralTo(char c, ostream* os) {
+ PrintAsWideStringLiteralTo(static_cast<unsigned char>(c), os);
+}
+
+// Prints a char and its code. The '\0' char is printed as "'\\0'",
+// other unprintable characters are also properly escaped using the
+// standard C++ escape sequence.
+void PrintCharTo(char c, int char_code, ostream* os) {
+ *os << "'";
+ PrintAsCharLiteralTo(c, os);
+ *os << "'";
+ if (c != '\0')
+ *os << " (" << char_code << ")";
+}
+
+// Prints a wchar_t as a symbol if it is printable or as its internal
+// code otherwise and also as its decimal code (except for L'\0').
+// The L'\0' char is printed as "L'\\0'". The decimal code is printed
+// as signed integer when wchar_t is implemented by the compiler
+// as a signed type and is printed as an unsigned integer when wchar_t
+// is implemented as an unsigned type.
+void PrintTo(wchar_t wc, ostream* os) {
+ *os << "L'";
+ PrintAsWideCharLiteralTo(wc, os);
+ *os << "'";
+ if (wc != L'\0') {
+ // Type Int64 is used because it provides more storage than wchar_t thus
+ // when the compiler converts signed or unsigned implementation of wchar_t
+ // to Int64 it fills higher bits with either zeros or the sign bit
+ // passing it to operator <<() as either signed or unsigned integer.
+ *os << " (" << static_cast<Int64>(wc) << ")";
+ }
+}
+
+// Prints the given array of characters to the ostream.
+// The array starts at *begin, the length is len, it may include '\0' characters
+// and may not be null-terminated.
+static void PrintCharsAsStringTo(const char* begin, size_t len, ostream* os) {
+ *os << "\"";
+ for (size_t index = 0; index < len; ++index) {
+ PrintAsStringLiteralTo(begin[index], os);
+ }
+ *os << "\"";
+}
+
+// Prints a (const) char array of 'len' elements, starting at address 'begin'.
+void UniversalPrintArray(const char* begin, size_t len, ostream* os) {
+ PrintCharsAsStringTo(begin, len, os);
+}
+
+// Prints the given array of wide characters to the ostream.
+// The array starts at *begin, the length is len, it may include L'\0'
+// characters and may not be null-terminated.
+static void PrintWideCharsAsStringTo(const wchar_t* begin, size_t len,
+ ostream* os) {
+ *os << "L\"";
+ for (size_t index = 0; index < len; ++index) {
+ PrintAsWideStringLiteralTo(begin[index], os);
+ }
+ *os << "\"";
+}
+
+// Prints the given C string to the ostream.
+void PrintTo(const char* s, ostream* os) {
+ if (s == NULL) {
+ *os << "NULL";
+ } else {
+ *os << implicit_cast<const void*>(s) << " pointing to ";
+ PrintCharsAsStringTo(s, strlen(s), os);
+ }
+}
+
+// MSVC compiler can be configured to define whar_t as a typedef
+// of unsigned short. Defining an overload for const wchar_t* in that case
+// would cause pointers to unsigned shorts be printed as wide strings,
+// possibly accessing more memory than intended and causing invalid
+// memory accesses. MSVC defines _NATIVE_WCHAR_T_DEFINED symbol when
+// wchar_t is implemented as a native type.
+#if !defined(_MSC_VER) || defined(_NATIVE_WCHAR_T_DEFINED)
+// Prints the given wide C string to the ostream.
+void PrintTo(const wchar_t* s, ostream* os) {
+ if (s == NULL) {
+ *os << "NULL";
+ } else {
+ *os << implicit_cast<const void*>(s) << " pointing to ";
+ PrintWideCharsAsStringTo(s, wcslen(s), os);
+ }
+}
+#endif // wchar_t is native
+
+// Prints a ::string object.
+#if GTEST_HAS_GLOBAL_STRING
+void PrintStringTo(const ::string& s, ostream* os) {
+ PrintCharsAsStringTo(s.data(), s.size(), os);
+}
+#endif // GTEST_HAS_GLOBAL_STRING
+
+void PrintStringTo(const ::std::string& s, ostream* os) {
+ PrintCharsAsStringTo(s.data(), s.size(), os);
+}
+
+// Prints a ::wstring object.
+#if GTEST_HAS_GLOBAL_WSTRING
+void PrintWideStringTo(const ::wstring& s, ostream* os) {
+ PrintWideCharsAsStringTo(s.data(), s.size(), os);
+}
+#endif // GTEST_HAS_GLOBAL_WSTRING
+
+#if GTEST_HAS_STD_WSTRING
+void PrintWideStringTo(const ::std::wstring& s, ostream* os) {
+ PrintWideCharsAsStringTo(s.data(), s.size(), os);
+}
+#endif // GTEST_HAS_STD_WSTRING
+
+} // namespace internal
+
+} // namespace testing