Commit 37f32278 by Abseil Team Committed by Gennadiy Civil

Googletest export

Add a matcher `testing::ReturnRoundRobin` which, on each call, returns the next element in the sequence, restarting at the beginning once it has reached the end. PiperOrigin-RevId: 276312136
parent 1110c471
...@@ -503,16 +503,17 @@ which must be a permanent callback. ...@@ -503,16 +503,17 @@ which must be a permanent callback.
#### Returning a Value #### Returning a Value
<!-- mdformat off(no multiline tables) --> <!-- mdformat off(no multiline tables) -->
| | | | | |
| :-------------------------- | :-------------------------------------------- | | :-------------------------------- | :-------------------------------------------- |
| `Return()` | Return from a `void` mock function. | | `Return()` | Return from a `void` mock function. |
| `Return(value)` | Return `value`. If the type of `value` is different to the mock function's return type, `value` is converted to the latter type <i>at the time the expectation is set</i>, not when the action is executed. | | `Return(value)` | Return `value`. If the type of `value` is different to the mock function's return type, `value` is converted to the latter type <i>at the time the expectation is set</i>, not when the action is executed. |
| `ReturnArg<N>()` | Return the `N`-th (0-based) argument. | | `ReturnArg<N>()` | Return the `N`-th (0-based) argument. |
| `ReturnNew<T>(a1, ..., ak)` | Return `new T(a1, ..., ak)`; a different object is created each time. | | `ReturnNew<T>(a1, ..., ak)` | Return `new T(a1, ..., ak)`; a different object is created each time. |
| `ReturnNull()` | Return a null pointer. | | `ReturnNull()` | Return a null pointer. |
| `ReturnPointee(ptr)` | Return the value pointed to by `ptr`. | | `ReturnPointee(ptr)` | Return the value pointed to by `ptr`. |
| `ReturnRef(variable)` | Return a reference to `variable`. | | `ReturnRef(variable)` | Return a reference to `variable`. |
| `ReturnRefOfCopy(value)` | Return a reference to a copy of `value`; the copy lives as long as the action. | | `ReturnRefOfCopy(value)` | Return a reference to a copy of `value`; the copy lives as long as the action. |
| `ReturnRoundRobin({a1, ..., ak})` | Each call will return the next `ai` in the list, starting at the beginning when the end of the list is reached. |
<!-- mdformat on --> <!-- mdformat on -->
#### Side Effects #### Side Effects
......
...@@ -716,6 +716,36 @@ class ReturnRefOfCopyAction { ...@@ -716,6 +716,36 @@ class ReturnRefOfCopyAction {
GTEST_DISALLOW_ASSIGN_(ReturnRefOfCopyAction); GTEST_DISALLOW_ASSIGN_(ReturnRefOfCopyAction);
}; };
// Implements the polymorphic ReturnRoundRobin(v) action, which can be
// used in any function that returns the element_type of v.
template <typename T>
class ReturnRoundRobinAction {
public:
explicit ReturnRoundRobinAction(std::vector<T> values) {
GTEST_CHECK_(!values.empty())
<< "ReturnRoundRobin requires at least one element.";
state_->values = std::move(values);
}
template <typename... Args>
T operator()(Args&&...) const {
return state_->Next();
}
private:
struct State {
T Next() {
T ret_val = values[i++];
if (i == values.size()) i = 0;
return ret_val;
}
std::vector<T> values;
size_t i = 0;
};
std::shared_ptr<State> state_ = std::make_shared<State>();
};
// Implements the polymorphic DoDefault() action. // Implements the polymorphic DoDefault() action.
class DoDefaultAction { class DoDefaultAction {
public: public:
...@@ -1039,6 +1069,23 @@ internal::ByMoveWrapper<R> ByMove(R x) { ...@@ -1039,6 +1069,23 @@ internal::ByMoveWrapper<R> ByMove(R x) {
return internal::ByMoveWrapper<R>(std::move(x)); return internal::ByMoveWrapper<R>(std::move(x));
} }
// Creates an action that returns an element of `vals`. Calling this action will
// repeatedly return the next value from `vals` until it reaches the end and
// will restart from the beginning.
template <typename T>
internal::ReturnRoundRobinAction<T> ReturnRoundRobin(std::vector<T> vals) {
return internal::ReturnRoundRobinAction<T>(std::move(vals));
}
// Creates an action that returns an element of `vals`. Calling this action will
// repeatedly return the next value from `vals` until it reaches the end and
// will restart from the beginning.
template <typename T>
internal::ReturnRoundRobinAction<T> ReturnRoundRobin(
std::initializer_list<T> vals) {
return internal::ReturnRoundRobinAction<T>(std::vector<T>(vals));
}
// Creates an action that does the default action for the give mock function. // Creates an action that does the default action for the give mock function.
inline internal::DoDefaultAction DoDefault() { inline internal::DoDefaultAction DoDefault() {
return internal::DoDefaultAction(); return internal::DoDefaultAction();
......
# Please Note:
Files in this directory are no longer supported by the maintainers. They
represent mosty historical artifacts and supported by the community only. There
is no guarantee whatsoever that these scripts still work.
...@@ -17,10 +17,7 @@ ...@@ -17,10 +17,7 @@
"""Generate an Abstract Syntax Tree (AST) for C++.""" """Generate an Abstract Syntax Tree (AST) for C++."""
__author__ = 'nnorwitz@google.com (Neal Norwitz)' # FIXME:
# TODO:
# * Tokens should never be exported, need to convert to Nodes # * Tokens should never be exported, need to convert to Nodes
# (return types, parameters, etc.) # (return types, parameters, etc.)
# * Handle static class data for templatized classes # * Handle static class data for templatized classes
...@@ -338,7 +335,7 @@ class Class(_GenericDeclaration): ...@@ -338,7 +335,7 @@ class Class(_GenericDeclaration):
# TODO(nnorwitz): handle namespaces, etc. # TODO(nnorwitz): handle namespaces, etc.
if self.bases: if self.bases:
for token_list in self.bases: for token_list in self.bases:
# TODO(nnorwitz): bases are tokens, do name comparison. # TODO(nnorwitz): bases are tokens, do name comparision.
for token in token_list: for token in token_list:
if token.name == node.name: if token.name == node.name:
return True return True
...@@ -381,7 +378,7 @@ class Function(_GenericDeclaration): ...@@ -381,7 +378,7 @@ class Function(_GenericDeclaration):
def Requires(self, node): def Requires(self, node):
if self.parameters: if self.parameters:
# TODO(nnorwitz): parameters are tokens, do name comparison. # TODO(nnorwitz): parameters are tokens, do name comparision.
for p in self.parameters: for p in self.parameters:
if p.name == node.name: if p.name == node.name:
return True return True
...@@ -739,6 +736,14 @@ class AstBuilder(object): ...@@ -739,6 +736,14 @@ class AstBuilder(object):
if token.token_type == tokenize.NAME: if token.token_type == tokenize.NAME:
if (keywords.IsKeyword(token.name) and if (keywords.IsKeyword(token.name) and
not keywords.IsBuiltinType(token.name)): not keywords.IsBuiltinType(token.name)):
if token.name == 'enum':
# Pop the next token and only put it back if it's not
# 'class'. This allows us to support the two-token
# 'enum class' keyword as if it were simply 'enum'.
next = self._GetNextToken()
if next.name != 'class':
self._AddBackToken(next)
method = getattr(self, 'handle_' + token.name) method = getattr(self, 'handle_' + token.name)
return method() return method()
elif token.name == self.in_class_name_only: elif token.name == self.in_class_name_only:
...@@ -754,7 +759,8 @@ class AstBuilder(object): ...@@ -754,7 +759,8 @@ class AstBuilder(object):
# Handle data or function declaration/definition. # Handle data or function declaration/definition.
syntax = tokenize.SYNTAX syntax = tokenize.SYNTAX
temp_tokens, last_token = \ temp_tokens, last_token = \
self._GetVarTokensUpTo(syntax, '(', ';', '{', '[') self._GetVarTokensUpToIgnoringTemplates(syntax,
'(', ';', '{', '[')
temp_tokens.insert(0, token) temp_tokens.insert(0, token)
if last_token.name == '(': if last_token.name == '(':
# If there is an assignment before the paren, # If there is an assignment before the paren,
...@@ -858,7 +864,25 @@ class AstBuilder(object): ...@@ -858,7 +864,25 @@ class AstBuilder(object):
last_token = self._GetNextToken() last_token = self._GetNextToken()
return tokens, last_token return tokens, last_token
# TODO(nnorwitz): remove _IgnoreUpTo() it shouldn't be necessary. # Same as _GetVarTokensUpTo, but skips over '<...>' which could contain an
# expected token.
def _GetVarTokensUpToIgnoringTemplates(self, expected_token_type,
*expected_tokens):
last_token = self._GetNextToken()
tokens = []
nesting = 0
while (nesting > 0 or
last_token.token_type != expected_token_type or
last_token.name not in expected_tokens):
tokens.append(last_token)
last_token = self._GetNextToken()
if last_token.name == '<':
nesting += 1
elif last_token.name == '>':
nesting -= 1
return tokens, last_token
# TODO(nnorwitz): remove _IgnoreUpTo() it shouldn't be necesary.
def _IgnoreUpTo(self, token_type, token): def _IgnoreUpTo(self, token_type, token):
unused_tokens = self._GetTokensUpTo(token_type, token) unused_tokens = self._GetTokensUpTo(token_type, token)
...@@ -1264,9 +1288,6 @@ class AstBuilder(object): ...@@ -1264,9 +1288,6 @@ class AstBuilder(object):
return self._GetNestedType(Union) return self._GetNestedType(Union)
def handle_enum(self): def handle_enum(self):
token = self._GetNextToken()
if not (token.token_type == tokenize.NAME and token.name == 'class'):
self._AddBackToken(token)
return self._GetNestedType(Enum) return self._GetNestedType(Enum)
def handle_auto(self): def handle_auto(self):
...@@ -1298,7 +1319,8 @@ class AstBuilder(object): ...@@ -1298,7 +1319,8 @@ class AstBuilder(object):
if token2.token_type == tokenize.SYNTAX and token2.name == '~': if token2.token_type == tokenize.SYNTAX and token2.name == '~':
return self.GetMethod(FUNCTION_VIRTUAL + FUNCTION_DTOR, None) return self.GetMethod(FUNCTION_VIRTUAL + FUNCTION_DTOR, None)
assert token.token_type == tokenize.NAME or token.name == '::', token assert token.token_type == tokenize.NAME or token.name == '::', token
return_type_and_name = self._GetTokensUpTo(tokenize.SYNTAX, '(') # ) return_type_and_name, _ = self._GetVarTokensUpToIgnoringTemplates(
tokenize.SYNTAX, '(') # )
return_type_and_name.insert(0, token) return_type_and_name.insert(0, token)
if token2 is not token: if token2 is not token:
return_type_and_name.insert(1, token2) return_type_and_name.insert(1, token2)
......
#!/usr/bin/env python #!/usr/bin/env python
# #
# Copyright 2008 Google Inc. All Rights Reserved. # Copyright 2008, Google Inc.
# All rights reserved.
# #
# Licensed under the Apache License, Version 2.0 (the "License"); # Redistribution and use in source and binary forms, with or without
# you may not use this file except in compliance with the License. # modification, are permitted provided that the following conditions are
# You may obtain a copy of the License at # met:
# #
# http://www.apache.org/licenses/LICENSE-2.0 # * 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.
# #
# Unless required by applicable law or agreed to in writing, software # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# distributed under the License is distributed on an "AS IS" BASIS, # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# See the License for the specific language governing permissions and # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# limitations under the License. # 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.
"""Generate Google Mock classes from base classes. """Generate Google Mock classes from base classes.
...@@ -26,9 +41,6 @@ Usage: ...@@ -26,9 +41,6 @@ Usage:
Output is sent to stdout. Output is sent to stdout.
""" """
__author__ = 'nnorwitz@google.com (Neal Norwitz)'
import os import os
import re import re
import sys import sys
...@@ -48,6 +60,50 @@ _VERSION = (1, 0, 1) # The version of this script. ...@@ -48,6 +60,50 @@ _VERSION = (1, 0, 1) # The version of this script.
_INDENT = 2 _INDENT = 2
def _RenderType(ast_type):
"""Renders the potentially recursively templated type into a string.
Args:
ast_type: The AST of the type.
Returns:
Rendered string and a boolean to indicate whether we have multiple args
(which is not handled correctly).
"""
has_multiarg_error = False
# Add modifiers like 'const'.
modifiers = ''
if ast_type.modifiers:
modifiers = ' '.join(ast_type.modifiers) + ' '
return_type = modifiers + ast_type.name
if ast_type.templated_types:
# Collect template args.
template_args = []
for arg in ast_type.templated_types:
rendered_arg, e = _RenderType(arg)
if e: has_multiarg_error = True
template_args.append(rendered_arg)
return_type += '<' + ', '.join(template_args) + '>'
# We are actually not handling multi-template-args correctly. So mark it.
if len(template_args) > 1:
has_multiarg_error = True
if ast_type.pointer:
return_type += '*'
if ast_type.reference:
return_type += '&'
return return_type, has_multiarg_error
def _GetNumParameters(parameters, source):
num_parameters = len(parameters)
if num_parameters == 1:
first_param = parameters[0]
if source[first_param.start:first_param.end].strip() == 'void':
# We must treat T(void) as a function with no parameters.
return 0
return num_parameters
def _GenerateMethods(output_lines, source, class_node): def _GenerateMethods(output_lines, source, class_node):
function_type = (ast.FUNCTION_VIRTUAL | ast.FUNCTION_PURE_VIRTUAL | function_type = (ast.FUNCTION_VIRTUAL | ast.FUNCTION_PURE_VIRTUAL |
ast.FUNCTION_OVERRIDE) ast.FUNCTION_OVERRIDE)
...@@ -63,32 +119,16 @@ def _GenerateMethods(output_lines, source, class_node): ...@@ -63,32 +119,16 @@ def _GenerateMethods(output_lines, source, class_node):
const = '' const = ''
if node.modifiers & ast.FUNCTION_CONST: if node.modifiers & ast.FUNCTION_CONST:
const = 'CONST_' const = 'CONST_'
num_parameters = _GetNumParameters(node.parameters, source)
return_type = 'void' return_type = 'void'
if node.return_type: if node.return_type:
# Add modifiers like 'const'. return_type, has_multiarg_error = _RenderType(node.return_type)
modifiers = '' if has_multiarg_error:
if node.return_type.modifiers: for line in [
modifiers = ' '.join(node.return_type.modifiers) + ' ' '// The following line won\'t really compile, as the return',
return_type = modifiers + node.return_type.name '// type has multiple template arguments. To fix it, use a',
template_args = [arg.name for arg in node.return_type.templated_types] '// typedef for the return type.']:
if template_args: output_lines.append(indent + line)
return_type += '<' + ', '.join(template_args) + '>'
if len(template_args) > 1:
for line in [
'// The following line won\'t really compile, as the return',
'// type has multiple template arguments. To fix it, use a',
'// typedef for the return type.']:
output_lines.append(indent + line)
if node.return_type.pointer:
return_type += '*'
if node.return_type.reference:
return_type += '&'
num_parameters = len(node.parameters)
if len(node.parameters) == 1:
first_param = node.parameters[0]
if source[first_param.start:first_param.end].strip() == 'void':
# We must treat T(void) as a function with no parameters.
num_parameters = 0
tmpl = '' tmpl = ''
if class_node.templated_types: if class_node.templated_types:
tmpl = '_T' tmpl = '_T'
......
#!/usr/bin/env python #!/usr/bin/env python
# #
# Copyright 2009 Neal Norwitz All Rights Reserved. # Copyright 2009, Google Inc.
# Portions Copyright 2009 Google Inc. All Rights Reserved. # All rights reserved.
# #
# Licensed under the Apache License, Version 2.0 (the "License"); # Redistribution and use in source and binary forms, with or without
# you may not use this file except in compliance with the License. # modification, are permitted provided that the following conditions are
# You may obtain a copy of the License at # met:
# #
# http://www.apache.org/licenses/LICENSE-2.0 # * 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.
# #
# Unless required by applicable law or agreed to in writing, software # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# distributed under the License is distributed on an "AS IS" BASIS, # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# See the License for the specific language governing permissions and # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# limitations under the License. # 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.
"""Tests for gmock.scripts.generator.cpp.gmock_class.""" """Tests for gmock.scripts.generator.cpp.gmock_class."""
__author__ = 'nnorwitz@google.com (Neal Norwitz)'
import os import os
import sys import sys
import unittest import unittest
...@@ -444,19 +455,63 @@ void(const FooType& test_arg)); ...@@ -444,19 +455,63 @@ void(const FooType& test_arg));
self.assertEqualIgnoreLeadingWhitespace( self.assertEqualIgnoreLeadingWhitespace(
expected, self.GenerateMocks(source)) expected, self.GenerateMocks(source))
def testEnumClass(self): def testEnumType(self):
source = """ source = """
class Test { class Test {
public: public:
enum class Baz { BAZINGA }; enum Bar {
virtual void Bar(const FooType& test_arg); BAZ, QUX, QUUX, QUUUX
};
virtual void Foo();
}; };
""" """
expected = """\ expected = """\
class MockTest : public Test { class MockTest : public Test {
public: public:
MOCK_METHOD1(Bar, MOCK_METHOD0(Foo,
void(const FooType& test_arg)); void());
};
"""
self.assertEqualIgnoreLeadingWhitespace(
expected, self.GenerateMocks(source))
def testEnumClassType(self):
source = """
class Test {
public:
enum class Bar {
BAZ, QUX, QUUX, QUUUX
};
virtual void Foo();
};
"""
expected = """\
class MockTest : public Test {
public:
MOCK_METHOD0(Foo,
void());
};
"""
self.assertEqualIgnoreLeadingWhitespace(
expected, self.GenerateMocks(source))
def testStdFunction(self):
source = """
class Test {
public:
Test(std::function<int(std::string)> foo) : foo_(foo) {}
virtual std::function<int(std::string)> foo();
private:
std::function<int(std::string)> foo_;
};
"""
expected = """\
class MockTest : public Test {
public:
MOCK_METHOD0(foo,
std::function<int (std::string)>());
}; };
""" """
self.assertEqualIgnoreLeadingWhitespace( self.assertEqualIgnoreLeadingWhitespace(
......
#!/usr/bin/env python #!/usr/bin/env python
# #
# Copyright 2007 Neal Norwitz # Copyright 2007, Google Inc.
# Portions Copyright 2007 Google Inc. # All rights reserved.
# #
# Licensed under the Apache License, Version 2.0 (the "License"); # Redistribution and use in source and binary forms, with or without
# you may not use this file except in compliance with the License. # modification, are permitted provided that the following conditions are
# You may obtain a copy of the License at # met:
# #
# http://www.apache.org/licenses/LICENSE-2.0 # * 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.
# #
# Unless required by applicable law or agreed to in writing, software # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# distributed under the License is distributed on an "AS IS" BASIS, # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# See the License for the specific language governing permissions and # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# limitations under the License. # 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.
"""C++ keywords and helper utilities for determining keywords.""" """C++ keywords and helper utilities for determining keywords."""
__author__ = 'nnorwitz@google.com (Neal Norwitz)'
try: try:
# Python 3.x # Python 3.x
import builtins import builtins
......
#!/usr/bin/env python #!/usr/bin/env python
# #
# Copyright 2007 Neal Norwitz # Copyright 2007, Google Inc.
# Portions Copyright 2007 Google Inc. # All rights reserved.
# #
# Licensed under the Apache License, Version 2.0 (the "License"); # Redistribution and use in source and binary forms, with or without
# you may not use this file except in compliance with the License. # modification, are permitted provided that the following conditions are
# You may obtain a copy of the License at # met:
# #
# http://www.apache.org/licenses/LICENSE-2.0 # * 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.
# #
# Unless required by applicable law or agreed to in writing, software # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# distributed under the License is distributed on an "AS IS" BASIS, # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# See the License for the specific language governing permissions and # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# limitations under the License. # 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.
"""Tokenize C++ source code.""" """Tokenize C++ source code."""
__author__ = 'nnorwitz@google.com (Neal Norwitz)'
try: try:
# Python 3.x # Python 3.x
import builtins import builtins
......
#!/usr/bin/env python #!/usr/bin/env python
# #
# Copyright 2007 Neal Norwitz # Copyright 2007, Google Inc.
# Portions Copyright 2007 Google Inc. # All rights reserved.
# #
# Licensed under the Apache License, Version 2.0 (the "License"); # Redistribution and use in source and binary forms, with or without
# you may not use this file except in compliance with the License. # modification, are permitted provided that the following conditions are
# You may obtain a copy of the License at # met:
# #
# http://www.apache.org/licenses/LICENSE-2.0 # * 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.
# #
# Unless required by applicable law or agreed to in writing, software # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# distributed under the License is distributed on an "AS IS" BASIS, # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# See the License for the specific language governing permissions and # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# limitations under the License. # 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.
"""Generic utilities for C++ parsing.""" """Generic utilities for C++ parsing."""
__author__ = 'nnorwitz@google.com (Neal Norwitz)'
import sys import sys
# Set to True to see the start/end token indices. # Set to True to see the start/end token indices.
DEBUG = True DEBUG = True
......
#!/usr/bin/env python #!/usr/bin/env python
# #
# Copyright 2008 Google Inc. All Rights Reserved. # Copyright 2008, Google Inc.
# All rights reserved.
# #
# Licensed under the Apache License, Version 2.0 (the "License"); # Redistribution and use in source and binary forms, with or without
# you may not use this file except in compliance with the License. # modification, are permitted provided that the following conditions are
# You may obtain a copy of the License at # met:
# #
# http://www.apache.org/licenses/LICENSE-2.0 # * 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.
# #
# Unless required by applicable law or agreed to in writing, software # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# distributed under the License is distributed on an "AS IS" BASIS, # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# See the License for the specific language governing permissions and # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# limitations under the License. # 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.
"""Driver for starting up Google Mock class generator.""" """Driver for starting up Google Mock class generator."""
__author__ = 'nnorwitz@google.com (Neal Norwitz)'
import os import os
import sys import sys
......
#!/usr/bin/env python #!/usr/bin/env python
# #
# Copyright 2007 Google Inc. # Copyright 2009, Google Inc.
# All rights reserved.
# #
# Licensed under the Apache License, Version 2.0 (the "License"); # Redistribution and use in source and binary forms, with or without
# you may not use this file except in compliance with the License. # modification, are permitted provided that the following conditions are
# You may obtain a copy of the License at # met:
# #
# http://www.apache.org/licenses/LICENSE-2.0 # * 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.
# #
# Unless required by applicable law or agreed to in writing, software # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# distributed under the License is distributed on an "AS IS" BASIS, # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# See the License for the specific language governing permissions and # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# limitations under the License. # 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.
"""Tool for uploading diffs from a version control system to the codereview app. """Tool for uploading diffs from a version control system to the codereview app.
......
...@@ -73,6 +73,7 @@ using testing::Return; ...@@ -73,6 +73,7 @@ using testing::Return;
using testing::ReturnNull; using testing::ReturnNull;
using testing::ReturnRef; using testing::ReturnRef;
using testing::ReturnRefOfCopy; using testing::ReturnRefOfCopy;
using testing::ReturnRoundRobin;
using testing::SetArgPointee; using testing::SetArgPointee;
using testing::SetArgumentPointee; using testing::SetArgumentPointee;
using testing::Unused; using testing::Unused;
...@@ -670,6 +671,31 @@ TEST(ReturnRefOfCopyTest, IsCovariant) { ...@@ -670,6 +671,31 @@ TEST(ReturnRefOfCopyTest, IsCovariant) {
EXPECT_NE(&derived, &a.Perform(std::make_tuple())); EXPECT_NE(&derived, &a.Perform(std::make_tuple()));
} }
// Tests that ReturnRoundRobin(v) works with initializer lists
TEST(ReturnRoundRobinTest, WorksForInitList) {
Action<int()> ret = ReturnRoundRobin({1, 2, 3});
EXPECT_EQ(1, ret.Perform(std::make_tuple()));
EXPECT_EQ(2, ret.Perform(std::make_tuple()));
EXPECT_EQ(3, ret.Perform(std::make_tuple()));
EXPECT_EQ(1, ret.Perform(std::make_tuple()));
EXPECT_EQ(2, ret.Perform(std::make_tuple()));
EXPECT_EQ(3, ret.Perform(std::make_tuple()));
}
// Tests that ReturnRoundRobin(v) works with vectors
TEST(ReturnRoundRobinTest, WorksForVector) {
std::vector<double> v = {4.4, 5.5, 6.6};
Action<double()> ret = ReturnRoundRobin(v);
EXPECT_EQ(4.4, ret.Perform(std::make_tuple()));
EXPECT_EQ(5.5, ret.Perform(std::make_tuple()));
EXPECT_EQ(6.6, ret.Perform(std::make_tuple()));
EXPECT_EQ(4.4, ret.Perform(std::make_tuple()));
EXPECT_EQ(5.5, ret.Perform(std::make_tuple()));
EXPECT_EQ(6.6, ret.Perform(std::make_tuple()));
}
// Tests that DoDefault() does the default action for the mock method. // Tests that DoDefault() does the default action for the mock method.
class MockClass { class MockClass {
......
# Please Note:
Files in this directory are no longer supported by the maintainers. They
represent mosty historical artifacts and supported by the community only. There
is no guarantee whatsoever that these scripts still work.
...@@ -111,6 +111,8 @@ def HeaderPreamble(n): ...@@ -111,6 +111,8 @@ def HeaderPreamble(n):
// '%(command)s'. DO NOT EDIT BY HAND! // '%(command)s'. DO NOT EDIT BY HAND!
// //
// Implements a family of generic predicate assertion macros. // Implements a family of generic predicate assertion macros.
// GOOGLETEST_CM0001 DO NOT DELETE
#ifndef GTEST_INCLUDE_GTEST_GTEST_PRED_IMPL_H_ #ifndef GTEST_INCLUDE_GTEST_GTEST_PRED_IMPL_H_
#define GTEST_INCLUDE_GTEST_GTEST_PRED_IMPL_H_ #define GTEST_INCLUDE_GTEST_GTEST_PRED_IMPL_H_
...@@ -246,8 +248,10 @@ AssertionResult AssertPred%(n)sHelper(const char* pred_text""" % DEFS ...@@ -246,8 +248,10 @@ AssertionResult AssertPred%(n)sHelper(const char* pred_text""" % DEFS
impl += ' << ") evaluates to false, where"' impl += ' << ") evaluates to false, where"'
impl += Iter(n, """ impl += Iter(
<< "\\n" << e%s << " evaluates to " << v%s""") n, """
<< "\\n" << e%s << " evaluates to " << ::testing::PrintToString(v%s)"""
)
impl += """; impl += """;
} }
...@@ -510,7 +514,7 @@ struct PredFormatFunctor%(n)s { ...@@ -510,7 +514,7 @@ struct PredFormatFunctor%(n)s {
class Predicate%(n)sTest : public testing::Test { class Predicate%(n)sTest : public testing::Test {
protected: protected:
virtual void SetUp() { void SetUp() override {
expected_to_finish_ = true; expected_to_finish_ = true;
finished_ = false;""" % DEFS finished_ = false;""" % DEFS
...@@ -520,7 +524,7 @@ class Predicate%(n)sTest : public testing::Test { ...@@ -520,7 +524,7 @@ class Predicate%(n)sTest : public testing::Test {
""" """
tests += """ tests += """
virtual void TearDown() { void TearDown() override {
// Verifies that each of the predicate's arguments was evaluated // Verifies that each of the predicate's arguments was evaluated
// exactly once.""" // exactly once."""
...@@ -588,7 +592,7 @@ typedef Predicate%(n)sTest ASSERT_PRED%(n)sTest; ...@@ -588,7 +592,7 @@ typedef Predicate%(n)sTest ASSERT_PRED%(n)sTest;
if use_assert: if use_assert:
assrt = 'ASSERT' # 'assert' is reserved, so we cannot use assrt = 'ASSERT' # 'assert' is reserved, so we cannot use
# that identifier here. # that identifier here.
else: else:
assrt = 'EXPECT' assrt = 'EXPECT'
......
#!/usr/bin/env python #!/usr/bin/env python2.7
# #
# Copyright 2008, Google Inc. # Copyright 2008, Google Inc.
# All rights reserved. # All rights reserved.
...@@ -62,7 +62,7 @@ GRAMMAR: ...@@ -62,7 +62,7 @@ GRAMMAR:
EXPRESSION has Python syntax. EXPRESSION has Python syntax.
""" """
__author__ = 'wan@google.com (Zhanyong Wan)' from __future__ import print_function
import os import os
import re import re
...@@ -246,7 +246,7 @@ def ParseToken(lines, pos, regex, token_type): ...@@ -246,7 +246,7 @@ def ParseToken(lines, pos, regex, token_type):
if m and not m.start(): if m and not m.start():
return MakeToken(lines, pos, pos + m.end(), token_type) return MakeToken(lines, pos, pos + m.end(), token_type)
else: else:
print 'ERROR: %s expected at %s.' % (token_type, pos) print('ERROR: %s expected at %s.' % (token_type, pos))
sys.exit(1) sys.exit(1)
...@@ -453,8 +453,8 @@ def PushFront(a_list, elem): ...@@ -453,8 +453,8 @@ def PushFront(a_list, elem):
def PopToken(a_list, token_type=None): def PopToken(a_list, token_type=None):
token = PopFront(a_list) token = PopFront(a_list)
if token_type is not None and token.token_type != token_type: if token_type is not None and token.token_type != token_type:
print 'ERROR: %s expected at %s' % (token_type, token.start) print('ERROR: %s expected at %s' % (token_type, token.start))
print 'ERROR: %s found instead' % (token,) print('ERROR: %s found instead' % (token,))
sys.exit(1) sys.exit(1)
return token return token
...@@ -616,16 +616,16 @@ class Env: ...@@ -616,16 +616,16 @@ class Env:
if identifier == var: if identifier == var:
return value return value
print 'ERROR: meta variable %s is undefined.' % (identifier,) print('ERROR: meta variable %s is undefined.' % (identifier,))
sys.exit(1) sys.exit(1)
def EvalExp(self, exp): def EvalExp(self, exp):
try: try:
result = eval(exp.python_exp) result = eval(exp.python_exp)
except Exception, e: except Exception as e: # pylint: disable=broad-except
print 'ERROR: caught exception %s: %s' % (e.__class__.__name__, e) print('ERROR: caught exception %s: %s' % (e.__class__.__name__, e))
print ('ERROR: failed to evaluate meta expression %s at %s' % print('ERROR: failed to evaluate meta expression %s at %s' %
(exp.python_exp, exp.token.start)) (exp.python_exp, exp.token.start))
sys.exit(1) sys.exit(1)
return result return result
...@@ -634,7 +634,7 @@ class Env: ...@@ -634,7 +634,7 @@ class Env:
if identifier == var: if identifier == var:
return (lower, upper) return (lower, upper)
print 'ERROR: range %s is undefined.' % (identifier,) print('ERROR: range %s is undefined.' % (identifier,))
sys.exit(1) sys.exit(1)
...@@ -694,8 +694,8 @@ def RunAtomicCode(env, node, output): ...@@ -694,8 +694,8 @@ def RunAtomicCode(env, node, output):
elif isinstance(node, CodeNode): elif isinstance(node, CodeNode):
RunCode(env.Clone(), node, output) RunCode(env.Clone(), node, output)
else: else:
print 'BAD' print('BAD')
print node print(node)
sys.exit(1) sys.exit(1)
...@@ -830,7 +830,7 @@ def ConvertFromPumpSource(src_text): ...@@ -830,7 +830,7 @@ def ConvertFromPumpSource(src_text):
def main(argv): def main(argv):
if len(argv) == 1: if len(argv) == 1:
print __doc__ print(__doc__)
sys.exit(1) sys.exit(1)
file_path = argv[-1] file_path = argv[-1]
...@@ -840,7 +840,7 @@ def main(argv): ...@@ -840,7 +840,7 @@ def main(argv):
else: else:
output_file_path = '-' output_file_path = '-'
if output_file_path == '-': if output_file_path == '-':
print output_str, print(output_str,)
else: else:
output_file = file(output_file_path, 'w') output_file = file(output_file_path, 'w')
output_file.write('// This file was GENERATED by command:\n') output_file.write('// This file was GENERATED by command:\n')
......
#!/usr/bin/env python
#
# Copyright 2010 Google Inc. All Rights Reserved.
"""Runs program specified in the command line with the substituted PATH.
This script is needed for to support building under Pulse which is unable
to override the existing PATH variable.
"""
import os
import subprocess
import sys
SUBST_PATH_ENV_VAR_NAME = "SUBST_PATH"
def main():
if SUBST_PATH_ENV_VAR_NAME in os.environ:
os.environ["PATH"] = os.environ[SUBST_PATH_ENV_VAR_NAME]
exit_code = subprocess.Popen(sys.argv[1:]).wait()
# exit_code is negative (-signal) if the process has been terminated by
# a signal. Returning negative exit code is not portable and so we return
# 100 instead.
if exit_code < 0:
exit_code = 100
sys.exit(exit_code)
if __name__ == "__main__":
main()
#!/usr/bin/env python #!/usr/bin/env python
# #
# Copyright 2007 Google Inc. # Copyright 2007, Google Inc.
# All rights reserved.
# #
# Licensed under the Apache License, Version 2.0 (the "License"); # Redistribution and use in source and binary forms, with or without
# you may not use this file except in compliance with the License. # modification, are permitted provided that the following conditions are
# You may obtain a copy of the License at # met:
# #
# http://www.apache.org/licenses/LICENSE-2.0 # * 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.
# #
# Unless required by applicable law or agreed to in writing, software # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# distributed under the License is distributed on an "AS IS" BASIS, # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# See the License for the specific language governing permissions and # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# limitations under the License. # 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.
"""Tool for uploading diffs from a version control system to the codereview app. """Tool for uploading diffs from a version control system to the codereview app.
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment