Fix line endings. WHAMMY.
This commit is contained in:
+58
-58
@@ -1,58 +1,58 @@
|
||||
#! /usr/bin/python
|
||||
|
||||
# See README.txt for information and build instructions.
|
||||
|
||||
import addressbook_pb2
|
||||
import sys
|
||||
|
||||
# This function fills in a Person message based on user input.
|
||||
def PromptForAddress(person):
|
||||
person.id = int(raw_input("Enter person ID number: "))
|
||||
person.name = raw_input("Enter name: ")
|
||||
|
||||
email = raw_input("Enter email address (blank for none): ")
|
||||
if email != "":
|
||||
person.email = email
|
||||
|
||||
while True:
|
||||
number = raw_input("Enter a phone number (or leave blank to finish): ")
|
||||
if number == "":
|
||||
break
|
||||
|
||||
phone_number = person.phone.add()
|
||||
phone_number.number = number
|
||||
|
||||
type = raw_input("Is this a mobile, home, or work phone? ")
|
||||
if type == "mobile":
|
||||
phone_number.type = addressbook_pb2.Person.MOBILE
|
||||
elif type == "home":
|
||||
phone_number.type = addressbook_pb2.Person.HOME
|
||||
elif type == "work":
|
||||
phone_number.type = addressbook_pb2.Person.WORK
|
||||
else:
|
||||
print "Unknown phone type; leaving as default value."
|
||||
|
||||
# Main procedure: Reads the entire address book from a file,
|
||||
# adds one person based on user input, then writes it back out to the same
|
||||
# file.
|
||||
if len(sys.argv) != 2:
|
||||
print "Usage:", sys.argv[0], "ADDRESS_BOOK_FILE"
|
||||
sys.exit(-1)
|
||||
|
||||
address_book = addressbook_pb2.AddressBook()
|
||||
|
||||
# Read the existing address book.
|
||||
try:
|
||||
f = open(sys.argv[1], "rb")
|
||||
address_book.ParseFromString(f.read())
|
||||
f.close()
|
||||
except IOError:
|
||||
print sys.argv[1] + ": File not found. Creating a new file."
|
||||
|
||||
# Add an address.
|
||||
PromptForAddress(address_book.person.add())
|
||||
|
||||
# Write the new address book back to disk.
|
||||
f = open(sys.argv[1], "wb")
|
||||
f.write(address_book.SerializeToString())
|
||||
f.close()
|
||||
#! /usr/bin/python
|
||||
|
||||
# See README.txt for information and build instructions.
|
||||
|
||||
import addressbook_pb2
|
||||
import sys
|
||||
|
||||
# This function fills in a Person message based on user input.
|
||||
def PromptForAddress(person):
|
||||
person.id = int(raw_input("Enter person ID number: "))
|
||||
person.name = raw_input("Enter name: ")
|
||||
|
||||
email = raw_input("Enter email address (blank for none): ")
|
||||
if email != "":
|
||||
person.email = email
|
||||
|
||||
while True:
|
||||
number = raw_input("Enter a phone number (or leave blank to finish): ")
|
||||
if number == "":
|
||||
break
|
||||
|
||||
phone_number = person.phone.add()
|
||||
phone_number.number = number
|
||||
|
||||
type = raw_input("Is this a mobile, home, or work phone? ")
|
||||
if type == "mobile":
|
||||
phone_number.type = addressbook_pb2.Person.MOBILE
|
||||
elif type == "home":
|
||||
phone_number.type = addressbook_pb2.Person.HOME
|
||||
elif type == "work":
|
||||
phone_number.type = addressbook_pb2.Person.WORK
|
||||
else:
|
||||
print "Unknown phone type; leaving as default value."
|
||||
|
||||
# Main procedure: Reads the entire address book from a file,
|
||||
# adds one person based on user input, then writes it back out to the same
|
||||
# file.
|
||||
if len(sys.argv) != 2:
|
||||
print "Usage:", sys.argv[0], "ADDRESS_BOOK_FILE"
|
||||
sys.exit(-1)
|
||||
|
||||
address_book = addressbook_pb2.AddressBook()
|
||||
|
||||
# Read the existing address book.
|
||||
try:
|
||||
f = open(sys.argv[1], "rb")
|
||||
address_book.ParseFromString(f.read())
|
||||
f.close()
|
||||
except IOError:
|
||||
print sys.argv[1] + ": File not found. Creating a new file."
|
||||
|
||||
# Add an address.
|
||||
PromptForAddress(address_book.person.add())
|
||||
|
||||
# Write the new address book back to disk.
|
||||
f = open(sys.argv[1], "wb")
|
||||
f.write(address_book.SerializeToString())
|
||||
f.close()
|
||||
|
||||
+38
-38
@@ -1,38 +1,38 @@
|
||||
#! /usr/bin/python
|
||||
|
||||
# See README.txt for information and build instructions.
|
||||
|
||||
import addressbook_pb2
|
||||
import sys
|
||||
|
||||
# Iterates though all people in the AddressBook and prints info about them.
|
||||
def ListPeople(address_book):
|
||||
for person in address_book.person:
|
||||
print "Person ID:", person.id
|
||||
print " Name:", person.name
|
||||
if person.HasField('email'):
|
||||
print " E-mail address:", person.email
|
||||
|
||||
for phone_number in person.phone:
|
||||
if phone_number.type == addressbook_pb2.Person.MOBILE:
|
||||
print " Mobile phone #:",
|
||||
elif phone_number.type == addressbook_pb2.Person.HOME:
|
||||
print " Home phone #:",
|
||||
elif phone_number.type == addressbook_pb2.Person.WORK:
|
||||
print " Work phone #:",
|
||||
print phone_number.number
|
||||
|
||||
# Main procedure: Reads the entire address book from a file and prints all
|
||||
# the information inside.
|
||||
if len(sys.argv) != 2:
|
||||
print "Usage:", sys.argv[0], "ADDRESS_BOOK_FILE"
|
||||
sys.exit(-1)
|
||||
|
||||
address_book = addressbook_pb2.AddressBook()
|
||||
|
||||
# Read the existing address book.
|
||||
f = open(sys.argv[1], "rb")
|
||||
address_book.ParseFromString(f.read())
|
||||
f.close()
|
||||
|
||||
ListPeople(address_book)
|
||||
#! /usr/bin/python
|
||||
|
||||
# See README.txt for information and build instructions.
|
||||
|
||||
import addressbook_pb2
|
||||
import sys
|
||||
|
||||
# Iterates though all people in the AddressBook and prints info about them.
|
||||
def ListPeople(address_book):
|
||||
for person in address_book.person:
|
||||
print "Person ID:", person.id
|
||||
print " Name:", person.name
|
||||
if person.HasField('email'):
|
||||
print " E-mail address:", person.email
|
||||
|
||||
for phone_number in person.phone:
|
||||
if phone_number.type == addressbook_pb2.Person.MOBILE:
|
||||
print " Mobile phone #:",
|
||||
elif phone_number.type == addressbook_pb2.Person.HOME:
|
||||
print " Home phone #:",
|
||||
elif phone_number.type == addressbook_pb2.Person.WORK:
|
||||
print " Work phone #:",
|
||||
print phone_number.number
|
||||
|
||||
# Main procedure: Reads the entire address book from a file and prints all
|
||||
# the information inside.
|
||||
if len(sys.argv) != 2:
|
||||
print "Usage:", sys.argv[0], "ADDRESS_BOOK_FILE"
|
||||
sys.exit(-1)
|
||||
|
||||
address_book = addressbook_pb2.AddressBook()
|
||||
|
||||
# Read the existing address book.
|
||||
f = open(sys.argv[1], "rb")
|
||||
address_book.ParseFromString(f.read())
|
||||
f.close()
|
||||
|
||||
ListPeople(address_book)
|
||||
|
||||
+283
-283
@@ -1,283 +1,283 @@
|
||||
// Copyright 2005, 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)
|
||||
//
|
||||
// The Google C++ Testing Framework (Google Test)
|
||||
//
|
||||
// This header file defines the public API for death tests. It is
|
||||
// #included by gtest.h so a user doesn't need to include this
|
||||
// directly.
|
||||
|
||||
#ifndef GTEST_INCLUDE_GTEST_GTEST_DEATH_TEST_H_
|
||||
#define GTEST_INCLUDE_GTEST_GTEST_DEATH_TEST_H_
|
||||
|
||||
#include <gtest/internal/gtest-death-test-internal.h>
|
||||
|
||||
namespace testing {
|
||||
|
||||
// This flag controls the style of death tests. Valid values are "threadsafe",
|
||||
// meaning that the death test child process will re-execute the test binary
|
||||
// from the start, running only a single death test, or "fast",
|
||||
// meaning that the child process will execute the test logic immediately
|
||||
// after forking.
|
||||
GTEST_DECLARE_string_(death_test_style);
|
||||
|
||||
#if GTEST_HAS_DEATH_TEST
|
||||
|
||||
// The following macros are useful for writing death tests.
|
||||
|
||||
// Here's what happens when an ASSERT_DEATH* or EXPECT_DEATH* is
|
||||
// executed:
|
||||
//
|
||||
// 1. It generates a warning if there is more than one active
|
||||
// thread. This is because it's safe to fork() or clone() only
|
||||
// when there is a single thread.
|
||||
//
|
||||
// 2. The parent process clone()s a sub-process and runs the death
|
||||
// test in it; the sub-process exits with code 0 at the end of the
|
||||
// death test, if it hasn't exited already.
|
||||
//
|
||||
// 3. The parent process waits for the sub-process to terminate.
|
||||
//
|
||||
// 4. The parent process checks the exit code and error message of
|
||||
// the sub-process.
|
||||
//
|
||||
// Examples:
|
||||
//
|
||||
// ASSERT_DEATH(server.SendMessage(56, "Hello"), "Invalid port number");
|
||||
// for (int i = 0; i < 5; i++) {
|
||||
// EXPECT_DEATH(server.ProcessRequest(i),
|
||||
// "Invalid request .* in ProcessRequest()")
|
||||
// << "Failed to die on request " << i);
|
||||
// }
|
||||
//
|
||||
// ASSERT_EXIT(server.ExitNow(), ::testing::ExitedWithCode(0), "Exiting");
|
||||
//
|
||||
// bool KilledBySIGHUP(int exit_code) {
|
||||
// return WIFSIGNALED(exit_code) && WTERMSIG(exit_code) == SIGHUP;
|
||||
// }
|
||||
//
|
||||
// ASSERT_EXIT(client.HangUpServer(), KilledBySIGHUP, "Hanging up!");
|
||||
//
|
||||
// On the regular expressions used in death tests:
|
||||
//
|
||||
// On POSIX-compliant systems (*nix), we use the <regex.h> library,
|
||||
// which uses the POSIX extended regex syntax.
|
||||
//
|
||||
// On other platforms (e.g. Windows), we only support a simple regex
|
||||
// syntax implemented as part of Google Test. This limited
|
||||
// implementation should be enough most of the time when writing
|
||||
// death tests; though it lacks many features you can find in PCRE
|
||||
// or POSIX extended regex syntax. For example, we don't support
|
||||
// union ("x|y"), grouping ("(xy)"), brackets ("[xy]"), and
|
||||
// repetition count ("x{5,7}"), among others.
|
||||
//
|
||||
// Below is the syntax that we do support. We chose it to be a
|
||||
// subset of both PCRE and POSIX extended regex, so it's easy to
|
||||
// learn wherever you come from. In the following: 'A' denotes a
|
||||
// literal character, period (.), or a single \\ escape sequence;
|
||||
// 'x' and 'y' denote regular expressions; 'm' and 'n' are for
|
||||
// natural numbers.
|
||||
//
|
||||
// c matches any literal character c
|
||||
// \\d matches any decimal digit
|
||||
// \\D matches any character that's not a decimal digit
|
||||
// \\f matches \f
|
||||
// \\n matches \n
|
||||
// \\r matches \r
|
||||
// \\s matches any ASCII whitespace, including \n
|
||||
// \\S matches any character that's not a whitespace
|
||||
// \\t matches \t
|
||||
// \\v matches \v
|
||||
// \\w matches any letter, _, or decimal digit
|
||||
// \\W matches any character that \\w doesn't match
|
||||
// \\c matches any literal character c, which must be a punctuation
|
||||
// . matches any single character except \n
|
||||
// A? matches 0 or 1 occurrences of A
|
||||
// A* matches 0 or many occurrences of A
|
||||
// A+ matches 1 or many occurrences of A
|
||||
// ^ matches the beginning of a string (not that of each line)
|
||||
// $ matches the end of a string (not that of each line)
|
||||
// xy matches x followed by y
|
||||
//
|
||||
// If you accidentally use PCRE or POSIX extended regex features
|
||||
// not implemented by us, you will get a run-time failure. In that
|
||||
// case, please try to rewrite your regular expression within the
|
||||
// above syntax.
|
||||
//
|
||||
// This implementation is *not* meant to be as highly tuned or robust
|
||||
// as a compiled regex library, but should perform well enough for a
|
||||
// death test, which already incurs significant overhead by launching
|
||||
// a child process.
|
||||
//
|
||||
// Known caveats:
|
||||
//
|
||||
// A "threadsafe" style death test obtains the path to the test
|
||||
// program from argv[0] and re-executes it in the sub-process. For
|
||||
// simplicity, the current implementation doesn't search the PATH
|
||||
// when launching the sub-process. This means that the user must
|
||||
// invoke the test program via a path that contains at least one
|
||||
// path separator (e.g. path/to/foo_test and
|
||||
// /absolute/path/to/bar_test are fine, but foo_test is not). This
|
||||
// is rarely a problem as people usually don't put the test binary
|
||||
// directory in PATH.
|
||||
//
|
||||
// TODO(wan@google.com): make thread-safe death tests search the PATH.
|
||||
|
||||
// Asserts that a given statement causes the program to exit, with an
|
||||
// integer exit status that satisfies predicate, and emitting error output
|
||||
// that matches regex.
|
||||
#define ASSERT_EXIT(statement, predicate, regex) \
|
||||
GTEST_DEATH_TEST_(statement, predicate, regex, GTEST_FATAL_FAILURE_)
|
||||
|
||||
// Like ASSERT_EXIT, but continues on to successive tests in the
|
||||
// test case, if any:
|
||||
#define EXPECT_EXIT(statement, predicate, regex) \
|
||||
GTEST_DEATH_TEST_(statement, predicate, regex, GTEST_NONFATAL_FAILURE_)
|
||||
|
||||
// Asserts that a given statement causes the program to exit, either by
|
||||
// explicitly exiting with a nonzero exit code or being killed by a
|
||||
// signal, and emitting error output that matches regex.
|
||||
#define ASSERT_DEATH(statement, regex) \
|
||||
ASSERT_EXIT(statement, ::testing::internal::ExitedUnsuccessfully, regex)
|
||||
|
||||
// Like ASSERT_DEATH, but continues on to successive tests in the
|
||||
// test case, if any:
|
||||
#define EXPECT_DEATH(statement, regex) \
|
||||
EXPECT_EXIT(statement, ::testing::internal::ExitedUnsuccessfully, regex)
|
||||
|
||||
// Two predicate classes that can be used in {ASSERT,EXPECT}_EXIT*:
|
||||
|
||||
// Tests that an exit code describes a normal exit with a given exit code.
|
||||
class ExitedWithCode {
|
||||
public:
|
||||
explicit ExitedWithCode(int exit_code);
|
||||
bool operator()(int exit_status) const;
|
||||
private:
|
||||
// No implementation - assignment is unsupported.
|
||||
void operator=(const ExitedWithCode& other);
|
||||
|
||||
const int exit_code_;
|
||||
};
|
||||
|
||||
#if !GTEST_OS_WINDOWS
|
||||
// Tests that an exit code describes an exit due to termination by a
|
||||
// given signal.
|
||||
class KilledBySignal {
|
||||
public:
|
||||
explicit KilledBySignal(int signum);
|
||||
bool operator()(int exit_status) const;
|
||||
private:
|
||||
const int signum_;
|
||||
};
|
||||
#endif // !GTEST_OS_WINDOWS
|
||||
|
||||
// EXPECT_DEBUG_DEATH asserts that the given statements die in debug mode.
|
||||
// The death testing framework causes this to have interesting semantics,
|
||||
// since the sideeffects of the call are only visible in opt mode, and not
|
||||
// in debug mode.
|
||||
//
|
||||
// In practice, this can be used to test functions that utilize the
|
||||
// LOG(DFATAL) macro using the following style:
|
||||
//
|
||||
// int DieInDebugOr12(int* sideeffect) {
|
||||
// if (sideeffect) {
|
||||
// *sideeffect = 12;
|
||||
// }
|
||||
// LOG(DFATAL) << "death";
|
||||
// return 12;
|
||||
// }
|
||||
//
|
||||
// TEST(TestCase, TestDieOr12WorksInDgbAndOpt) {
|
||||
// int sideeffect = 0;
|
||||
// // Only asserts in dbg.
|
||||
// EXPECT_DEBUG_DEATH(DieInDebugOr12(&sideeffect), "death");
|
||||
//
|
||||
// #ifdef NDEBUG
|
||||
// // opt-mode has sideeffect visible.
|
||||
// EXPECT_EQ(12, sideeffect);
|
||||
// #else
|
||||
// // dbg-mode no visible sideeffect.
|
||||
// EXPECT_EQ(0, sideeffect);
|
||||
// #endif
|
||||
// }
|
||||
//
|
||||
// This will assert that DieInDebugReturn12InOpt() crashes in debug
|
||||
// mode, usually due to a DCHECK or LOG(DFATAL), but returns the
|
||||
// appropriate fallback value (12 in this case) in opt mode. If you
|
||||
// need to test that a function has appropriate side-effects in opt
|
||||
// mode, include assertions against the side-effects. A general
|
||||
// pattern for this is:
|
||||
//
|
||||
// EXPECT_DEBUG_DEATH({
|
||||
// // Side-effects here will have an effect after this statement in
|
||||
// // opt mode, but none in debug mode.
|
||||
// EXPECT_EQ(12, DieInDebugOr12(&sideeffect));
|
||||
// }, "death");
|
||||
//
|
||||
#ifdef NDEBUG
|
||||
|
||||
#define EXPECT_DEBUG_DEATH(statement, regex) \
|
||||
do { statement; } while (::testing::internal::AlwaysFalse())
|
||||
|
||||
#define ASSERT_DEBUG_DEATH(statement, regex) \
|
||||
do { statement; } while (::testing::internal::AlwaysFalse())
|
||||
|
||||
#else
|
||||
|
||||
#define EXPECT_DEBUG_DEATH(statement, regex) \
|
||||
EXPECT_DEATH(statement, regex)
|
||||
|
||||
#define ASSERT_DEBUG_DEATH(statement, regex) \
|
||||
ASSERT_DEATH(statement, regex)
|
||||
|
||||
#endif // NDEBUG for EXPECT_DEBUG_DEATH
|
||||
#endif // GTEST_HAS_DEATH_TEST
|
||||
|
||||
// EXPECT_DEATH_IF_SUPPORTED(statement, regex) and
|
||||
// ASSERT_DEATH_IF_SUPPORTED(statement, regex) expand to real death tests if
|
||||
// death tests are supported; otherwise they just issue a warning. This is
|
||||
// useful when you are combining death test assertions with normal test
|
||||
// assertions in one test.
|
||||
#if GTEST_HAS_DEATH_TEST
|
||||
#define EXPECT_DEATH_IF_SUPPORTED(statement, regex) \
|
||||
EXPECT_DEATH(statement, regex)
|
||||
#define ASSERT_DEATH_IF_SUPPORTED(statement, regex) \
|
||||
ASSERT_DEATH(statement, regex)
|
||||
#else
|
||||
#define EXPECT_DEATH_IF_SUPPORTED(statement, regex) \
|
||||
GTEST_UNSUPPORTED_DEATH_TEST_(statement, regex, )
|
||||
#define ASSERT_DEATH_IF_SUPPORTED(statement, regex) \
|
||||
GTEST_UNSUPPORTED_DEATH_TEST_(statement, regex, return)
|
||||
#endif
|
||||
|
||||
} // namespace testing
|
||||
|
||||
#endif // GTEST_INCLUDE_GTEST_GTEST_DEATH_TEST_H_
|
||||
// Copyright 2005, 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)
|
||||
//
|
||||
// The Google C++ Testing Framework (Google Test)
|
||||
//
|
||||
// This header file defines the public API for death tests. It is
|
||||
// #included by gtest.h so a user doesn't need to include this
|
||||
// directly.
|
||||
|
||||
#ifndef GTEST_INCLUDE_GTEST_GTEST_DEATH_TEST_H_
|
||||
#define GTEST_INCLUDE_GTEST_GTEST_DEATH_TEST_H_
|
||||
|
||||
#include <gtest/internal/gtest-death-test-internal.h>
|
||||
|
||||
namespace testing {
|
||||
|
||||
// This flag controls the style of death tests. Valid values are "threadsafe",
|
||||
// meaning that the death test child process will re-execute the test binary
|
||||
// from the start, running only a single death test, or "fast",
|
||||
// meaning that the child process will execute the test logic immediately
|
||||
// after forking.
|
||||
GTEST_DECLARE_string_(death_test_style);
|
||||
|
||||
#if GTEST_HAS_DEATH_TEST
|
||||
|
||||
// The following macros are useful for writing death tests.
|
||||
|
||||
// Here's what happens when an ASSERT_DEATH* or EXPECT_DEATH* is
|
||||
// executed:
|
||||
//
|
||||
// 1. It generates a warning if there is more than one active
|
||||
// thread. This is because it's safe to fork() or clone() only
|
||||
// when there is a single thread.
|
||||
//
|
||||
// 2. The parent process clone()s a sub-process and runs the death
|
||||
// test in it; the sub-process exits with code 0 at the end of the
|
||||
// death test, if it hasn't exited already.
|
||||
//
|
||||
// 3. The parent process waits for the sub-process to terminate.
|
||||
//
|
||||
// 4. The parent process checks the exit code and error message of
|
||||
// the sub-process.
|
||||
//
|
||||
// Examples:
|
||||
//
|
||||
// ASSERT_DEATH(server.SendMessage(56, "Hello"), "Invalid port number");
|
||||
// for (int i = 0; i < 5; i++) {
|
||||
// EXPECT_DEATH(server.ProcessRequest(i),
|
||||
// "Invalid request .* in ProcessRequest()")
|
||||
// << "Failed to die on request " << i);
|
||||
// }
|
||||
//
|
||||
// ASSERT_EXIT(server.ExitNow(), ::testing::ExitedWithCode(0), "Exiting");
|
||||
//
|
||||
// bool KilledBySIGHUP(int exit_code) {
|
||||
// return WIFSIGNALED(exit_code) && WTERMSIG(exit_code) == SIGHUP;
|
||||
// }
|
||||
//
|
||||
// ASSERT_EXIT(client.HangUpServer(), KilledBySIGHUP, "Hanging up!");
|
||||
//
|
||||
// On the regular expressions used in death tests:
|
||||
//
|
||||
// On POSIX-compliant systems (*nix), we use the <regex.h> library,
|
||||
// which uses the POSIX extended regex syntax.
|
||||
//
|
||||
// On other platforms (e.g. Windows), we only support a simple regex
|
||||
// syntax implemented as part of Google Test. This limited
|
||||
// implementation should be enough most of the time when writing
|
||||
// death tests; though it lacks many features you can find in PCRE
|
||||
// or POSIX extended regex syntax. For example, we don't support
|
||||
// union ("x|y"), grouping ("(xy)"), brackets ("[xy]"), and
|
||||
// repetition count ("x{5,7}"), among others.
|
||||
//
|
||||
// Below is the syntax that we do support. We chose it to be a
|
||||
// subset of both PCRE and POSIX extended regex, so it's easy to
|
||||
// learn wherever you come from. In the following: 'A' denotes a
|
||||
// literal character, period (.), or a single \\ escape sequence;
|
||||
// 'x' and 'y' denote regular expressions; 'm' and 'n' are for
|
||||
// natural numbers.
|
||||
//
|
||||
// c matches any literal character c
|
||||
// \\d matches any decimal digit
|
||||
// \\D matches any character that's not a decimal digit
|
||||
// \\f matches \f
|
||||
// \\n matches \n
|
||||
// \\r matches \r
|
||||
// \\s matches any ASCII whitespace, including \n
|
||||
// \\S matches any character that's not a whitespace
|
||||
// \\t matches \t
|
||||
// \\v matches \v
|
||||
// \\w matches any letter, _, or decimal digit
|
||||
// \\W matches any character that \\w doesn't match
|
||||
// \\c matches any literal character c, which must be a punctuation
|
||||
// . matches any single character except \n
|
||||
// A? matches 0 or 1 occurrences of A
|
||||
// A* matches 0 or many occurrences of A
|
||||
// A+ matches 1 or many occurrences of A
|
||||
// ^ matches the beginning of a string (not that of each line)
|
||||
// $ matches the end of a string (not that of each line)
|
||||
// xy matches x followed by y
|
||||
//
|
||||
// If you accidentally use PCRE or POSIX extended regex features
|
||||
// not implemented by us, you will get a run-time failure. In that
|
||||
// case, please try to rewrite your regular expression within the
|
||||
// above syntax.
|
||||
//
|
||||
// This implementation is *not* meant to be as highly tuned or robust
|
||||
// as a compiled regex library, but should perform well enough for a
|
||||
// death test, which already incurs significant overhead by launching
|
||||
// a child process.
|
||||
//
|
||||
// Known caveats:
|
||||
//
|
||||
// A "threadsafe" style death test obtains the path to the test
|
||||
// program from argv[0] and re-executes it in the sub-process. For
|
||||
// simplicity, the current implementation doesn't search the PATH
|
||||
// when launching the sub-process. This means that the user must
|
||||
// invoke the test program via a path that contains at least one
|
||||
// path separator (e.g. path/to/foo_test and
|
||||
// /absolute/path/to/bar_test are fine, but foo_test is not). This
|
||||
// is rarely a problem as people usually don't put the test binary
|
||||
// directory in PATH.
|
||||
//
|
||||
// TODO(wan@google.com): make thread-safe death tests search the PATH.
|
||||
|
||||
// Asserts that a given statement causes the program to exit, with an
|
||||
// integer exit status that satisfies predicate, and emitting error output
|
||||
// that matches regex.
|
||||
#define ASSERT_EXIT(statement, predicate, regex) \
|
||||
GTEST_DEATH_TEST_(statement, predicate, regex, GTEST_FATAL_FAILURE_)
|
||||
|
||||
// Like ASSERT_EXIT, but continues on to successive tests in the
|
||||
// test case, if any:
|
||||
#define EXPECT_EXIT(statement, predicate, regex) \
|
||||
GTEST_DEATH_TEST_(statement, predicate, regex, GTEST_NONFATAL_FAILURE_)
|
||||
|
||||
// Asserts that a given statement causes the program to exit, either by
|
||||
// explicitly exiting with a nonzero exit code or being killed by a
|
||||
// signal, and emitting error output that matches regex.
|
||||
#define ASSERT_DEATH(statement, regex) \
|
||||
ASSERT_EXIT(statement, ::testing::internal::ExitedUnsuccessfully, regex)
|
||||
|
||||
// Like ASSERT_DEATH, but continues on to successive tests in the
|
||||
// test case, if any:
|
||||
#define EXPECT_DEATH(statement, regex) \
|
||||
EXPECT_EXIT(statement, ::testing::internal::ExitedUnsuccessfully, regex)
|
||||
|
||||
// Two predicate classes that can be used in {ASSERT,EXPECT}_EXIT*:
|
||||
|
||||
// Tests that an exit code describes a normal exit with a given exit code.
|
||||
class ExitedWithCode {
|
||||
public:
|
||||
explicit ExitedWithCode(int exit_code);
|
||||
bool operator()(int exit_status) const;
|
||||
private:
|
||||
// No implementation - assignment is unsupported.
|
||||
void operator=(const ExitedWithCode& other);
|
||||
|
||||
const int exit_code_;
|
||||
};
|
||||
|
||||
#if !GTEST_OS_WINDOWS
|
||||
// Tests that an exit code describes an exit due to termination by a
|
||||
// given signal.
|
||||
class KilledBySignal {
|
||||
public:
|
||||
explicit KilledBySignal(int signum);
|
||||
bool operator()(int exit_status) const;
|
||||
private:
|
||||
const int signum_;
|
||||
};
|
||||
#endif // !GTEST_OS_WINDOWS
|
||||
|
||||
// EXPECT_DEBUG_DEATH asserts that the given statements die in debug mode.
|
||||
// The death testing framework causes this to have interesting semantics,
|
||||
// since the sideeffects of the call are only visible in opt mode, and not
|
||||
// in debug mode.
|
||||
//
|
||||
// In practice, this can be used to test functions that utilize the
|
||||
// LOG(DFATAL) macro using the following style:
|
||||
//
|
||||
// int DieInDebugOr12(int* sideeffect) {
|
||||
// if (sideeffect) {
|
||||
// *sideeffect = 12;
|
||||
// }
|
||||
// LOG(DFATAL) << "death";
|
||||
// return 12;
|
||||
// }
|
||||
//
|
||||
// TEST(TestCase, TestDieOr12WorksInDgbAndOpt) {
|
||||
// int sideeffect = 0;
|
||||
// // Only asserts in dbg.
|
||||
// EXPECT_DEBUG_DEATH(DieInDebugOr12(&sideeffect), "death");
|
||||
//
|
||||
// #ifdef NDEBUG
|
||||
// // opt-mode has sideeffect visible.
|
||||
// EXPECT_EQ(12, sideeffect);
|
||||
// #else
|
||||
// // dbg-mode no visible sideeffect.
|
||||
// EXPECT_EQ(0, sideeffect);
|
||||
// #endif
|
||||
// }
|
||||
//
|
||||
// This will assert that DieInDebugReturn12InOpt() crashes in debug
|
||||
// mode, usually due to a DCHECK or LOG(DFATAL), but returns the
|
||||
// appropriate fallback value (12 in this case) in opt mode. If you
|
||||
// need to test that a function has appropriate side-effects in opt
|
||||
// mode, include assertions against the side-effects. A general
|
||||
// pattern for this is:
|
||||
//
|
||||
// EXPECT_DEBUG_DEATH({
|
||||
// // Side-effects here will have an effect after this statement in
|
||||
// // opt mode, but none in debug mode.
|
||||
// EXPECT_EQ(12, DieInDebugOr12(&sideeffect));
|
||||
// }, "death");
|
||||
//
|
||||
#ifdef NDEBUG
|
||||
|
||||
#define EXPECT_DEBUG_DEATH(statement, regex) \
|
||||
do { statement; } while (::testing::internal::AlwaysFalse())
|
||||
|
||||
#define ASSERT_DEBUG_DEATH(statement, regex) \
|
||||
do { statement; } while (::testing::internal::AlwaysFalse())
|
||||
|
||||
#else
|
||||
|
||||
#define EXPECT_DEBUG_DEATH(statement, regex) \
|
||||
EXPECT_DEATH(statement, regex)
|
||||
|
||||
#define ASSERT_DEBUG_DEATH(statement, regex) \
|
||||
ASSERT_DEATH(statement, regex)
|
||||
|
||||
#endif // NDEBUG for EXPECT_DEBUG_DEATH
|
||||
#endif // GTEST_HAS_DEATH_TEST
|
||||
|
||||
// EXPECT_DEATH_IF_SUPPORTED(statement, regex) and
|
||||
// ASSERT_DEATH_IF_SUPPORTED(statement, regex) expand to real death tests if
|
||||
// death tests are supported; otherwise they just issue a warning. This is
|
||||
// useful when you are combining death test assertions with normal test
|
||||
// assertions in one test.
|
||||
#if GTEST_HAS_DEATH_TEST
|
||||
#define EXPECT_DEATH_IF_SUPPORTED(statement, regex) \
|
||||
EXPECT_DEATH(statement, regex)
|
||||
#define ASSERT_DEATH_IF_SUPPORTED(statement, regex) \
|
||||
ASSERT_DEATH(statement, regex)
|
||||
#else
|
||||
#define EXPECT_DEATH_IF_SUPPORTED(statement, regex) \
|
||||
GTEST_UNSUPPORTED_DEATH_TEST_(statement, regex, )
|
||||
#define ASSERT_DEATH_IF_SUPPORTED(statement, regex) \
|
||||
GTEST_UNSUPPORTED_DEATH_TEST_(statement, regex, return)
|
||||
#endif
|
||||
|
||||
} // namespace testing
|
||||
|
||||
#endif // GTEST_INCLUDE_GTEST_GTEST_DEATH_TEST_H_
|
||||
|
||||
+224
-224
@@ -1,224 +1,224 @@
|
||||
// Copyright 2005, 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)
|
||||
//
|
||||
// The Google C++ Testing Framework (Google Test)
|
||||
//
|
||||
// This header file defines the Message class.
|
||||
//
|
||||
// IMPORTANT NOTE: Due to limitation of the C++ language, we have to
|
||||
// leave some internal implementation details in this header file.
|
||||
// They are clearly marked by comments like this:
|
||||
//
|
||||
// // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
|
||||
//
|
||||
// Such code is NOT meant to be used by a user directly, and is subject
|
||||
// to CHANGE WITHOUT NOTICE. Therefore DO NOT DEPEND ON IT in a user
|
||||
// program!
|
||||
|
||||
#ifndef GTEST_INCLUDE_GTEST_GTEST_MESSAGE_H_
|
||||
#define GTEST_INCLUDE_GTEST_GTEST_MESSAGE_H_
|
||||
|
||||
#include <gtest/internal/gtest-string.h>
|
||||
#include <gtest/internal/gtest-internal.h>
|
||||
|
||||
namespace testing {
|
||||
|
||||
// The Message class works like an ostream repeater.
|
||||
//
|
||||
// Typical usage:
|
||||
//
|
||||
// 1. You stream a bunch of values to a Message object.
|
||||
// It will remember the text in a StrStream.
|
||||
// 2. Then you stream the Message object to an ostream.
|
||||
// This causes the text in the Message to be streamed
|
||||
// to the ostream.
|
||||
//
|
||||
// For example;
|
||||
//
|
||||
// testing::Message foo;
|
||||
// foo << 1 << " != " << 2;
|
||||
// std::cout << foo;
|
||||
//
|
||||
// will print "1 != 2".
|
||||
//
|
||||
// Message is not intended to be inherited from. In particular, its
|
||||
// destructor is not virtual.
|
||||
//
|
||||
// Note that StrStream behaves differently in gcc and in MSVC. You
|
||||
// can stream a NULL char pointer to it in the former, but not in the
|
||||
// latter (it causes an access violation if you do). The Message
|
||||
// class hides this difference by treating a NULL char pointer as
|
||||
// "(null)".
|
||||
class Message {
|
||||
private:
|
||||
// The type of basic IO manipulators (endl, ends, and flush) for
|
||||
// narrow streams.
|
||||
typedef std::ostream& (*BasicNarrowIoManip)(std::ostream&);
|
||||
|
||||
public:
|
||||
// Constructs an empty Message.
|
||||
// We allocate the StrStream separately because it otherwise each use of
|
||||
// ASSERT/EXPECT in a procedure adds over 200 bytes to the procedure's
|
||||
// stack frame leading to huge stack frames in some cases; gcc does not reuse
|
||||
// the stack space.
|
||||
Message() : ss_(new internal::StrStream) {}
|
||||
|
||||
// Copy constructor.
|
||||
Message(const Message& msg) : ss_(new internal::StrStream) { // NOLINT
|
||||
*ss_ << msg.GetString();
|
||||
}
|
||||
|
||||
// Constructs a Message from a C-string.
|
||||
explicit Message(const char* str) : ss_(new internal::StrStream) {
|
||||
*ss_ << str;
|
||||
}
|
||||
|
||||
~Message() { delete ss_; }
|
||||
#if GTEST_OS_SYMBIAN
|
||||
// Streams a value (either a pointer or not) to this object.
|
||||
template <typename T>
|
||||
inline Message& operator <<(const T& value) {
|
||||
StreamHelper(typename internal::is_pointer<T>::type(), value);
|
||||
return *this;
|
||||
}
|
||||
#else
|
||||
// Streams a non-pointer value to this object.
|
||||
template <typename T>
|
||||
inline Message& operator <<(const T& val) {
|
||||
::GTestStreamToHelper(ss_, val);
|
||||
return *this;
|
||||
}
|
||||
|
||||
// Streams a pointer value to this object.
|
||||
//
|
||||
// This function is an overload of the previous one. When you
|
||||
// stream a pointer to a Message, this definition will be used as it
|
||||
// is more specialized. (The C++ Standard, section
|
||||
// [temp.func.order].) If you stream a non-pointer, then the
|
||||
// previous definition will be used.
|
||||
//
|
||||
// The reason for this overload is that streaming a NULL pointer to
|
||||
// ostream is undefined behavior. Depending on the compiler, you
|
||||
// may get "0", "(nil)", "(null)", or an access violation. To
|
||||
// ensure consistent result across compilers, we always treat NULL
|
||||
// as "(null)".
|
||||
template <typename T>
|
||||
inline Message& operator <<(T* const& pointer) { // NOLINT
|
||||
if (pointer == NULL) {
|
||||
*ss_ << "(null)";
|
||||
} else {
|
||||
::GTestStreamToHelper(ss_, pointer);
|
||||
}
|
||||
return *this;
|
||||
}
|
||||
#endif // GTEST_OS_SYMBIAN
|
||||
|
||||
// Since the basic IO manipulators are overloaded for both narrow
|
||||
// and wide streams, we have to provide this specialized definition
|
||||
// of operator <<, even though its body is the same as the
|
||||
// templatized version above. Without this definition, streaming
|
||||
// endl or other basic IO manipulators to Message will confuse the
|
||||
// compiler.
|
||||
Message& operator <<(BasicNarrowIoManip val) {
|
||||
*ss_ << val;
|
||||
return *this;
|
||||
}
|
||||
|
||||
// Instead of 1/0, we want to see true/false for bool values.
|
||||
Message& operator <<(bool b) {
|
||||
return *this << (b ? "true" : "false");
|
||||
}
|
||||
|
||||
// These two overloads allow streaming a wide C string to a Message
|
||||
// using the UTF-8 encoding.
|
||||
Message& operator <<(const wchar_t* wide_c_str) {
|
||||
return *this << internal::String::ShowWideCString(wide_c_str);
|
||||
}
|
||||
Message& operator <<(wchar_t* wide_c_str) {
|
||||
return *this << internal::String::ShowWideCString(wide_c_str);
|
||||
}
|
||||
|
||||
#if GTEST_HAS_STD_WSTRING
|
||||
// Converts the given wide string to a narrow string using the UTF-8
|
||||
// encoding, and streams the result to this Message object.
|
||||
Message& operator <<(const ::std::wstring& wstr);
|
||||
#endif // GTEST_HAS_STD_WSTRING
|
||||
|
||||
#if GTEST_HAS_GLOBAL_WSTRING
|
||||
// Converts the given wide string to a narrow string using the UTF-8
|
||||
// encoding, and streams the result to this Message object.
|
||||
Message& operator <<(const ::wstring& wstr);
|
||||
#endif // GTEST_HAS_GLOBAL_WSTRING
|
||||
|
||||
// Gets the text streamed to this object so far as a String.
|
||||
// Each '\0' character in the buffer is replaced with "\\0".
|
||||
//
|
||||
// INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
|
||||
internal::String GetString() const {
|
||||
return internal::StrStreamToString(ss_);
|
||||
}
|
||||
|
||||
private:
|
||||
#if GTEST_OS_SYMBIAN
|
||||
// These are needed as the Nokia Symbian Compiler cannot decide between
|
||||
// const T& and const T* in a function template. The Nokia compiler _can_
|
||||
// decide between class template specializations for T and T*, so a
|
||||
// tr1::type_traits-like is_pointer works, and we can overload on that.
|
||||
template <typename T>
|
||||
inline void StreamHelper(internal::true_type /*dummy*/, T* pointer) {
|
||||
if (pointer == NULL) {
|
||||
*ss_ << "(null)";
|
||||
} else {
|
||||
::GTestStreamToHelper(ss_, pointer);
|
||||
}
|
||||
}
|
||||
template <typename T>
|
||||
inline void StreamHelper(internal::false_type /*dummy*/, const T& value) {
|
||||
::GTestStreamToHelper(ss_, value);
|
||||
}
|
||||
#endif // GTEST_OS_SYMBIAN
|
||||
|
||||
// We'll hold the text streamed to this object here.
|
||||
internal::StrStream* const ss_;
|
||||
|
||||
// We declare (but don't implement) this to prevent the compiler
|
||||
// from implementing the assignment operator.
|
||||
void operator=(const Message&);
|
||||
};
|
||||
|
||||
// Streams a Message to an ostream.
|
||||
inline std::ostream& operator <<(std::ostream& os, const Message& sb) {
|
||||
return os << sb.GetString();
|
||||
}
|
||||
|
||||
} // namespace testing
|
||||
|
||||
#endif // GTEST_INCLUDE_GTEST_GTEST_MESSAGE_H_
|
||||
// Copyright 2005, 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)
|
||||
//
|
||||
// The Google C++ Testing Framework (Google Test)
|
||||
//
|
||||
// This header file defines the Message class.
|
||||
//
|
||||
// IMPORTANT NOTE: Due to limitation of the C++ language, we have to
|
||||
// leave some internal implementation details in this header file.
|
||||
// They are clearly marked by comments like this:
|
||||
//
|
||||
// // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
|
||||
//
|
||||
// Such code is NOT meant to be used by a user directly, and is subject
|
||||
// to CHANGE WITHOUT NOTICE. Therefore DO NOT DEPEND ON IT in a user
|
||||
// program!
|
||||
|
||||
#ifndef GTEST_INCLUDE_GTEST_GTEST_MESSAGE_H_
|
||||
#define GTEST_INCLUDE_GTEST_GTEST_MESSAGE_H_
|
||||
|
||||
#include <gtest/internal/gtest-string.h>
|
||||
#include <gtest/internal/gtest-internal.h>
|
||||
|
||||
namespace testing {
|
||||
|
||||
// The Message class works like an ostream repeater.
|
||||
//
|
||||
// Typical usage:
|
||||
//
|
||||
// 1. You stream a bunch of values to a Message object.
|
||||
// It will remember the text in a StrStream.
|
||||
// 2. Then you stream the Message object to an ostream.
|
||||
// This causes the text in the Message to be streamed
|
||||
// to the ostream.
|
||||
//
|
||||
// For example;
|
||||
//
|
||||
// testing::Message foo;
|
||||
// foo << 1 << " != " << 2;
|
||||
// std::cout << foo;
|
||||
//
|
||||
// will print "1 != 2".
|
||||
//
|
||||
// Message is not intended to be inherited from. In particular, its
|
||||
// destructor is not virtual.
|
||||
//
|
||||
// Note that StrStream behaves differently in gcc and in MSVC. You
|
||||
// can stream a NULL char pointer to it in the former, but not in the
|
||||
// latter (it causes an access violation if you do). The Message
|
||||
// class hides this difference by treating a NULL char pointer as
|
||||
// "(null)".
|
||||
class Message {
|
||||
private:
|
||||
// The type of basic IO manipulators (endl, ends, and flush) for
|
||||
// narrow streams.
|
||||
typedef std::ostream& (*BasicNarrowIoManip)(std::ostream&);
|
||||
|
||||
public:
|
||||
// Constructs an empty Message.
|
||||
// We allocate the StrStream separately because it otherwise each use of
|
||||
// ASSERT/EXPECT in a procedure adds over 200 bytes to the procedure's
|
||||
// stack frame leading to huge stack frames in some cases; gcc does not reuse
|
||||
// the stack space.
|
||||
Message() : ss_(new internal::StrStream) {}
|
||||
|
||||
// Copy constructor.
|
||||
Message(const Message& msg) : ss_(new internal::StrStream) { // NOLINT
|
||||
*ss_ << msg.GetString();
|
||||
}
|
||||
|
||||
// Constructs a Message from a C-string.
|
||||
explicit Message(const char* str) : ss_(new internal::StrStream) {
|
||||
*ss_ << str;
|
||||
}
|
||||
|
||||
~Message() { delete ss_; }
|
||||
#if GTEST_OS_SYMBIAN
|
||||
// Streams a value (either a pointer or not) to this object.
|
||||
template <typename T>
|
||||
inline Message& operator <<(const T& value) {
|
||||
StreamHelper(typename internal::is_pointer<T>::type(), value);
|
||||
return *this;
|
||||
}
|
||||
#else
|
||||
// Streams a non-pointer value to this object.
|
||||
template <typename T>
|
||||
inline Message& operator <<(const T& val) {
|
||||
::GTestStreamToHelper(ss_, val);
|
||||
return *this;
|
||||
}
|
||||
|
||||
// Streams a pointer value to this object.
|
||||
//
|
||||
// This function is an overload of the previous one. When you
|
||||
// stream a pointer to a Message, this definition will be used as it
|
||||
// is more specialized. (The C++ Standard, section
|
||||
// [temp.func.order].) If you stream a non-pointer, then the
|
||||
// previous definition will be used.
|
||||
//
|
||||
// The reason for this overload is that streaming a NULL pointer to
|
||||
// ostream is undefined behavior. Depending on the compiler, you
|
||||
// may get "0", "(nil)", "(null)", or an access violation. To
|
||||
// ensure consistent result across compilers, we always treat NULL
|
||||
// as "(null)".
|
||||
template <typename T>
|
||||
inline Message& operator <<(T* const& pointer) { // NOLINT
|
||||
if (pointer == NULL) {
|
||||
*ss_ << "(null)";
|
||||
} else {
|
||||
::GTestStreamToHelper(ss_, pointer);
|
||||
}
|
||||
return *this;
|
||||
}
|
||||
#endif // GTEST_OS_SYMBIAN
|
||||
|
||||
// Since the basic IO manipulators are overloaded for both narrow
|
||||
// and wide streams, we have to provide this specialized definition
|
||||
// of operator <<, even though its body is the same as the
|
||||
// templatized version above. Without this definition, streaming
|
||||
// endl or other basic IO manipulators to Message will confuse the
|
||||
// compiler.
|
||||
Message& operator <<(BasicNarrowIoManip val) {
|
||||
*ss_ << val;
|
||||
return *this;
|
||||
}
|
||||
|
||||
// Instead of 1/0, we want to see true/false for bool values.
|
||||
Message& operator <<(bool b) {
|
||||
return *this << (b ? "true" : "false");
|
||||
}
|
||||
|
||||
// These two overloads allow streaming a wide C string to a Message
|
||||
// using the UTF-8 encoding.
|
||||
Message& operator <<(const wchar_t* wide_c_str) {
|
||||
return *this << internal::String::ShowWideCString(wide_c_str);
|
||||
}
|
||||
Message& operator <<(wchar_t* wide_c_str) {
|
||||
return *this << internal::String::ShowWideCString(wide_c_str);
|
||||
}
|
||||
|
||||
#if GTEST_HAS_STD_WSTRING
|
||||
// Converts the given wide string to a narrow string using the UTF-8
|
||||
// encoding, and streams the result to this Message object.
|
||||
Message& operator <<(const ::std::wstring& wstr);
|
||||
#endif // GTEST_HAS_STD_WSTRING
|
||||
|
||||
#if GTEST_HAS_GLOBAL_WSTRING
|
||||
// Converts the given wide string to a narrow string using the UTF-8
|
||||
// encoding, and streams the result to this Message object.
|
||||
Message& operator <<(const ::wstring& wstr);
|
||||
#endif // GTEST_HAS_GLOBAL_WSTRING
|
||||
|
||||
// Gets the text streamed to this object so far as a String.
|
||||
// Each '\0' character in the buffer is replaced with "\\0".
|
||||
//
|
||||
// INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
|
||||
internal::String GetString() const {
|
||||
return internal::StrStreamToString(ss_);
|
||||
}
|
||||
|
||||
private:
|
||||
#if GTEST_OS_SYMBIAN
|
||||
// These are needed as the Nokia Symbian Compiler cannot decide between
|
||||
// const T& and const T* in a function template. The Nokia compiler _can_
|
||||
// decide between class template specializations for T and T*, so a
|
||||
// tr1::type_traits-like is_pointer works, and we can overload on that.
|
||||
template <typename T>
|
||||
inline void StreamHelper(internal::true_type /*dummy*/, T* pointer) {
|
||||
if (pointer == NULL) {
|
||||
*ss_ << "(null)";
|
||||
} else {
|
||||
::GTestStreamToHelper(ss_, pointer);
|
||||
}
|
||||
}
|
||||
template <typename T>
|
||||
inline void StreamHelper(internal::false_type /*dummy*/, const T& value) {
|
||||
::GTestStreamToHelper(ss_, value);
|
||||
}
|
||||
#endif // GTEST_OS_SYMBIAN
|
||||
|
||||
// We'll hold the text streamed to this object here.
|
||||
internal::StrStream* const ss_;
|
||||
|
||||
// We declare (but don't implement) this to prevent the compiler
|
||||
// from implementing the assignment operator.
|
||||
void operator=(const Message&);
|
||||
};
|
||||
|
||||
// Streams a Message to an ostream.
|
||||
inline std::ostream& operator <<(std::ostream& os, const Message& sb) {
|
||||
return os << sb.GetString();
|
||||
}
|
||||
|
||||
} // namespace testing
|
||||
|
||||
#endif // GTEST_INCLUDE_GTEST_GTEST_MESSAGE_H_
|
||||
|
||||
+1386
-1386
File diff suppressed because it is too large
Load Diff
+232
-232
@@ -1,232 +1,232 @@
|
||||
// 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)
|
||||
//
|
||||
// Utilities for testing Google Test itself and code that uses Google Test
|
||||
// (e.g. frameworks built on top of Google Test).
|
||||
|
||||
#ifndef GTEST_INCLUDE_GTEST_GTEST_SPI_H_
|
||||
#define GTEST_INCLUDE_GTEST_GTEST_SPI_H_
|
||||
|
||||
#include <gtest/gtest.h>
|
||||
|
||||
namespace testing {
|
||||
|
||||
// This helper class can be used to mock out Google Test failure reporting
|
||||
// so that we can test Google Test or code that builds on Google Test.
|
||||
//
|
||||
// An object of this class appends a TestPartResult object to the
|
||||
// TestPartResultArray object given in the constructor whenever a Google Test
|
||||
// failure is reported. It can either intercept only failures that are
|
||||
// generated in the same thread that created this object or it can intercept
|
||||
// all generated failures. The scope of this mock object can be controlled with
|
||||
// the second argument to the two arguments constructor.
|
||||
class ScopedFakeTestPartResultReporter
|
||||
: public TestPartResultReporterInterface {
|
||||
public:
|
||||
// The two possible mocking modes of this object.
|
||||
enum InterceptMode {
|
||||
INTERCEPT_ONLY_CURRENT_THREAD, // Intercepts only thread local failures.
|
||||
INTERCEPT_ALL_THREADS // Intercepts all failures.
|
||||
};
|
||||
|
||||
// The c'tor sets this object as the test part result reporter used
|
||||
// by Google Test. The 'result' parameter specifies where to report the
|
||||
// results. This reporter will only catch failures generated in the current
|
||||
// thread. DEPRECATED
|
||||
explicit ScopedFakeTestPartResultReporter(TestPartResultArray* result);
|
||||
|
||||
// Same as above, but you can choose the interception scope of this object.
|
||||
ScopedFakeTestPartResultReporter(InterceptMode intercept_mode,
|
||||
TestPartResultArray* result);
|
||||
|
||||
// The d'tor restores the previous test part result reporter.
|
||||
virtual ~ScopedFakeTestPartResultReporter();
|
||||
|
||||
// Appends the TestPartResult object to the TestPartResultArray
|
||||
// received in the constructor.
|
||||
//
|
||||
// This method is from the TestPartResultReporterInterface
|
||||
// interface.
|
||||
virtual void ReportTestPartResult(const TestPartResult& result);
|
||||
private:
|
||||
void Init();
|
||||
|
||||
const InterceptMode intercept_mode_;
|
||||
TestPartResultReporterInterface* old_reporter_;
|
||||
TestPartResultArray* const result_;
|
||||
|
||||
GTEST_DISALLOW_COPY_AND_ASSIGN_(ScopedFakeTestPartResultReporter);
|
||||
};
|
||||
|
||||
namespace internal {
|
||||
|
||||
// A helper class for implementing EXPECT_FATAL_FAILURE() and
|
||||
// EXPECT_NONFATAL_FAILURE(). Its destructor verifies that the given
|
||||
// TestPartResultArray contains exactly one failure that has the given
|
||||
// type and contains the given substring. If that's not the case, a
|
||||
// non-fatal failure will be generated.
|
||||
class SingleFailureChecker {
|
||||
public:
|
||||
// The constructor remembers the arguments.
|
||||
SingleFailureChecker(const TestPartResultArray* results,
|
||||
TestPartResult::Type type,
|
||||
const char* substr);
|
||||
~SingleFailureChecker();
|
||||
private:
|
||||
const TestPartResultArray* const results_;
|
||||
const TestPartResult::Type type_;
|
||||
const String substr_;
|
||||
|
||||
GTEST_DISALLOW_COPY_AND_ASSIGN_(SingleFailureChecker);
|
||||
};
|
||||
|
||||
} // namespace internal
|
||||
|
||||
} // namespace testing
|
||||
|
||||
// A set of macros for testing Google Test assertions or code that's expected
|
||||
// to generate Google Test fatal failures. It verifies that the given
|
||||
// statement will cause exactly one fatal Google Test failure with 'substr'
|
||||
// being part of the failure message.
|
||||
//
|
||||
// There are two different versions of this macro. EXPECT_FATAL_FAILURE only
|
||||
// affects and considers failures generated in the current thread and
|
||||
// EXPECT_FATAL_FAILURE_ON_ALL_THREADS does the same but for all threads.
|
||||
//
|
||||
// The verification of the assertion is done correctly even when the statement
|
||||
// throws an exception or aborts the current function.
|
||||
//
|
||||
// Known restrictions:
|
||||
// - 'statement' cannot reference local non-static variables or
|
||||
// non-static members of the current object.
|
||||
// - 'statement' cannot return a value.
|
||||
// - You cannot stream a failure message to this macro.
|
||||
//
|
||||
// Note that even though the implementations of the following two
|
||||
// macros are much alike, we cannot refactor them to use a common
|
||||
// helper macro, due to some peculiarity in how the preprocessor
|
||||
// works. The AcceptsMacroThatExpandsToUnprotectedComma test in
|
||||
// gtest_unittest.cc will fail to compile if we do that.
|
||||
#define EXPECT_FATAL_FAILURE(statement, substr) \
|
||||
do { \
|
||||
class GTestExpectFatalFailureHelper {\
|
||||
public:\
|
||||
static void Execute() { statement; }\
|
||||
};\
|
||||
::testing::TestPartResultArray gtest_failures;\
|
||||
::testing::internal::SingleFailureChecker gtest_checker(\
|
||||
>est_failures, ::testing::TestPartResult::kFatalFailure, (substr));\
|
||||
{\
|
||||
::testing::ScopedFakeTestPartResultReporter gtest_reporter(\
|
||||
::testing::ScopedFakeTestPartResultReporter:: \
|
||||
INTERCEPT_ONLY_CURRENT_THREAD, >est_failures);\
|
||||
GTestExpectFatalFailureHelper::Execute();\
|
||||
}\
|
||||
} while (::testing::internal::AlwaysFalse())
|
||||
|
||||
#define EXPECT_FATAL_FAILURE_ON_ALL_THREADS(statement, substr) \
|
||||
do { \
|
||||
class GTestExpectFatalFailureHelper {\
|
||||
public:\
|
||||
static void Execute() { statement; }\
|
||||
};\
|
||||
::testing::TestPartResultArray gtest_failures;\
|
||||
::testing::internal::SingleFailureChecker gtest_checker(\
|
||||
>est_failures, ::testing::TestPartResult::kFatalFailure, (substr));\
|
||||
{\
|
||||
::testing::ScopedFakeTestPartResultReporter gtest_reporter(\
|
||||
::testing::ScopedFakeTestPartResultReporter:: \
|
||||
INTERCEPT_ALL_THREADS, >est_failures);\
|
||||
GTestExpectFatalFailureHelper::Execute();\
|
||||
}\
|
||||
} while (::testing::internal::AlwaysFalse())
|
||||
|
||||
// A macro for testing Google Test assertions or code that's expected to
|
||||
// generate Google Test non-fatal failures. It asserts that the given
|
||||
// statement will cause exactly one non-fatal Google Test failure with 'substr'
|
||||
// being part of the failure message.
|
||||
//
|
||||
// There are two different versions of this macro. EXPECT_NONFATAL_FAILURE only
|
||||
// affects and considers failures generated in the current thread and
|
||||
// EXPECT_NONFATAL_FAILURE_ON_ALL_THREADS does the same but for all threads.
|
||||
//
|
||||
// 'statement' is allowed to reference local variables and members of
|
||||
// the current object.
|
||||
//
|
||||
// The verification of the assertion is done correctly even when the statement
|
||||
// throws an exception or aborts the current function.
|
||||
//
|
||||
// Known restrictions:
|
||||
// - You cannot stream a failure message to this macro.
|
||||
//
|
||||
// Note that even though the implementations of the following two
|
||||
// macros are much alike, we cannot refactor them to use a common
|
||||
// helper macro, due to some peculiarity in how the preprocessor
|
||||
// works. If we do that, the code won't compile when the user gives
|
||||
// EXPECT_NONFATAL_FAILURE() a statement that contains a macro that
|
||||
// expands to code containing an unprotected comma. The
|
||||
// AcceptsMacroThatExpandsToUnprotectedComma test in gtest_unittest.cc
|
||||
// catches that.
|
||||
//
|
||||
// For the same reason, we have to write
|
||||
// if (::testing::internal::AlwaysTrue()) { statement; }
|
||||
// instead of
|
||||
// GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement)
|
||||
// to avoid an MSVC warning on unreachable code.
|
||||
#define EXPECT_NONFATAL_FAILURE(statement, substr) \
|
||||
do {\
|
||||
::testing::TestPartResultArray gtest_failures;\
|
||||
::testing::internal::SingleFailureChecker gtest_checker(\
|
||||
>est_failures, ::testing::TestPartResult::kNonFatalFailure, \
|
||||
(substr));\
|
||||
{\
|
||||
::testing::ScopedFakeTestPartResultReporter gtest_reporter(\
|
||||
::testing::ScopedFakeTestPartResultReporter:: \
|
||||
INTERCEPT_ONLY_CURRENT_THREAD, >est_failures);\
|
||||
if (::testing::internal::AlwaysTrue()) { statement; }\
|
||||
}\
|
||||
} while (::testing::internal::AlwaysFalse())
|
||||
|
||||
#define EXPECT_NONFATAL_FAILURE_ON_ALL_THREADS(statement, substr) \
|
||||
do {\
|
||||
::testing::TestPartResultArray gtest_failures;\
|
||||
::testing::internal::SingleFailureChecker gtest_checker(\
|
||||
>est_failures, ::testing::TestPartResult::kNonFatalFailure, \
|
||||
(substr));\
|
||||
{\
|
||||
::testing::ScopedFakeTestPartResultReporter gtest_reporter(\
|
||||
::testing::ScopedFakeTestPartResultReporter::INTERCEPT_ALL_THREADS,\
|
||||
>est_failures);\
|
||||
if (::testing::internal::AlwaysTrue()) { statement; }\
|
||||
}\
|
||||
} while (::testing::internal::AlwaysFalse())
|
||||
|
||||
#endif // GTEST_INCLUDE_GTEST_GTEST_SPI_H_
|
||||
// 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)
|
||||
//
|
||||
// Utilities for testing Google Test itself and code that uses Google Test
|
||||
// (e.g. frameworks built on top of Google Test).
|
||||
|
||||
#ifndef GTEST_INCLUDE_GTEST_GTEST_SPI_H_
|
||||
#define GTEST_INCLUDE_GTEST_GTEST_SPI_H_
|
||||
|
||||
#include <gtest/gtest.h>
|
||||
|
||||
namespace testing {
|
||||
|
||||
// This helper class can be used to mock out Google Test failure reporting
|
||||
// so that we can test Google Test or code that builds on Google Test.
|
||||
//
|
||||
// An object of this class appends a TestPartResult object to the
|
||||
// TestPartResultArray object given in the constructor whenever a Google Test
|
||||
// failure is reported. It can either intercept only failures that are
|
||||
// generated in the same thread that created this object or it can intercept
|
||||
// all generated failures. The scope of this mock object can be controlled with
|
||||
// the second argument to the two arguments constructor.
|
||||
class ScopedFakeTestPartResultReporter
|
||||
: public TestPartResultReporterInterface {
|
||||
public:
|
||||
// The two possible mocking modes of this object.
|
||||
enum InterceptMode {
|
||||
INTERCEPT_ONLY_CURRENT_THREAD, // Intercepts only thread local failures.
|
||||
INTERCEPT_ALL_THREADS // Intercepts all failures.
|
||||
};
|
||||
|
||||
// The c'tor sets this object as the test part result reporter used
|
||||
// by Google Test. The 'result' parameter specifies where to report the
|
||||
// results. This reporter will only catch failures generated in the current
|
||||
// thread. DEPRECATED
|
||||
explicit ScopedFakeTestPartResultReporter(TestPartResultArray* result);
|
||||
|
||||
// Same as above, but you can choose the interception scope of this object.
|
||||
ScopedFakeTestPartResultReporter(InterceptMode intercept_mode,
|
||||
TestPartResultArray* result);
|
||||
|
||||
// The d'tor restores the previous test part result reporter.
|
||||
virtual ~ScopedFakeTestPartResultReporter();
|
||||
|
||||
// Appends the TestPartResult object to the TestPartResultArray
|
||||
// received in the constructor.
|
||||
//
|
||||
// This method is from the TestPartResultReporterInterface
|
||||
// interface.
|
||||
virtual void ReportTestPartResult(const TestPartResult& result);
|
||||
private:
|
||||
void Init();
|
||||
|
||||
const InterceptMode intercept_mode_;
|
||||
TestPartResultReporterInterface* old_reporter_;
|
||||
TestPartResultArray* const result_;
|
||||
|
||||
GTEST_DISALLOW_COPY_AND_ASSIGN_(ScopedFakeTestPartResultReporter);
|
||||
};
|
||||
|
||||
namespace internal {
|
||||
|
||||
// A helper class for implementing EXPECT_FATAL_FAILURE() and
|
||||
// EXPECT_NONFATAL_FAILURE(). Its destructor verifies that the given
|
||||
// TestPartResultArray contains exactly one failure that has the given
|
||||
// type and contains the given substring. If that's not the case, a
|
||||
// non-fatal failure will be generated.
|
||||
class SingleFailureChecker {
|
||||
public:
|
||||
// The constructor remembers the arguments.
|
||||
SingleFailureChecker(const TestPartResultArray* results,
|
||||
TestPartResult::Type type,
|
||||
const char* substr);
|
||||
~SingleFailureChecker();
|
||||
private:
|
||||
const TestPartResultArray* const results_;
|
||||
const TestPartResult::Type type_;
|
||||
const String substr_;
|
||||
|
||||
GTEST_DISALLOW_COPY_AND_ASSIGN_(SingleFailureChecker);
|
||||
};
|
||||
|
||||
} // namespace internal
|
||||
|
||||
} // namespace testing
|
||||
|
||||
// A set of macros for testing Google Test assertions or code that's expected
|
||||
// to generate Google Test fatal failures. It verifies that the given
|
||||
// statement will cause exactly one fatal Google Test failure with 'substr'
|
||||
// being part of the failure message.
|
||||
//
|
||||
// There are two different versions of this macro. EXPECT_FATAL_FAILURE only
|
||||
// affects and considers failures generated in the current thread and
|
||||
// EXPECT_FATAL_FAILURE_ON_ALL_THREADS does the same but for all threads.
|
||||
//
|
||||
// The verification of the assertion is done correctly even when the statement
|
||||
// throws an exception or aborts the current function.
|
||||
//
|
||||
// Known restrictions:
|
||||
// - 'statement' cannot reference local non-static variables or
|
||||
// non-static members of the current object.
|
||||
// - 'statement' cannot return a value.
|
||||
// - You cannot stream a failure message to this macro.
|
||||
//
|
||||
// Note that even though the implementations of the following two
|
||||
// macros are much alike, we cannot refactor them to use a common
|
||||
// helper macro, due to some peculiarity in how the preprocessor
|
||||
// works. The AcceptsMacroThatExpandsToUnprotectedComma test in
|
||||
// gtest_unittest.cc will fail to compile if we do that.
|
||||
#define EXPECT_FATAL_FAILURE(statement, substr) \
|
||||
do { \
|
||||
class GTestExpectFatalFailureHelper {\
|
||||
public:\
|
||||
static void Execute() { statement; }\
|
||||
};\
|
||||
::testing::TestPartResultArray gtest_failures;\
|
||||
::testing::internal::SingleFailureChecker gtest_checker(\
|
||||
>est_failures, ::testing::TestPartResult::kFatalFailure, (substr));\
|
||||
{\
|
||||
::testing::ScopedFakeTestPartResultReporter gtest_reporter(\
|
||||
::testing::ScopedFakeTestPartResultReporter:: \
|
||||
INTERCEPT_ONLY_CURRENT_THREAD, >est_failures);\
|
||||
GTestExpectFatalFailureHelper::Execute();\
|
||||
}\
|
||||
} while (::testing::internal::AlwaysFalse())
|
||||
|
||||
#define EXPECT_FATAL_FAILURE_ON_ALL_THREADS(statement, substr) \
|
||||
do { \
|
||||
class GTestExpectFatalFailureHelper {\
|
||||
public:\
|
||||
static void Execute() { statement; }\
|
||||
};\
|
||||
::testing::TestPartResultArray gtest_failures;\
|
||||
::testing::internal::SingleFailureChecker gtest_checker(\
|
||||
>est_failures, ::testing::TestPartResult::kFatalFailure, (substr));\
|
||||
{\
|
||||
::testing::ScopedFakeTestPartResultReporter gtest_reporter(\
|
||||
::testing::ScopedFakeTestPartResultReporter:: \
|
||||
INTERCEPT_ALL_THREADS, >est_failures);\
|
||||
GTestExpectFatalFailureHelper::Execute();\
|
||||
}\
|
||||
} while (::testing::internal::AlwaysFalse())
|
||||
|
||||
// A macro for testing Google Test assertions or code that's expected to
|
||||
// generate Google Test non-fatal failures. It asserts that the given
|
||||
// statement will cause exactly one non-fatal Google Test failure with 'substr'
|
||||
// being part of the failure message.
|
||||
//
|
||||
// There are two different versions of this macro. EXPECT_NONFATAL_FAILURE only
|
||||
// affects and considers failures generated in the current thread and
|
||||
// EXPECT_NONFATAL_FAILURE_ON_ALL_THREADS does the same but for all threads.
|
||||
//
|
||||
// 'statement' is allowed to reference local variables and members of
|
||||
// the current object.
|
||||
//
|
||||
// The verification of the assertion is done correctly even when the statement
|
||||
// throws an exception or aborts the current function.
|
||||
//
|
||||
// Known restrictions:
|
||||
// - You cannot stream a failure message to this macro.
|
||||
//
|
||||
// Note that even though the implementations of the following two
|
||||
// macros are much alike, we cannot refactor them to use a common
|
||||
// helper macro, due to some peculiarity in how the preprocessor
|
||||
// works. If we do that, the code won't compile when the user gives
|
||||
// EXPECT_NONFATAL_FAILURE() a statement that contains a macro that
|
||||
// expands to code containing an unprotected comma. The
|
||||
// AcceptsMacroThatExpandsToUnprotectedComma test in gtest_unittest.cc
|
||||
// catches that.
|
||||
//
|
||||
// For the same reason, we have to write
|
||||
// if (::testing::internal::AlwaysTrue()) { statement; }
|
||||
// instead of
|
||||
// GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement)
|
||||
// to avoid an MSVC warning on unreachable code.
|
||||
#define EXPECT_NONFATAL_FAILURE(statement, substr) \
|
||||
do {\
|
||||
::testing::TestPartResultArray gtest_failures;\
|
||||
::testing::internal::SingleFailureChecker gtest_checker(\
|
||||
>est_failures, ::testing::TestPartResult::kNonFatalFailure, \
|
||||
(substr));\
|
||||
{\
|
||||
::testing::ScopedFakeTestPartResultReporter gtest_reporter(\
|
||||
::testing::ScopedFakeTestPartResultReporter:: \
|
||||
INTERCEPT_ONLY_CURRENT_THREAD, >est_failures);\
|
||||
if (::testing::internal::AlwaysTrue()) { statement; }\
|
||||
}\
|
||||
} while (::testing::internal::AlwaysFalse())
|
||||
|
||||
#define EXPECT_NONFATAL_FAILURE_ON_ALL_THREADS(statement, substr) \
|
||||
do {\
|
||||
::testing::TestPartResultArray gtest_failures;\
|
||||
::testing::internal::SingleFailureChecker gtest_checker(\
|
||||
>est_failures, ::testing::TestPartResult::kNonFatalFailure, \
|
||||
(substr));\
|
||||
{\
|
||||
::testing::ScopedFakeTestPartResultReporter gtest_reporter(\
|
||||
::testing::ScopedFakeTestPartResultReporter::INTERCEPT_ALL_THREADS,\
|
||||
>est_failures);\
|
||||
if (::testing::internal::AlwaysTrue()) { statement; }\
|
||||
}\
|
||||
} while (::testing::internal::AlwaysFalse())
|
||||
|
||||
#endif // GTEST_INCLUDE_GTEST_GTEST_SPI_H_
|
||||
|
||||
+178
-178
@@ -1,178 +1,178 @@
|
||||
// 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.
|
||||
//
|
||||
// Author: mheule@google.com (Markus Heule)
|
||||
//
|
||||
|
||||
#ifndef GTEST_INCLUDE_GTEST_GTEST_TEST_PART_H_
|
||||
#define GTEST_INCLUDE_GTEST_GTEST_TEST_PART_H_
|
||||
|
||||
#include <iosfwd>
|
||||
#include <gtest/internal/gtest-internal.h>
|
||||
#include <gtest/internal/gtest-string.h>
|
||||
|
||||
namespace testing {
|
||||
|
||||
// A copyable object representing the result of a test part (i.e. an
|
||||
// assertion or an explicit FAIL(), ADD_FAILURE(), or SUCCESS()).
|
||||
//
|
||||
// Don't inherit from TestPartResult as its destructor is not virtual.
|
||||
class TestPartResult {
|
||||
public:
|
||||
// The possible outcomes of a test part (i.e. an assertion or an
|
||||
// explicit SUCCEED(), FAIL(), or ADD_FAILURE()).
|
||||
enum Type {
|
||||
kSuccess, // Succeeded.
|
||||
kNonFatalFailure, // Failed but the test can continue.
|
||||
kFatalFailure // Failed and the test should be terminated.
|
||||
};
|
||||
|
||||
// C'tor. TestPartResult does NOT have a default constructor.
|
||||
// Always use this constructor (with parameters) to create a
|
||||
// TestPartResult object.
|
||||
TestPartResult(Type type,
|
||||
const char* file_name,
|
||||
int line_number,
|
||||
const char* message)
|
||||
: type_(type),
|
||||
file_name_(file_name),
|
||||
line_number_(line_number),
|
||||
summary_(ExtractSummary(message)),
|
||||
message_(message) {
|
||||
}
|
||||
|
||||
// Gets the outcome of the test part.
|
||||
Type type() const { return type_; }
|
||||
|
||||
// Gets the name of the source file where the test part took place, or
|
||||
// NULL if it's unknown.
|
||||
const char* file_name() const { return file_name_.c_str(); }
|
||||
|
||||
// Gets the line in the source file where the test part took place,
|
||||
// or -1 if it's unknown.
|
||||
int line_number() const { return line_number_; }
|
||||
|
||||
// Gets the summary of the failure message.
|
||||
const char* summary() const { return summary_.c_str(); }
|
||||
|
||||
// Gets the message associated with the test part.
|
||||
const char* message() const { return message_.c_str(); }
|
||||
|
||||
// Returns true iff the test part passed.
|
||||
bool passed() const { return type_ == kSuccess; }
|
||||
|
||||
// Returns true iff the test part failed.
|
||||
bool failed() const { return type_ != kSuccess; }
|
||||
|
||||
// Returns true iff the test part non-fatally failed.
|
||||
bool nonfatally_failed() const { return type_ == kNonFatalFailure; }
|
||||
|
||||
// Returns true iff the test part fatally failed.
|
||||
bool fatally_failed() const { return type_ == kFatalFailure; }
|
||||
private:
|
||||
Type type_;
|
||||
|
||||
// Gets the summary of the failure message by omitting the stack
|
||||
// trace in it.
|
||||
static internal::String ExtractSummary(const char* message);
|
||||
|
||||
// The name of the source file where the test part took place, or
|
||||
// NULL if the source file is unknown.
|
||||
internal::String file_name_;
|
||||
// The line in the source file where the test part took place, or -1
|
||||
// if the line number is unknown.
|
||||
int line_number_;
|
||||
internal::String summary_; // The test failure summary.
|
||||
internal::String message_; // The test failure message.
|
||||
};
|
||||
|
||||
// Prints a TestPartResult object.
|
||||
std::ostream& operator<<(std::ostream& os, const TestPartResult& result);
|
||||
|
||||
// An array of TestPartResult objects.
|
||||
//
|
||||
// We define this class as we cannot use STL containers when compiling
|
||||
// Google Test with MSVC 7.1 and exceptions disabled.
|
||||
//
|
||||
// Don't inherit from TestPartResultArray as its destructor is not
|
||||
// virtual.
|
||||
class TestPartResultArray {
|
||||
public:
|
||||
TestPartResultArray();
|
||||
~TestPartResultArray();
|
||||
|
||||
// Appends the given TestPartResult to the array.
|
||||
void Append(const TestPartResult& result);
|
||||
|
||||
// Returns the TestPartResult at the given index (0-based).
|
||||
const TestPartResult& GetTestPartResult(int index) const;
|
||||
|
||||
// Returns the number of TestPartResult objects in the array.
|
||||
int size() const;
|
||||
private:
|
||||
// Internally we use a Vector to implement the array.
|
||||
internal::Vector<TestPartResult>* const array_;
|
||||
|
||||
GTEST_DISALLOW_COPY_AND_ASSIGN_(TestPartResultArray);
|
||||
};
|
||||
|
||||
// This interface knows how to report a test part result.
|
||||
class TestPartResultReporterInterface {
|
||||
public:
|
||||
virtual ~TestPartResultReporterInterface() {}
|
||||
|
||||
virtual void ReportTestPartResult(const TestPartResult& result) = 0;
|
||||
};
|
||||
|
||||
namespace internal {
|
||||
|
||||
// This helper class is used by {ASSERT|EXPECT}_NO_FATAL_FAILURE to check if a
|
||||
// statement generates new fatal failures. To do so it registers itself as the
|
||||
// current test part result reporter. Besides checking if fatal failures were
|
||||
// reported, it only delegates the reporting to the former result reporter.
|
||||
// The original result reporter is restored in the destructor.
|
||||
// INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
|
||||
class HasNewFatalFailureHelper : public TestPartResultReporterInterface {
|
||||
public:
|
||||
HasNewFatalFailureHelper();
|
||||
virtual ~HasNewFatalFailureHelper();
|
||||
virtual void ReportTestPartResult(const TestPartResult& result);
|
||||
bool has_new_fatal_failure() const { return has_new_fatal_failure_; }
|
||||
private:
|
||||
bool has_new_fatal_failure_;
|
||||
TestPartResultReporterInterface* original_reporter_;
|
||||
|
||||
GTEST_DISALLOW_COPY_AND_ASSIGN_(HasNewFatalFailureHelper);
|
||||
};
|
||||
|
||||
} // namespace internal
|
||||
|
||||
} // namespace testing
|
||||
|
||||
#endif // GTEST_INCLUDE_GTEST_GTEST_TEST_PART_H_
|
||||
// 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.
|
||||
//
|
||||
// Author: mheule@google.com (Markus Heule)
|
||||
//
|
||||
|
||||
#ifndef GTEST_INCLUDE_GTEST_GTEST_TEST_PART_H_
|
||||
#define GTEST_INCLUDE_GTEST_GTEST_TEST_PART_H_
|
||||
|
||||
#include <iosfwd>
|
||||
#include <gtest/internal/gtest-internal.h>
|
||||
#include <gtest/internal/gtest-string.h>
|
||||
|
||||
namespace testing {
|
||||
|
||||
// A copyable object representing the result of a test part (i.e. an
|
||||
// assertion or an explicit FAIL(), ADD_FAILURE(), or SUCCESS()).
|
||||
//
|
||||
// Don't inherit from TestPartResult as its destructor is not virtual.
|
||||
class TestPartResult {
|
||||
public:
|
||||
// The possible outcomes of a test part (i.e. an assertion or an
|
||||
// explicit SUCCEED(), FAIL(), or ADD_FAILURE()).
|
||||
enum Type {
|
||||
kSuccess, // Succeeded.
|
||||
kNonFatalFailure, // Failed but the test can continue.
|
||||
kFatalFailure // Failed and the test should be terminated.
|
||||
};
|
||||
|
||||
// C'tor. TestPartResult does NOT have a default constructor.
|
||||
// Always use this constructor (with parameters) to create a
|
||||
// TestPartResult object.
|
||||
TestPartResult(Type type,
|
||||
const char* file_name,
|
||||
int line_number,
|
||||
const char* message)
|
||||
: type_(type),
|
||||
file_name_(file_name),
|
||||
line_number_(line_number),
|
||||
summary_(ExtractSummary(message)),
|
||||
message_(message) {
|
||||
}
|
||||
|
||||
// Gets the outcome of the test part.
|
||||
Type type() const { return type_; }
|
||||
|
||||
// Gets the name of the source file where the test part took place, or
|
||||
// NULL if it's unknown.
|
||||
const char* file_name() const { return file_name_.c_str(); }
|
||||
|
||||
// Gets the line in the source file where the test part took place,
|
||||
// or -1 if it's unknown.
|
||||
int line_number() const { return line_number_; }
|
||||
|
||||
// Gets the summary of the failure message.
|
||||
const char* summary() const { return summary_.c_str(); }
|
||||
|
||||
// Gets the message associated with the test part.
|
||||
const char* message() const { return message_.c_str(); }
|
||||
|
||||
// Returns true iff the test part passed.
|
||||
bool passed() const { return type_ == kSuccess; }
|
||||
|
||||
// Returns true iff the test part failed.
|
||||
bool failed() const { return type_ != kSuccess; }
|
||||
|
||||
// Returns true iff the test part non-fatally failed.
|
||||
bool nonfatally_failed() const { return type_ == kNonFatalFailure; }
|
||||
|
||||
// Returns true iff the test part fatally failed.
|
||||
bool fatally_failed() const { return type_ == kFatalFailure; }
|
||||
private:
|
||||
Type type_;
|
||||
|
||||
// Gets the summary of the failure message by omitting the stack
|
||||
// trace in it.
|
||||
static internal::String ExtractSummary(const char* message);
|
||||
|
||||
// The name of the source file where the test part took place, or
|
||||
// NULL if the source file is unknown.
|
||||
internal::String file_name_;
|
||||
// The line in the source file where the test part took place, or -1
|
||||
// if the line number is unknown.
|
||||
int line_number_;
|
||||
internal::String summary_; // The test failure summary.
|
||||
internal::String message_; // The test failure message.
|
||||
};
|
||||
|
||||
// Prints a TestPartResult object.
|
||||
std::ostream& operator<<(std::ostream& os, const TestPartResult& result);
|
||||
|
||||
// An array of TestPartResult objects.
|
||||
//
|
||||
// We define this class as we cannot use STL containers when compiling
|
||||
// Google Test with MSVC 7.1 and exceptions disabled.
|
||||
//
|
||||
// Don't inherit from TestPartResultArray as its destructor is not
|
||||
// virtual.
|
||||
class TestPartResultArray {
|
||||
public:
|
||||
TestPartResultArray();
|
||||
~TestPartResultArray();
|
||||
|
||||
// Appends the given TestPartResult to the array.
|
||||
void Append(const TestPartResult& result);
|
||||
|
||||
// Returns the TestPartResult at the given index (0-based).
|
||||
const TestPartResult& GetTestPartResult(int index) const;
|
||||
|
||||
// Returns the number of TestPartResult objects in the array.
|
||||
int size() const;
|
||||
private:
|
||||
// Internally we use a Vector to implement the array.
|
||||
internal::Vector<TestPartResult>* const array_;
|
||||
|
||||
GTEST_DISALLOW_COPY_AND_ASSIGN_(TestPartResultArray);
|
||||
};
|
||||
|
||||
// This interface knows how to report a test part result.
|
||||
class TestPartResultReporterInterface {
|
||||
public:
|
||||
virtual ~TestPartResultReporterInterface() {}
|
||||
|
||||
virtual void ReportTestPartResult(const TestPartResult& result) = 0;
|
||||
};
|
||||
|
||||
namespace internal {
|
||||
|
||||
// This helper class is used by {ASSERT|EXPECT}_NO_FATAL_FAILURE to check if a
|
||||
// statement generates new fatal failures. To do so it registers itself as the
|
||||
// current test part result reporter. Besides checking if fatal failures were
|
||||
// reported, it only delegates the reporting to the former result reporter.
|
||||
// The original result reporter is restored in the destructor.
|
||||
// INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
|
||||
class HasNewFatalFailureHelper : public TestPartResultReporterInterface {
|
||||
public:
|
||||
HasNewFatalFailureHelper();
|
||||
virtual ~HasNewFatalFailureHelper();
|
||||
virtual void ReportTestPartResult(const TestPartResult& result);
|
||||
bool has_new_fatal_failure() const { return has_new_fatal_failure_; }
|
||||
private:
|
||||
bool has_new_fatal_failure_;
|
||||
TestPartResultReporterInterface* original_reporter_;
|
||||
|
||||
GTEST_DISALLOW_COPY_AND_ASSIGN_(HasNewFatalFailureHelper);
|
||||
};
|
||||
|
||||
} // namespace internal
|
||||
|
||||
} // namespace testing
|
||||
|
||||
#endif // GTEST_INCLUDE_GTEST_GTEST_TEST_PART_H_
|
||||
|
||||
+253
-253
@@ -1,253 +1,253 @@
|
||||
// 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.
|
||||
//
|
||||
// Author: wan@google.com (Zhanyong Wan)
|
||||
|
||||
#ifndef GTEST_INCLUDE_GTEST_GTEST_TYPED_TEST_H_
|
||||
#define GTEST_INCLUDE_GTEST_GTEST_TYPED_TEST_H_
|
||||
|
||||
// This header implements typed tests and type-parameterized tests.
|
||||
|
||||
// Typed (aka type-driven) tests repeat the same test for types in a
|
||||
// list. You must know which types you want to test with when writing
|
||||
// typed tests. Here's how you do it:
|
||||
|
||||
#if 0
|
||||
|
||||
// First, define a fixture class template. It should be parameterized
|
||||
// by a type. Remember to derive it from testing::Test.
|
||||
template <typename T>
|
||||
class FooTest : public testing::Test {
|
||||
public:
|
||||
...
|
||||
typedef std::list<T> List;
|
||||
static T shared_;
|
||||
T value_;
|
||||
};
|
||||
|
||||
// Next, associate a list of types with the test case, which will be
|
||||
// repeated for each type in the list. The typedef is necessary for
|
||||
// the macro to parse correctly.
|
||||
typedef testing::Types<char, int, unsigned int> MyTypes;
|
||||
TYPED_TEST_CASE(FooTest, MyTypes);
|
||||
|
||||
// If the type list contains only one type, you can write that type
|
||||
// directly without Types<...>:
|
||||
// TYPED_TEST_CASE(FooTest, int);
|
||||
|
||||
// Then, use TYPED_TEST() instead of TEST_F() to define as many typed
|
||||
// tests for this test case as you want.
|
||||
TYPED_TEST(FooTest, DoesBlah) {
|
||||
// Inside a test, refer to TypeParam to get the type parameter.
|
||||
// Since we are inside a derived class template, C++ requires use to
|
||||
// visit the members of FooTest via 'this'.
|
||||
TypeParam n = this->value_;
|
||||
|
||||
// To visit static members of the fixture, add the TestFixture::
|
||||
// prefix.
|
||||
n += TestFixture::shared_;
|
||||
|
||||
// To refer to typedefs in the fixture, add the "typename
|
||||
// TestFixture::" prefix.
|
||||
typename TestFixture::List values;
|
||||
values.push_back(n);
|
||||
...
|
||||
}
|
||||
|
||||
TYPED_TEST(FooTest, HasPropertyA) { ... }
|
||||
|
||||
#endif // 0
|
||||
|
||||
// Type-parameterized tests are abstract test patterns parameterized
|
||||
// by a type. Compared with typed tests, type-parameterized tests
|
||||
// allow you to define the test pattern without knowing what the type
|
||||
// parameters are. The defined pattern can be instantiated with
|
||||
// different types any number of times, in any number of translation
|
||||
// units.
|
||||
//
|
||||
// If you are designing an interface or concept, you can define a
|
||||
// suite of type-parameterized tests to verify properties that any
|
||||
// valid implementation of the interface/concept should have. Then,
|
||||
// each implementation can easily instantiate the test suite to verify
|
||||
// that it conforms to the requirements, without having to write
|
||||
// similar tests repeatedly. Here's an example:
|
||||
|
||||
#if 0
|
||||
|
||||
// First, define a fixture class template. It should be parameterized
|
||||
// by a type. Remember to derive it from testing::Test.
|
||||
template <typename T>
|
||||
class FooTest : public testing::Test {
|
||||
...
|
||||
};
|
||||
|
||||
// Next, declare that you will define a type-parameterized test case
|
||||
// (the _P suffix is for "parameterized" or "pattern", whichever you
|
||||
// prefer):
|
||||
TYPED_TEST_CASE_P(FooTest);
|
||||
|
||||
// Then, use TYPED_TEST_P() to define as many type-parameterized tests
|
||||
// for this type-parameterized test case as you want.
|
||||
TYPED_TEST_P(FooTest, DoesBlah) {
|
||||
// Inside a test, refer to TypeParam to get the type parameter.
|
||||
TypeParam n = 0;
|
||||
...
|
||||
}
|
||||
|
||||
TYPED_TEST_P(FooTest, HasPropertyA) { ... }
|
||||
|
||||
// Now the tricky part: you need to register all test patterns before
|
||||
// you can instantiate them. The first argument of the macro is the
|
||||
// test case name; the rest are the names of the tests in this test
|
||||
// case.
|
||||
REGISTER_TYPED_TEST_CASE_P(FooTest,
|
||||
DoesBlah, HasPropertyA);
|
||||
|
||||
// Finally, you are free to instantiate the pattern with the types you
|
||||
// want. If you put the above code in a header file, you can #include
|
||||
// it in multiple C++ source files and instantiate it multiple times.
|
||||
//
|
||||
// To distinguish different instances of the pattern, the first
|
||||
// argument to the INSTANTIATE_* macro is a prefix that will be added
|
||||
// to the actual test case name. Remember to pick unique prefixes for
|
||||
// different instances.
|
||||
typedef testing::Types<char, int, unsigned int> MyTypes;
|
||||
INSTANTIATE_TYPED_TEST_CASE_P(My, FooTest, MyTypes);
|
||||
|
||||
// If the type list contains only one type, you can write that type
|
||||
// directly without Types<...>:
|
||||
// INSTANTIATE_TYPED_TEST_CASE_P(My, FooTest, int);
|
||||
|
||||
#endif // 0
|
||||
|
||||
#include <gtest/internal/gtest-port.h>
|
||||
#include <gtest/internal/gtest-type-util.h>
|
||||
|
||||
// Implements typed tests.
|
||||
|
||||
#if GTEST_HAS_TYPED_TEST
|
||||
|
||||
// INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE.
|
||||
//
|
||||
// Expands to the name of the typedef for the type parameters of the
|
||||
// given test case.
|
||||
#define GTEST_TYPE_PARAMS_(TestCaseName) gtest_type_params_##TestCaseName##_
|
||||
|
||||
#define TYPED_TEST_CASE(CaseName, Types) \
|
||||
typedef ::testing::internal::TypeList<Types>::type \
|
||||
GTEST_TYPE_PARAMS_(CaseName)
|
||||
|
||||
#define TYPED_TEST(CaseName, TestName) \
|
||||
template <typename gtest_TypeParam_> \
|
||||
class GTEST_TEST_CLASS_NAME_(CaseName, TestName) \
|
||||
: public CaseName<gtest_TypeParam_> { \
|
||||
private: \
|
||||
typedef CaseName<gtest_TypeParam_> TestFixture; \
|
||||
typedef gtest_TypeParam_ TypeParam; \
|
||||
virtual void TestBody(); \
|
||||
}; \
|
||||
bool gtest_##CaseName##_##TestName##_registered_ = \
|
||||
::testing::internal::TypeParameterizedTest< \
|
||||
CaseName, \
|
||||
::testing::internal::TemplateSel< \
|
||||
GTEST_TEST_CLASS_NAME_(CaseName, TestName)>, \
|
||||
GTEST_TYPE_PARAMS_(CaseName)>::Register(\
|
||||
"", #CaseName, #TestName, 0); \
|
||||
template <typename gtest_TypeParam_> \
|
||||
void GTEST_TEST_CLASS_NAME_(CaseName, TestName)<gtest_TypeParam_>::TestBody()
|
||||
|
||||
#endif // GTEST_HAS_TYPED_TEST
|
||||
|
||||
// Implements type-parameterized tests.
|
||||
|
||||
#if GTEST_HAS_TYPED_TEST_P
|
||||
|
||||
// INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE.
|
||||
//
|
||||
// Expands to the namespace name that the type-parameterized tests for
|
||||
// the given type-parameterized test case are defined in. The exact
|
||||
// name of the namespace is subject to change without notice.
|
||||
#define GTEST_CASE_NAMESPACE_(TestCaseName) \
|
||||
gtest_case_##TestCaseName##_
|
||||
|
||||
// INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE.
|
||||
//
|
||||
// Expands to the name of the variable used to remember the names of
|
||||
// the defined tests in the given test case.
|
||||
#define GTEST_TYPED_TEST_CASE_P_STATE_(TestCaseName) \
|
||||
gtest_typed_test_case_p_state_##TestCaseName##_
|
||||
|
||||
// INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE DIRECTLY.
|
||||
//
|
||||
// Expands to the name of the variable used to remember the names of
|
||||
// the registered tests in the given test case.
|
||||
#define GTEST_REGISTERED_TEST_NAMES_(TestCaseName) \
|
||||
gtest_registered_test_names_##TestCaseName##_
|
||||
|
||||
// The variables defined in the type-parameterized test macros are
|
||||
// static as typically these macros are used in a .h file that can be
|
||||
// #included in multiple translation units linked together.
|
||||
#define TYPED_TEST_CASE_P(CaseName) \
|
||||
static ::testing::internal::TypedTestCasePState \
|
||||
GTEST_TYPED_TEST_CASE_P_STATE_(CaseName)
|
||||
|
||||
#define TYPED_TEST_P(CaseName, TestName) \
|
||||
namespace GTEST_CASE_NAMESPACE_(CaseName) { \
|
||||
template <typename gtest_TypeParam_> \
|
||||
class TestName : public CaseName<gtest_TypeParam_> { \
|
||||
private: \
|
||||
typedef CaseName<gtest_TypeParam_> TestFixture; \
|
||||
typedef gtest_TypeParam_ TypeParam; \
|
||||
virtual void TestBody(); \
|
||||
}; \
|
||||
static bool gtest_##TestName##_defined_ = \
|
||||
GTEST_TYPED_TEST_CASE_P_STATE_(CaseName).AddTestName(\
|
||||
__FILE__, __LINE__, #CaseName, #TestName); \
|
||||
} \
|
||||
template <typename gtest_TypeParam_> \
|
||||
void GTEST_CASE_NAMESPACE_(CaseName)::TestName<gtest_TypeParam_>::TestBody()
|
||||
|
||||
#define REGISTER_TYPED_TEST_CASE_P(CaseName, ...) \
|
||||
namespace GTEST_CASE_NAMESPACE_(CaseName) { \
|
||||
typedef ::testing::internal::Templates<__VA_ARGS__>::type gtest_AllTests_; \
|
||||
} \
|
||||
static const char* const GTEST_REGISTERED_TEST_NAMES_(CaseName) = \
|
||||
GTEST_TYPED_TEST_CASE_P_STATE_(CaseName).VerifyRegisteredTestNames(\
|
||||
__FILE__, __LINE__, #__VA_ARGS__)
|
||||
|
||||
#define INSTANTIATE_TYPED_TEST_CASE_P(Prefix, CaseName, Types) \
|
||||
bool gtest_##Prefix##_##CaseName = \
|
||||
::testing::internal::TypeParameterizedTestCase<CaseName, \
|
||||
GTEST_CASE_NAMESPACE_(CaseName)::gtest_AllTests_, \
|
||||
::testing::internal::TypeList<Types>::type>::Register(\
|
||||
#Prefix, #CaseName, GTEST_REGISTERED_TEST_NAMES_(CaseName))
|
||||
|
||||
#endif // GTEST_HAS_TYPED_TEST_P
|
||||
|
||||
#endif // GTEST_INCLUDE_GTEST_GTEST_TYPED_TEST_H_
|
||||
// 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.
|
||||
//
|
||||
// Author: wan@google.com (Zhanyong Wan)
|
||||
|
||||
#ifndef GTEST_INCLUDE_GTEST_GTEST_TYPED_TEST_H_
|
||||
#define GTEST_INCLUDE_GTEST_GTEST_TYPED_TEST_H_
|
||||
|
||||
// This header implements typed tests and type-parameterized tests.
|
||||
|
||||
// Typed (aka type-driven) tests repeat the same test for types in a
|
||||
// list. You must know which types you want to test with when writing
|
||||
// typed tests. Here's how you do it:
|
||||
|
||||
#if 0
|
||||
|
||||
// First, define a fixture class template. It should be parameterized
|
||||
// by a type. Remember to derive it from testing::Test.
|
||||
template <typename T>
|
||||
class FooTest : public testing::Test {
|
||||
public:
|
||||
...
|
||||
typedef std::list<T> List;
|
||||
static T shared_;
|
||||
T value_;
|
||||
};
|
||||
|
||||
// Next, associate a list of types with the test case, which will be
|
||||
// repeated for each type in the list. The typedef is necessary for
|
||||
// the macro to parse correctly.
|
||||
typedef testing::Types<char, int, unsigned int> MyTypes;
|
||||
TYPED_TEST_CASE(FooTest, MyTypes);
|
||||
|
||||
// If the type list contains only one type, you can write that type
|
||||
// directly without Types<...>:
|
||||
// TYPED_TEST_CASE(FooTest, int);
|
||||
|
||||
// Then, use TYPED_TEST() instead of TEST_F() to define as many typed
|
||||
// tests for this test case as you want.
|
||||
TYPED_TEST(FooTest, DoesBlah) {
|
||||
// Inside a test, refer to TypeParam to get the type parameter.
|
||||
// Since we are inside a derived class template, C++ requires use to
|
||||
// visit the members of FooTest via 'this'.
|
||||
TypeParam n = this->value_;
|
||||
|
||||
// To visit static members of the fixture, add the TestFixture::
|
||||
// prefix.
|
||||
n += TestFixture::shared_;
|
||||
|
||||
// To refer to typedefs in the fixture, add the "typename
|
||||
// TestFixture::" prefix.
|
||||
typename TestFixture::List values;
|
||||
values.push_back(n);
|
||||
...
|
||||
}
|
||||
|
||||
TYPED_TEST(FooTest, HasPropertyA) { ... }
|
||||
|
||||
#endif // 0
|
||||
|
||||
// Type-parameterized tests are abstract test patterns parameterized
|
||||
// by a type. Compared with typed tests, type-parameterized tests
|
||||
// allow you to define the test pattern without knowing what the type
|
||||
// parameters are. The defined pattern can be instantiated with
|
||||
// different types any number of times, in any number of translation
|
||||
// units.
|
||||
//
|
||||
// If you are designing an interface or concept, you can define a
|
||||
// suite of type-parameterized tests to verify properties that any
|
||||
// valid implementation of the interface/concept should have. Then,
|
||||
// each implementation can easily instantiate the test suite to verify
|
||||
// that it conforms to the requirements, without having to write
|
||||
// similar tests repeatedly. Here's an example:
|
||||
|
||||
#if 0
|
||||
|
||||
// First, define a fixture class template. It should be parameterized
|
||||
// by a type. Remember to derive it from testing::Test.
|
||||
template <typename T>
|
||||
class FooTest : public testing::Test {
|
||||
...
|
||||
};
|
||||
|
||||
// Next, declare that you will define a type-parameterized test case
|
||||
// (the _P suffix is for "parameterized" or "pattern", whichever you
|
||||
// prefer):
|
||||
TYPED_TEST_CASE_P(FooTest);
|
||||
|
||||
// Then, use TYPED_TEST_P() to define as many type-parameterized tests
|
||||
// for this type-parameterized test case as you want.
|
||||
TYPED_TEST_P(FooTest, DoesBlah) {
|
||||
// Inside a test, refer to TypeParam to get the type parameter.
|
||||
TypeParam n = 0;
|
||||
...
|
||||
}
|
||||
|
||||
TYPED_TEST_P(FooTest, HasPropertyA) { ... }
|
||||
|
||||
// Now the tricky part: you need to register all test patterns before
|
||||
// you can instantiate them. The first argument of the macro is the
|
||||
// test case name; the rest are the names of the tests in this test
|
||||
// case.
|
||||
REGISTER_TYPED_TEST_CASE_P(FooTest,
|
||||
DoesBlah, HasPropertyA);
|
||||
|
||||
// Finally, you are free to instantiate the pattern with the types you
|
||||
// want. If you put the above code in a header file, you can #include
|
||||
// it in multiple C++ source files and instantiate it multiple times.
|
||||
//
|
||||
// To distinguish different instances of the pattern, the first
|
||||
// argument to the INSTANTIATE_* macro is a prefix that will be added
|
||||
// to the actual test case name. Remember to pick unique prefixes for
|
||||
// different instances.
|
||||
typedef testing::Types<char, int, unsigned int> MyTypes;
|
||||
INSTANTIATE_TYPED_TEST_CASE_P(My, FooTest, MyTypes);
|
||||
|
||||
// If the type list contains only one type, you can write that type
|
||||
// directly without Types<...>:
|
||||
// INSTANTIATE_TYPED_TEST_CASE_P(My, FooTest, int);
|
||||
|
||||
#endif // 0
|
||||
|
||||
#include <gtest/internal/gtest-port.h>
|
||||
#include <gtest/internal/gtest-type-util.h>
|
||||
|
||||
// Implements typed tests.
|
||||
|
||||
#if GTEST_HAS_TYPED_TEST
|
||||
|
||||
// INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE.
|
||||
//
|
||||
// Expands to the name of the typedef for the type parameters of the
|
||||
// given test case.
|
||||
#define GTEST_TYPE_PARAMS_(TestCaseName) gtest_type_params_##TestCaseName##_
|
||||
|
||||
#define TYPED_TEST_CASE(CaseName, Types) \
|
||||
typedef ::testing::internal::TypeList<Types>::type \
|
||||
GTEST_TYPE_PARAMS_(CaseName)
|
||||
|
||||
#define TYPED_TEST(CaseName, TestName) \
|
||||
template <typename gtest_TypeParam_> \
|
||||
class GTEST_TEST_CLASS_NAME_(CaseName, TestName) \
|
||||
: public CaseName<gtest_TypeParam_> { \
|
||||
private: \
|
||||
typedef CaseName<gtest_TypeParam_> TestFixture; \
|
||||
typedef gtest_TypeParam_ TypeParam; \
|
||||
virtual void TestBody(); \
|
||||
}; \
|
||||
bool gtest_##CaseName##_##TestName##_registered_ = \
|
||||
::testing::internal::TypeParameterizedTest< \
|
||||
CaseName, \
|
||||
::testing::internal::TemplateSel< \
|
||||
GTEST_TEST_CLASS_NAME_(CaseName, TestName)>, \
|
||||
GTEST_TYPE_PARAMS_(CaseName)>::Register(\
|
||||
"", #CaseName, #TestName, 0); \
|
||||
template <typename gtest_TypeParam_> \
|
||||
void GTEST_TEST_CLASS_NAME_(CaseName, TestName)<gtest_TypeParam_>::TestBody()
|
||||
|
||||
#endif // GTEST_HAS_TYPED_TEST
|
||||
|
||||
// Implements type-parameterized tests.
|
||||
|
||||
#if GTEST_HAS_TYPED_TEST_P
|
||||
|
||||
// INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE.
|
||||
//
|
||||
// Expands to the namespace name that the type-parameterized tests for
|
||||
// the given type-parameterized test case are defined in. The exact
|
||||
// name of the namespace is subject to change without notice.
|
||||
#define GTEST_CASE_NAMESPACE_(TestCaseName) \
|
||||
gtest_case_##TestCaseName##_
|
||||
|
||||
// INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE.
|
||||
//
|
||||
// Expands to the name of the variable used to remember the names of
|
||||
// the defined tests in the given test case.
|
||||
#define GTEST_TYPED_TEST_CASE_P_STATE_(TestCaseName) \
|
||||
gtest_typed_test_case_p_state_##TestCaseName##_
|
||||
|
||||
// INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE DIRECTLY.
|
||||
//
|
||||
// Expands to the name of the variable used to remember the names of
|
||||
// the registered tests in the given test case.
|
||||
#define GTEST_REGISTERED_TEST_NAMES_(TestCaseName) \
|
||||
gtest_registered_test_names_##TestCaseName##_
|
||||
|
||||
// The variables defined in the type-parameterized test macros are
|
||||
// static as typically these macros are used in a .h file that can be
|
||||
// #included in multiple translation units linked together.
|
||||
#define TYPED_TEST_CASE_P(CaseName) \
|
||||
static ::testing::internal::TypedTestCasePState \
|
||||
GTEST_TYPED_TEST_CASE_P_STATE_(CaseName)
|
||||
|
||||
#define TYPED_TEST_P(CaseName, TestName) \
|
||||
namespace GTEST_CASE_NAMESPACE_(CaseName) { \
|
||||
template <typename gtest_TypeParam_> \
|
||||
class TestName : public CaseName<gtest_TypeParam_> { \
|
||||
private: \
|
||||
typedef CaseName<gtest_TypeParam_> TestFixture; \
|
||||
typedef gtest_TypeParam_ TypeParam; \
|
||||
virtual void TestBody(); \
|
||||
}; \
|
||||
static bool gtest_##TestName##_defined_ = \
|
||||
GTEST_TYPED_TEST_CASE_P_STATE_(CaseName).AddTestName(\
|
||||
__FILE__, __LINE__, #CaseName, #TestName); \
|
||||
} \
|
||||
template <typename gtest_TypeParam_> \
|
||||
void GTEST_CASE_NAMESPACE_(CaseName)::TestName<gtest_TypeParam_>::TestBody()
|
||||
|
||||
#define REGISTER_TYPED_TEST_CASE_P(CaseName, ...) \
|
||||
namespace GTEST_CASE_NAMESPACE_(CaseName) { \
|
||||
typedef ::testing::internal::Templates<__VA_ARGS__>::type gtest_AllTests_; \
|
||||
} \
|
||||
static const char* const GTEST_REGISTERED_TEST_NAMES_(CaseName) = \
|
||||
GTEST_TYPED_TEST_CASE_P_STATE_(CaseName).VerifyRegisteredTestNames(\
|
||||
__FILE__, __LINE__, #__VA_ARGS__)
|
||||
|
||||
#define INSTANTIATE_TYPED_TEST_CASE_P(Prefix, CaseName, Types) \
|
||||
bool gtest_##Prefix##_##CaseName = \
|
||||
::testing::internal::TypeParameterizedTestCase<CaseName, \
|
||||
GTEST_CASE_NAMESPACE_(CaseName)::gtest_AllTests_, \
|
||||
::testing::internal::TypeList<Types>::type>::Register(\
|
||||
#Prefix, #CaseName, GTEST_REGISTERED_TEST_NAMES_(CaseName))
|
||||
|
||||
#endif // GTEST_HAS_TYPED_TEST_P
|
||||
|
||||
#endif // GTEST_INCLUDE_GTEST_GTEST_TYPED_TEST_H_
|
||||
|
||||
+1958
-1958
File diff suppressed because it is too large
Load Diff
+368
-368
@@ -1,368 +1,368 @@
|
||||
// Copyright 2006, 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.
|
||||
|
||||
// This file is AUTOMATICALLY GENERATED on 10/02/2008 by command
|
||||
// 'gen_gtest_pred_impl.py 5'. DO NOT EDIT BY HAND!
|
||||
//
|
||||
// Implements a family of generic predicate assertion macros.
|
||||
|
||||
#ifndef GTEST_INCLUDE_GTEST_GTEST_PRED_IMPL_H_
|
||||
#define GTEST_INCLUDE_GTEST_GTEST_PRED_IMPL_H_
|
||||
|
||||
// Makes sure this header is not included before gtest.h.
|
||||
#ifndef GTEST_INCLUDE_GTEST_GTEST_H_
|
||||
#error Do not include gtest_pred_impl.h directly. Include gtest.h instead.
|
||||
#endif // GTEST_INCLUDE_GTEST_GTEST_H_
|
||||
|
||||
// This header implements a family of generic predicate assertion
|
||||
// macros:
|
||||
//
|
||||
// ASSERT_PRED_FORMAT1(pred_format, v1)
|
||||
// ASSERT_PRED_FORMAT2(pred_format, v1, v2)
|
||||
// ...
|
||||
//
|
||||
// where pred_format is a function or functor that takes n (in the
|
||||
// case of ASSERT_PRED_FORMATn) values and their source expression
|
||||
// text, and returns a testing::AssertionResult. See the definition
|
||||
// of ASSERT_EQ in gtest.h for an example.
|
||||
//
|
||||
// If you don't care about formatting, you can use the more
|
||||
// restrictive version:
|
||||
//
|
||||
// ASSERT_PRED1(pred, v1)
|
||||
// ASSERT_PRED2(pred, v1, v2)
|
||||
// ...
|
||||
//
|
||||
// where pred is an n-ary function or functor that returns bool,
|
||||
// and the values v1, v2, ..., must support the << operator for
|
||||
// streaming to std::ostream.
|
||||
//
|
||||
// We also define the EXPECT_* variations.
|
||||
//
|
||||
// For now we only support predicates whose arity is at most 5.
|
||||
// Please email googletestframework@googlegroups.com if you need
|
||||
// support for higher arities.
|
||||
|
||||
// GTEST_ASSERT_ is the basic statement to which all of the assertions
|
||||
// in this file reduce. Don't use this in your code.
|
||||
|
||||
#define GTEST_ASSERT_(expression, on_failure) \
|
||||
GTEST_AMBIGUOUS_ELSE_BLOCKER_ \
|
||||
if (const ::testing::AssertionResult gtest_ar = (expression)) \
|
||||
; \
|
||||
else \
|
||||
on_failure(gtest_ar.failure_message())
|
||||
|
||||
|
||||
// Helper function for implementing {EXPECT|ASSERT}_PRED1. Don't use
|
||||
// this in your code.
|
||||
template <typename Pred,
|
||||
typename T1>
|
||||
AssertionResult AssertPred1Helper(const char* pred_text,
|
||||
const char* e1,
|
||||
Pred pred,
|
||||
const T1& v1) {
|
||||
if (pred(v1)) return AssertionSuccess();
|
||||
|
||||
Message msg;
|
||||
msg << pred_text << "("
|
||||
<< e1 << ") evaluates to false, where"
|
||||
<< "\n" << e1 << " evaluates to " << v1;
|
||||
return AssertionFailure(msg);
|
||||
}
|
||||
|
||||
// Internal macro for implementing {EXPECT|ASSERT}_PRED_FORMAT1.
|
||||
// Don't use this in your code.
|
||||
#define GTEST_PRED_FORMAT1_(pred_format, v1, on_failure)\
|
||||
GTEST_ASSERT_(pred_format(#v1, v1),\
|
||||
on_failure)
|
||||
|
||||
// Internal macro for implementing {EXPECT|ASSERT}_PRED1. Don't use
|
||||
// this in your code.
|
||||
#define GTEST_PRED1_(pred, v1, on_failure)\
|
||||
GTEST_ASSERT_(::testing::AssertPred1Helper(#pred, \
|
||||
#v1, \
|
||||
pred, \
|
||||
v1), on_failure)
|
||||
|
||||
// Unary predicate assertion macros.
|
||||
#define EXPECT_PRED_FORMAT1(pred_format, v1) \
|
||||
GTEST_PRED_FORMAT1_(pred_format, v1, GTEST_NONFATAL_FAILURE_)
|
||||
#define EXPECT_PRED1(pred, v1) \
|
||||
GTEST_PRED1_(pred, v1, GTEST_NONFATAL_FAILURE_)
|
||||
#define ASSERT_PRED_FORMAT1(pred_format, v1) \
|
||||
GTEST_PRED_FORMAT1_(pred_format, v1, GTEST_FATAL_FAILURE_)
|
||||
#define ASSERT_PRED1(pred, v1) \
|
||||
GTEST_PRED1_(pred, v1, GTEST_FATAL_FAILURE_)
|
||||
|
||||
|
||||
|
||||
// Helper function for implementing {EXPECT|ASSERT}_PRED2. Don't use
|
||||
// this in your code.
|
||||
template <typename Pred,
|
||||
typename T1,
|
||||
typename T2>
|
||||
AssertionResult AssertPred2Helper(const char* pred_text,
|
||||
const char* e1,
|
||||
const char* e2,
|
||||
Pred pred,
|
||||
const T1& v1,
|
||||
const T2& v2) {
|
||||
if (pred(v1, v2)) return AssertionSuccess();
|
||||
|
||||
Message msg;
|
||||
msg << pred_text << "("
|
||||
<< e1 << ", "
|
||||
<< e2 << ") evaluates to false, where"
|
||||
<< "\n" << e1 << " evaluates to " << v1
|
||||
<< "\n" << e2 << " evaluates to " << v2;
|
||||
return AssertionFailure(msg);
|
||||
}
|
||||
|
||||
// Internal macro for implementing {EXPECT|ASSERT}_PRED_FORMAT2.
|
||||
// Don't use this in your code.
|
||||
#define GTEST_PRED_FORMAT2_(pred_format, v1, v2, on_failure)\
|
||||
GTEST_ASSERT_(pred_format(#v1, #v2, v1, v2),\
|
||||
on_failure)
|
||||
|
||||
// Internal macro for implementing {EXPECT|ASSERT}_PRED2. Don't use
|
||||
// this in your code.
|
||||
#define GTEST_PRED2_(pred, v1, v2, on_failure)\
|
||||
GTEST_ASSERT_(::testing::AssertPred2Helper(#pred, \
|
||||
#v1, \
|
||||
#v2, \
|
||||
pred, \
|
||||
v1, \
|
||||
v2), on_failure)
|
||||
|
||||
// Binary predicate assertion macros.
|
||||
#define EXPECT_PRED_FORMAT2(pred_format, v1, v2) \
|
||||
GTEST_PRED_FORMAT2_(pred_format, v1, v2, GTEST_NONFATAL_FAILURE_)
|
||||
#define EXPECT_PRED2(pred, v1, v2) \
|
||||
GTEST_PRED2_(pred, v1, v2, GTEST_NONFATAL_FAILURE_)
|
||||
#define ASSERT_PRED_FORMAT2(pred_format, v1, v2) \
|
||||
GTEST_PRED_FORMAT2_(pred_format, v1, v2, GTEST_FATAL_FAILURE_)
|
||||
#define ASSERT_PRED2(pred, v1, v2) \
|
||||
GTEST_PRED2_(pred, v1, v2, GTEST_FATAL_FAILURE_)
|
||||
|
||||
|
||||
|
||||
// Helper function for implementing {EXPECT|ASSERT}_PRED3. Don't use
|
||||
// this in your code.
|
||||
template <typename Pred,
|
||||
typename T1,
|
||||
typename T2,
|
||||
typename T3>
|
||||
AssertionResult AssertPred3Helper(const char* pred_text,
|
||||
const char* e1,
|
||||
const char* e2,
|
||||
const char* e3,
|
||||
Pred pred,
|
||||
const T1& v1,
|
||||
const T2& v2,
|
||||
const T3& v3) {
|
||||
if (pred(v1, v2, v3)) return AssertionSuccess();
|
||||
|
||||
Message msg;
|
||||
msg << pred_text << "("
|
||||
<< e1 << ", "
|
||||
<< e2 << ", "
|
||||
<< e3 << ") evaluates to false, where"
|
||||
<< "\n" << e1 << " evaluates to " << v1
|
||||
<< "\n" << e2 << " evaluates to " << v2
|
||||
<< "\n" << e3 << " evaluates to " << v3;
|
||||
return AssertionFailure(msg);
|
||||
}
|
||||
|
||||
// Internal macro for implementing {EXPECT|ASSERT}_PRED_FORMAT3.
|
||||
// Don't use this in your code.
|
||||
#define GTEST_PRED_FORMAT3_(pred_format, v1, v2, v3, on_failure)\
|
||||
GTEST_ASSERT_(pred_format(#v1, #v2, #v3, v1, v2, v3),\
|
||||
on_failure)
|
||||
|
||||
// Internal macro for implementing {EXPECT|ASSERT}_PRED3. Don't use
|
||||
// this in your code.
|
||||
#define GTEST_PRED3_(pred, v1, v2, v3, on_failure)\
|
||||
GTEST_ASSERT_(::testing::AssertPred3Helper(#pred, \
|
||||
#v1, \
|
||||
#v2, \
|
||||
#v3, \
|
||||
pred, \
|
||||
v1, \
|
||||
v2, \
|
||||
v3), on_failure)
|
||||
|
||||
// Ternary predicate assertion macros.
|
||||
#define EXPECT_PRED_FORMAT3(pred_format, v1, v2, v3) \
|
||||
GTEST_PRED_FORMAT3_(pred_format, v1, v2, v3, GTEST_NONFATAL_FAILURE_)
|
||||
#define EXPECT_PRED3(pred, v1, v2, v3) \
|
||||
GTEST_PRED3_(pred, v1, v2, v3, GTEST_NONFATAL_FAILURE_)
|
||||
#define ASSERT_PRED_FORMAT3(pred_format, v1, v2, v3) \
|
||||
GTEST_PRED_FORMAT3_(pred_format, v1, v2, v3, GTEST_FATAL_FAILURE_)
|
||||
#define ASSERT_PRED3(pred, v1, v2, v3) \
|
||||
GTEST_PRED3_(pred, v1, v2, v3, GTEST_FATAL_FAILURE_)
|
||||
|
||||
|
||||
|
||||
// Helper function for implementing {EXPECT|ASSERT}_PRED4. Don't use
|
||||
// this in your code.
|
||||
template <typename Pred,
|
||||
typename T1,
|
||||
typename T2,
|
||||
typename T3,
|
||||
typename T4>
|
||||
AssertionResult AssertPred4Helper(const char* pred_text,
|
||||
const char* e1,
|
||||
const char* e2,
|
||||
const char* e3,
|
||||
const char* e4,
|
||||
Pred pred,
|
||||
const T1& v1,
|
||||
const T2& v2,
|
||||
const T3& v3,
|
||||
const T4& v4) {
|
||||
if (pred(v1, v2, v3, v4)) return AssertionSuccess();
|
||||
|
||||
Message msg;
|
||||
msg << pred_text << "("
|
||||
<< e1 << ", "
|
||||
<< e2 << ", "
|
||||
<< e3 << ", "
|
||||
<< e4 << ") evaluates to false, where"
|
||||
<< "\n" << e1 << " evaluates to " << v1
|
||||
<< "\n" << e2 << " evaluates to " << v2
|
||||
<< "\n" << e3 << " evaluates to " << v3
|
||||
<< "\n" << e4 << " evaluates to " << v4;
|
||||
return AssertionFailure(msg);
|
||||
}
|
||||
|
||||
// Internal macro for implementing {EXPECT|ASSERT}_PRED_FORMAT4.
|
||||
// Don't use this in your code.
|
||||
#define GTEST_PRED_FORMAT4_(pred_format, v1, v2, v3, v4, on_failure)\
|
||||
GTEST_ASSERT_(pred_format(#v1, #v2, #v3, #v4, v1, v2, v3, v4),\
|
||||
on_failure)
|
||||
|
||||
// Internal macro for implementing {EXPECT|ASSERT}_PRED4. Don't use
|
||||
// this in your code.
|
||||
#define GTEST_PRED4_(pred, v1, v2, v3, v4, on_failure)\
|
||||
GTEST_ASSERT_(::testing::AssertPred4Helper(#pred, \
|
||||
#v1, \
|
||||
#v2, \
|
||||
#v3, \
|
||||
#v4, \
|
||||
pred, \
|
||||
v1, \
|
||||
v2, \
|
||||
v3, \
|
||||
v4), on_failure)
|
||||
|
||||
// 4-ary predicate assertion macros.
|
||||
#define EXPECT_PRED_FORMAT4(pred_format, v1, v2, v3, v4) \
|
||||
GTEST_PRED_FORMAT4_(pred_format, v1, v2, v3, v4, GTEST_NONFATAL_FAILURE_)
|
||||
#define EXPECT_PRED4(pred, v1, v2, v3, v4) \
|
||||
GTEST_PRED4_(pred, v1, v2, v3, v4, GTEST_NONFATAL_FAILURE_)
|
||||
#define ASSERT_PRED_FORMAT4(pred_format, v1, v2, v3, v4) \
|
||||
GTEST_PRED_FORMAT4_(pred_format, v1, v2, v3, v4, GTEST_FATAL_FAILURE_)
|
||||
#define ASSERT_PRED4(pred, v1, v2, v3, v4) \
|
||||
GTEST_PRED4_(pred, v1, v2, v3, v4, GTEST_FATAL_FAILURE_)
|
||||
|
||||
|
||||
|
||||
// Helper function for implementing {EXPECT|ASSERT}_PRED5. Don't use
|
||||
// this in your code.
|
||||
template <typename Pred,
|
||||
typename T1,
|
||||
typename T2,
|
||||
typename T3,
|
||||
typename T4,
|
||||
typename T5>
|
||||
AssertionResult AssertPred5Helper(const char* pred_text,
|
||||
const char* e1,
|
||||
const char* e2,
|
||||
const char* e3,
|
||||
const char* e4,
|
||||
const char* e5,
|
||||
Pred pred,
|
||||
const T1& v1,
|
||||
const T2& v2,
|
||||
const T3& v3,
|
||||
const T4& v4,
|
||||
const T5& v5) {
|
||||
if (pred(v1, v2, v3, v4, v5)) return AssertionSuccess();
|
||||
|
||||
Message msg;
|
||||
msg << pred_text << "("
|
||||
<< e1 << ", "
|
||||
<< e2 << ", "
|
||||
<< e3 << ", "
|
||||
<< e4 << ", "
|
||||
<< e5 << ") evaluates to false, where"
|
||||
<< "\n" << e1 << " evaluates to " << v1
|
||||
<< "\n" << e2 << " evaluates to " << v2
|
||||
<< "\n" << e3 << " evaluates to " << v3
|
||||
<< "\n" << e4 << " evaluates to " << v4
|
||||
<< "\n" << e5 << " evaluates to " << v5;
|
||||
return AssertionFailure(msg);
|
||||
}
|
||||
|
||||
// Internal macro for implementing {EXPECT|ASSERT}_PRED_FORMAT5.
|
||||
// Don't use this in your code.
|
||||
#define GTEST_PRED_FORMAT5_(pred_format, v1, v2, v3, v4, v5, on_failure)\
|
||||
GTEST_ASSERT_(pred_format(#v1, #v2, #v3, #v4, #v5, v1, v2, v3, v4, v5),\
|
||||
on_failure)
|
||||
|
||||
// Internal macro for implementing {EXPECT|ASSERT}_PRED5. Don't use
|
||||
// this in your code.
|
||||
#define GTEST_PRED5_(pred, v1, v2, v3, v4, v5, on_failure)\
|
||||
GTEST_ASSERT_(::testing::AssertPred5Helper(#pred, \
|
||||
#v1, \
|
||||
#v2, \
|
||||
#v3, \
|
||||
#v4, \
|
||||
#v5, \
|
||||
pred, \
|
||||
v1, \
|
||||
v2, \
|
||||
v3, \
|
||||
v4, \
|
||||
v5), on_failure)
|
||||
|
||||
// 5-ary predicate assertion macros.
|
||||
#define EXPECT_PRED_FORMAT5(pred_format, v1, v2, v3, v4, v5) \
|
||||
GTEST_PRED_FORMAT5_(pred_format, v1, v2, v3, v4, v5, GTEST_NONFATAL_FAILURE_)
|
||||
#define EXPECT_PRED5(pred, v1, v2, v3, v4, v5) \
|
||||
GTEST_PRED5_(pred, v1, v2, v3, v4, v5, GTEST_NONFATAL_FAILURE_)
|
||||
#define ASSERT_PRED_FORMAT5(pred_format, v1, v2, v3, v4, v5) \
|
||||
GTEST_PRED_FORMAT5_(pred_format, v1, v2, v3, v4, v5, GTEST_FATAL_FAILURE_)
|
||||
#define ASSERT_PRED5(pred, v1, v2, v3, v4, v5) \
|
||||
GTEST_PRED5_(pred, v1, v2, v3, v4, v5, GTEST_FATAL_FAILURE_)
|
||||
|
||||
|
||||
|
||||
#endif // GTEST_INCLUDE_GTEST_GTEST_PRED_IMPL_H_
|
||||
// Copyright 2006, 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.
|
||||
|
||||
// This file is AUTOMATICALLY GENERATED on 10/02/2008 by command
|
||||
// 'gen_gtest_pred_impl.py 5'. DO NOT EDIT BY HAND!
|
||||
//
|
||||
// Implements a family of generic predicate assertion macros.
|
||||
|
||||
#ifndef GTEST_INCLUDE_GTEST_GTEST_PRED_IMPL_H_
|
||||
#define GTEST_INCLUDE_GTEST_GTEST_PRED_IMPL_H_
|
||||
|
||||
// Makes sure this header is not included before gtest.h.
|
||||
#ifndef GTEST_INCLUDE_GTEST_GTEST_H_
|
||||
#error Do not include gtest_pred_impl.h directly. Include gtest.h instead.
|
||||
#endif // GTEST_INCLUDE_GTEST_GTEST_H_
|
||||
|
||||
// This header implements a family of generic predicate assertion
|
||||
// macros:
|
||||
//
|
||||
// ASSERT_PRED_FORMAT1(pred_format, v1)
|
||||
// ASSERT_PRED_FORMAT2(pred_format, v1, v2)
|
||||
// ...
|
||||
//
|
||||
// where pred_format is a function or functor that takes n (in the
|
||||
// case of ASSERT_PRED_FORMATn) values and their source expression
|
||||
// text, and returns a testing::AssertionResult. See the definition
|
||||
// of ASSERT_EQ in gtest.h for an example.
|
||||
//
|
||||
// If you don't care about formatting, you can use the more
|
||||
// restrictive version:
|
||||
//
|
||||
// ASSERT_PRED1(pred, v1)
|
||||
// ASSERT_PRED2(pred, v1, v2)
|
||||
// ...
|
||||
//
|
||||
// where pred is an n-ary function or functor that returns bool,
|
||||
// and the values v1, v2, ..., must support the << operator for
|
||||
// streaming to std::ostream.
|
||||
//
|
||||
// We also define the EXPECT_* variations.
|
||||
//
|
||||
// For now we only support predicates whose arity is at most 5.
|
||||
// Please email googletestframework@googlegroups.com if you need
|
||||
// support for higher arities.
|
||||
|
||||
// GTEST_ASSERT_ is the basic statement to which all of the assertions
|
||||
// in this file reduce. Don't use this in your code.
|
||||
|
||||
#define GTEST_ASSERT_(expression, on_failure) \
|
||||
GTEST_AMBIGUOUS_ELSE_BLOCKER_ \
|
||||
if (const ::testing::AssertionResult gtest_ar = (expression)) \
|
||||
; \
|
||||
else \
|
||||
on_failure(gtest_ar.failure_message())
|
||||
|
||||
|
||||
// Helper function for implementing {EXPECT|ASSERT}_PRED1. Don't use
|
||||
// this in your code.
|
||||
template <typename Pred,
|
||||
typename T1>
|
||||
AssertionResult AssertPred1Helper(const char* pred_text,
|
||||
const char* e1,
|
||||
Pred pred,
|
||||
const T1& v1) {
|
||||
if (pred(v1)) return AssertionSuccess();
|
||||
|
||||
Message msg;
|
||||
msg << pred_text << "("
|
||||
<< e1 << ") evaluates to false, where"
|
||||
<< "\n" << e1 << " evaluates to " << v1;
|
||||
return AssertionFailure(msg);
|
||||
}
|
||||
|
||||
// Internal macro for implementing {EXPECT|ASSERT}_PRED_FORMAT1.
|
||||
// Don't use this in your code.
|
||||
#define GTEST_PRED_FORMAT1_(pred_format, v1, on_failure)\
|
||||
GTEST_ASSERT_(pred_format(#v1, v1),\
|
||||
on_failure)
|
||||
|
||||
// Internal macro for implementing {EXPECT|ASSERT}_PRED1. Don't use
|
||||
// this in your code.
|
||||
#define GTEST_PRED1_(pred, v1, on_failure)\
|
||||
GTEST_ASSERT_(::testing::AssertPred1Helper(#pred, \
|
||||
#v1, \
|
||||
pred, \
|
||||
v1), on_failure)
|
||||
|
||||
// Unary predicate assertion macros.
|
||||
#define EXPECT_PRED_FORMAT1(pred_format, v1) \
|
||||
GTEST_PRED_FORMAT1_(pred_format, v1, GTEST_NONFATAL_FAILURE_)
|
||||
#define EXPECT_PRED1(pred, v1) \
|
||||
GTEST_PRED1_(pred, v1, GTEST_NONFATAL_FAILURE_)
|
||||
#define ASSERT_PRED_FORMAT1(pred_format, v1) \
|
||||
GTEST_PRED_FORMAT1_(pred_format, v1, GTEST_FATAL_FAILURE_)
|
||||
#define ASSERT_PRED1(pred, v1) \
|
||||
GTEST_PRED1_(pred, v1, GTEST_FATAL_FAILURE_)
|
||||
|
||||
|
||||
|
||||
// Helper function for implementing {EXPECT|ASSERT}_PRED2. Don't use
|
||||
// this in your code.
|
||||
template <typename Pred,
|
||||
typename T1,
|
||||
typename T2>
|
||||
AssertionResult AssertPred2Helper(const char* pred_text,
|
||||
const char* e1,
|
||||
const char* e2,
|
||||
Pred pred,
|
||||
const T1& v1,
|
||||
const T2& v2) {
|
||||
if (pred(v1, v2)) return AssertionSuccess();
|
||||
|
||||
Message msg;
|
||||
msg << pred_text << "("
|
||||
<< e1 << ", "
|
||||
<< e2 << ") evaluates to false, where"
|
||||
<< "\n" << e1 << " evaluates to " << v1
|
||||
<< "\n" << e2 << " evaluates to " << v2;
|
||||
return AssertionFailure(msg);
|
||||
}
|
||||
|
||||
// Internal macro for implementing {EXPECT|ASSERT}_PRED_FORMAT2.
|
||||
// Don't use this in your code.
|
||||
#define GTEST_PRED_FORMAT2_(pred_format, v1, v2, on_failure)\
|
||||
GTEST_ASSERT_(pred_format(#v1, #v2, v1, v2),\
|
||||
on_failure)
|
||||
|
||||
// Internal macro for implementing {EXPECT|ASSERT}_PRED2. Don't use
|
||||
// this in your code.
|
||||
#define GTEST_PRED2_(pred, v1, v2, on_failure)\
|
||||
GTEST_ASSERT_(::testing::AssertPred2Helper(#pred, \
|
||||
#v1, \
|
||||
#v2, \
|
||||
pred, \
|
||||
v1, \
|
||||
v2), on_failure)
|
||||
|
||||
// Binary predicate assertion macros.
|
||||
#define EXPECT_PRED_FORMAT2(pred_format, v1, v2) \
|
||||
GTEST_PRED_FORMAT2_(pred_format, v1, v2, GTEST_NONFATAL_FAILURE_)
|
||||
#define EXPECT_PRED2(pred, v1, v2) \
|
||||
GTEST_PRED2_(pred, v1, v2, GTEST_NONFATAL_FAILURE_)
|
||||
#define ASSERT_PRED_FORMAT2(pred_format, v1, v2) \
|
||||
GTEST_PRED_FORMAT2_(pred_format, v1, v2, GTEST_FATAL_FAILURE_)
|
||||
#define ASSERT_PRED2(pred, v1, v2) \
|
||||
GTEST_PRED2_(pred, v1, v2, GTEST_FATAL_FAILURE_)
|
||||
|
||||
|
||||
|
||||
// Helper function for implementing {EXPECT|ASSERT}_PRED3. Don't use
|
||||
// this in your code.
|
||||
template <typename Pred,
|
||||
typename T1,
|
||||
typename T2,
|
||||
typename T3>
|
||||
AssertionResult AssertPred3Helper(const char* pred_text,
|
||||
const char* e1,
|
||||
const char* e2,
|
||||
const char* e3,
|
||||
Pred pred,
|
||||
const T1& v1,
|
||||
const T2& v2,
|
||||
const T3& v3) {
|
||||
if (pred(v1, v2, v3)) return AssertionSuccess();
|
||||
|
||||
Message msg;
|
||||
msg << pred_text << "("
|
||||
<< e1 << ", "
|
||||
<< e2 << ", "
|
||||
<< e3 << ") evaluates to false, where"
|
||||
<< "\n" << e1 << " evaluates to " << v1
|
||||
<< "\n" << e2 << " evaluates to " << v2
|
||||
<< "\n" << e3 << " evaluates to " << v3;
|
||||
return AssertionFailure(msg);
|
||||
}
|
||||
|
||||
// Internal macro for implementing {EXPECT|ASSERT}_PRED_FORMAT3.
|
||||
// Don't use this in your code.
|
||||
#define GTEST_PRED_FORMAT3_(pred_format, v1, v2, v3, on_failure)\
|
||||
GTEST_ASSERT_(pred_format(#v1, #v2, #v3, v1, v2, v3),\
|
||||
on_failure)
|
||||
|
||||
// Internal macro for implementing {EXPECT|ASSERT}_PRED3. Don't use
|
||||
// this in your code.
|
||||
#define GTEST_PRED3_(pred, v1, v2, v3, on_failure)\
|
||||
GTEST_ASSERT_(::testing::AssertPred3Helper(#pred, \
|
||||
#v1, \
|
||||
#v2, \
|
||||
#v3, \
|
||||
pred, \
|
||||
v1, \
|
||||
v2, \
|
||||
v3), on_failure)
|
||||
|
||||
// Ternary predicate assertion macros.
|
||||
#define EXPECT_PRED_FORMAT3(pred_format, v1, v2, v3) \
|
||||
GTEST_PRED_FORMAT3_(pred_format, v1, v2, v3, GTEST_NONFATAL_FAILURE_)
|
||||
#define EXPECT_PRED3(pred, v1, v2, v3) \
|
||||
GTEST_PRED3_(pred, v1, v2, v3, GTEST_NONFATAL_FAILURE_)
|
||||
#define ASSERT_PRED_FORMAT3(pred_format, v1, v2, v3) \
|
||||
GTEST_PRED_FORMAT3_(pred_format, v1, v2, v3, GTEST_FATAL_FAILURE_)
|
||||
#define ASSERT_PRED3(pred, v1, v2, v3) \
|
||||
GTEST_PRED3_(pred, v1, v2, v3, GTEST_FATAL_FAILURE_)
|
||||
|
||||
|
||||
|
||||
// Helper function for implementing {EXPECT|ASSERT}_PRED4. Don't use
|
||||
// this in your code.
|
||||
template <typename Pred,
|
||||
typename T1,
|
||||
typename T2,
|
||||
typename T3,
|
||||
typename T4>
|
||||
AssertionResult AssertPred4Helper(const char* pred_text,
|
||||
const char* e1,
|
||||
const char* e2,
|
||||
const char* e3,
|
||||
const char* e4,
|
||||
Pred pred,
|
||||
const T1& v1,
|
||||
const T2& v2,
|
||||
const T3& v3,
|
||||
const T4& v4) {
|
||||
if (pred(v1, v2, v3, v4)) return AssertionSuccess();
|
||||
|
||||
Message msg;
|
||||
msg << pred_text << "("
|
||||
<< e1 << ", "
|
||||
<< e2 << ", "
|
||||
<< e3 << ", "
|
||||
<< e4 << ") evaluates to false, where"
|
||||
<< "\n" << e1 << " evaluates to " << v1
|
||||
<< "\n" << e2 << " evaluates to " << v2
|
||||
<< "\n" << e3 << " evaluates to " << v3
|
||||
<< "\n" << e4 << " evaluates to " << v4;
|
||||
return AssertionFailure(msg);
|
||||
}
|
||||
|
||||
// Internal macro for implementing {EXPECT|ASSERT}_PRED_FORMAT4.
|
||||
// Don't use this in your code.
|
||||
#define GTEST_PRED_FORMAT4_(pred_format, v1, v2, v3, v4, on_failure)\
|
||||
GTEST_ASSERT_(pred_format(#v1, #v2, #v3, #v4, v1, v2, v3, v4),\
|
||||
on_failure)
|
||||
|
||||
// Internal macro for implementing {EXPECT|ASSERT}_PRED4. Don't use
|
||||
// this in your code.
|
||||
#define GTEST_PRED4_(pred, v1, v2, v3, v4, on_failure)\
|
||||
GTEST_ASSERT_(::testing::AssertPred4Helper(#pred, \
|
||||
#v1, \
|
||||
#v2, \
|
||||
#v3, \
|
||||
#v4, \
|
||||
pred, \
|
||||
v1, \
|
||||
v2, \
|
||||
v3, \
|
||||
v4), on_failure)
|
||||
|
||||
// 4-ary predicate assertion macros.
|
||||
#define EXPECT_PRED_FORMAT4(pred_format, v1, v2, v3, v4) \
|
||||
GTEST_PRED_FORMAT4_(pred_format, v1, v2, v3, v4, GTEST_NONFATAL_FAILURE_)
|
||||
#define EXPECT_PRED4(pred, v1, v2, v3, v4) \
|
||||
GTEST_PRED4_(pred, v1, v2, v3, v4, GTEST_NONFATAL_FAILURE_)
|
||||
#define ASSERT_PRED_FORMAT4(pred_format, v1, v2, v3, v4) \
|
||||
GTEST_PRED_FORMAT4_(pred_format, v1, v2, v3, v4, GTEST_FATAL_FAILURE_)
|
||||
#define ASSERT_PRED4(pred, v1, v2, v3, v4) \
|
||||
GTEST_PRED4_(pred, v1, v2, v3, v4, GTEST_FATAL_FAILURE_)
|
||||
|
||||
|
||||
|
||||
// Helper function for implementing {EXPECT|ASSERT}_PRED5. Don't use
|
||||
// this in your code.
|
||||
template <typename Pred,
|
||||
typename T1,
|
||||
typename T2,
|
||||
typename T3,
|
||||
typename T4,
|
||||
typename T5>
|
||||
AssertionResult AssertPred5Helper(const char* pred_text,
|
||||
const char* e1,
|
||||
const char* e2,
|
||||
const char* e3,
|
||||
const char* e4,
|
||||
const char* e5,
|
||||
Pred pred,
|
||||
const T1& v1,
|
||||
const T2& v2,
|
||||
const T3& v3,
|
||||
const T4& v4,
|
||||
const T5& v5) {
|
||||
if (pred(v1, v2, v3, v4, v5)) return AssertionSuccess();
|
||||
|
||||
Message msg;
|
||||
msg << pred_text << "("
|
||||
<< e1 << ", "
|
||||
<< e2 << ", "
|
||||
<< e3 << ", "
|
||||
<< e4 << ", "
|
||||
<< e5 << ") evaluates to false, where"
|
||||
<< "\n" << e1 << " evaluates to " << v1
|
||||
<< "\n" << e2 << " evaluates to " << v2
|
||||
<< "\n" << e3 << " evaluates to " << v3
|
||||
<< "\n" << e4 << " evaluates to " << v4
|
||||
<< "\n" << e5 << " evaluates to " << v5;
|
||||
return AssertionFailure(msg);
|
||||
}
|
||||
|
||||
// Internal macro for implementing {EXPECT|ASSERT}_PRED_FORMAT5.
|
||||
// Don't use this in your code.
|
||||
#define GTEST_PRED_FORMAT5_(pred_format, v1, v2, v3, v4, v5, on_failure)\
|
||||
GTEST_ASSERT_(pred_format(#v1, #v2, #v3, #v4, #v5, v1, v2, v3, v4, v5),\
|
||||
on_failure)
|
||||
|
||||
// Internal macro for implementing {EXPECT|ASSERT}_PRED5. Don't use
|
||||
// this in your code.
|
||||
#define GTEST_PRED5_(pred, v1, v2, v3, v4, v5, on_failure)\
|
||||
GTEST_ASSERT_(::testing::AssertPred5Helper(#pred, \
|
||||
#v1, \
|
||||
#v2, \
|
||||
#v3, \
|
||||
#v4, \
|
||||
#v5, \
|
||||
pred, \
|
||||
v1, \
|
||||
v2, \
|
||||
v3, \
|
||||
v4, \
|
||||
v5), on_failure)
|
||||
|
||||
// 5-ary predicate assertion macros.
|
||||
#define EXPECT_PRED_FORMAT5(pred_format, v1, v2, v3, v4, v5) \
|
||||
GTEST_PRED_FORMAT5_(pred_format, v1, v2, v3, v4, v5, GTEST_NONFATAL_FAILURE_)
|
||||
#define EXPECT_PRED5(pred, v1, v2, v3, v4, v5) \
|
||||
GTEST_PRED5_(pred, v1, v2, v3, v4, v5, GTEST_NONFATAL_FAILURE_)
|
||||
#define ASSERT_PRED_FORMAT5(pred_format, v1, v2, v3, v4, v5) \
|
||||
GTEST_PRED_FORMAT5_(pred_format, v1, v2, v3, v4, v5, GTEST_FATAL_FAILURE_)
|
||||
#define ASSERT_PRED5(pred, v1, v2, v3, v4, v5) \
|
||||
GTEST_PRED5_(pred, v1, v2, v3, v4, v5, GTEST_FATAL_FAILURE_)
|
||||
|
||||
|
||||
|
||||
#endif // GTEST_INCLUDE_GTEST_GTEST_PRED_IMPL_H_
|
||||
|
||||
@@ -1,58 +1,58 @@
|
||||
// Copyright 2006, 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 C++ Testing Framework definitions useful in production code.
|
||||
|
||||
#ifndef GTEST_INCLUDE_GTEST_GTEST_PROD_H_
|
||||
#define GTEST_INCLUDE_GTEST_GTEST_PROD_H_
|
||||
|
||||
// When you need to test the private or protected members of a class,
|
||||
// use the FRIEND_TEST macro to declare your tests as friends of the
|
||||
// class. For example:
|
||||
//
|
||||
// class MyClass {
|
||||
// private:
|
||||
// void MyMethod();
|
||||
// FRIEND_TEST(MyClassTest, MyMethod);
|
||||
// };
|
||||
//
|
||||
// class MyClassTest : public testing::Test {
|
||||
// // ...
|
||||
// };
|
||||
//
|
||||
// TEST_F(MyClassTest, MyMethod) {
|
||||
// // Can call MyClass::MyMethod() here.
|
||||
// }
|
||||
|
||||
#define FRIEND_TEST(test_case_name, test_name)\
|
||||
friend class test_case_name##_##test_name##_Test
|
||||
|
||||
#endif // GTEST_INCLUDE_GTEST_GTEST_PROD_H_
|
||||
// Copyright 2006, 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 C++ Testing Framework definitions useful in production code.
|
||||
|
||||
#ifndef GTEST_INCLUDE_GTEST_GTEST_PROD_H_
|
||||
#define GTEST_INCLUDE_GTEST_GTEST_PROD_H_
|
||||
|
||||
// When you need to test the private or protected members of a class,
|
||||
// use the FRIEND_TEST macro to declare your tests as friends of the
|
||||
// class. For example:
|
||||
//
|
||||
// class MyClass {
|
||||
// private:
|
||||
// void MyMethod();
|
||||
// FRIEND_TEST(MyClassTest, MyMethod);
|
||||
// };
|
||||
//
|
||||
// class MyClassTest : public testing::Test {
|
||||
// // ...
|
||||
// };
|
||||
//
|
||||
// TEST_F(MyClassTest, MyMethod) {
|
||||
// // Can call MyClass::MyMethod() here.
|
||||
// }
|
||||
|
||||
#define FRIEND_TEST(test_case_name, test_name)\
|
||||
friend class test_case_name##_##test_name##_Test
|
||||
|
||||
#endif // GTEST_INCLUDE_GTEST_GTEST_PROD_H_
|
||||
|
||||
+274
-274
@@ -1,274 +1,274 @@
|
||||
// Copyright 2005, 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.
|
||||
//
|
||||
// Authors: wan@google.com (Zhanyong Wan), eefacm@gmail.com (Sean Mcafee)
|
||||
//
|
||||
// The Google C++ Testing Framework (Google Test)
|
||||
//
|
||||
// This header file defines internal utilities needed for implementing
|
||||
// death tests. They are subject to change without notice.
|
||||
|
||||
#ifndef GTEST_INCLUDE_GTEST_INTERNAL_GTEST_DEATH_TEST_INTERNAL_H_
|
||||
#define GTEST_INCLUDE_GTEST_INTERNAL_GTEST_DEATH_TEST_INTERNAL_H_
|
||||
|
||||
#include <gtest/internal/gtest-internal.h>
|
||||
|
||||
namespace testing {
|
||||
namespace internal {
|
||||
|
||||
GTEST_DECLARE_string_(internal_run_death_test);
|
||||
|
||||
// Names of the flags (needed for parsing Google Test flags).
|
||||
const char kDeathTestStyleFlag[] = "death_test_style";
|
||||
const char kDeathTestUseFork[] = "death_test_use_fork";
|
||||
const char kInternalRunDeathTestFlag[] = "internal_run_death_test";
|
||||
|
||||
#if GTEST_HAS_DEATH_TEST
|
||||
|
||||
// DeathTest is a class that hides much of the complexity of the
|
||||
// GTEST_DEATH_TEST_ macro. It is abstract; its static Create method
|
||||
// returns a concrete class that depends on the prevailing death test
|
||||
// style, as defined by the --gtest_death_test_style and/or
|
||||
// --gtest_internal_run_death_test flags.
|
||||
|
||||
// In describing the results of death tests, these terms are used with
|
||||
// the corresponding definitions:
|
||||
//
|
||||
// exit status: The integer exit information in the format specified
|
||||
// by wait(2)
|
||||
// exit code: The integer code passed to exit(3), _exit(2), or
|
||||
// returned from main()
|
||||
class DeathTest {
|
||||
public:
|
||||
// Create returns false if there was an error determining the
|
||||
// appropriate action to take for the current death test; for example,
|
||||
// if the gtest_death_test_style flag is set to an invalid value.
|
||||
// The LastMessage method will return a more detailed message in that
|
||||
// case. Otherwise, the DeathTest pointer pointed to by the "test"
|
||||
// argument is set. If the death test should be skipped, the pointer
|
||||
// is set to NULL; otherwise, it is set to the address of a new concrete
|
||||
// DeathTest object that controls the execution of the current test.
|
||||
static bool Create(const char* statement, const RE* regex,
|
||||
const char* file, int line, DeathTest** test);
|
||||
DeathTest();
|
||||
virtual ~DeathTest() { }
|
||||
|
||||
// A helper class that aborts a death test when it's deleted.
|
||||
class ReturnSentinel {
|
||||
public:
|
||||
explicit ReturnSentinel(DeathTest* test) : test_(test) { }
|
||||
~ReturnSentinel() { test_->Abort(TEST_ENCOUNTERED_RETURN_STATEMENT); }
|
||||
private:
|
||||
DeathTest* const test_;
|
||||
GTEST_DISALLOW_COPY_AND_ASSIGN_(ReturnSentinel);
|
||||
} GTEST_ATTRIBUTE_UNUSED_;
|
||||
|
||||
// An enumeration of possible roles that may be taken when a death
|
||||
// test is encountered. EXECUTE means that the death test logic should
|
||||
// be executed immediately. OVERSEE means that the program should prepare
|
||||
// the appropriate environment for a child process to execute the death
|
||||
// test, then wait for it to complete.
|
||||
enum TestRole { OVERSEE_TEST, EXECUTE_TEST };
|
||||
|
||||
// An enumeration of the two reasons that a test might be aborted.
|
||||
enum AbortReason { TEST_ENCOUNTERED_RETURN_STATEMENT, TEST_DID_NOT_DIE };
|
||||
|
||||
// Assumes one of the above roles.
|
||||
virtual TestRole AssumeRole() = 0;
|
||||
|
||||
// Waits for the death test to finish and returns its status.
|
||||
virtual int Wait() = 0;
|
||||
|
||||
// Returns true if the death test passed; that is, the test process
|
||||
// exited during the test, its exit status matches a user-supplied
|
||||
// predicate, and its stderr output matches a user-supplied regular
|
||||
// expression.
|
||||
// The user-supplied predicate may be a macro expression rather
|
||||
// than a function pointer or functor, or else Wait and Passed could
|
||||
// be combined.
|
||||
virtual bool Passed(bool exit_status_ok) = 0;
|
||||
|
||||
// Signals that the death test did not die as expected.
|
||||
virtual void Abort(AbortReason reason) = 0;
|
||||
|
||||
// Returns a human-readable outcome message regarding the outcome of
|
||||
// the last death test.
|
||||
static const char* LastMessage();
|
||||
|
||||
static void set_last_death_test_message(const String& message);
|
||||
|
||||
private:
|
||||
// A string containing a description of the outcome of the last death test.
|
||||
static String last_death_test_message_;
|
||||
|
||||
GTEST_DISALLOW_COPY_AND_ASSIGN_(DeathTest);
|
||||
};
|
||||
|
||||
// Factory interface for death tests. May be mocked out for testing.
|
||||
class DeathTestFactory {
|
||||
public:
|
||||
virtual ~DeathTestFactory() { }
|
||||
virtual bool Create(const char* statement, const RE* regex,
|
||||
const char* file, int line, DeathTest** test) = 0;
|
||||
};
|
||||
|
||||
// A concrete DeathTestFactory implementation for normal use.
|
||||
class DefaultDeathTestFactory : public DeathTestFactory {
|
||||
public:
|
||||
virtual bool Create(const char* statement, const RE* regex,
|
||||
const char* file, int line, DeathTest** test);
|
||||
};
|
||||
|
||||
// Returns true if exit_status describes a process that was terminated
|
||||
// by a signal, or exited normally with a nonzero exit code.
|
||||
bool ExitedUnsuccessfully(int exit_status);
|
||||
|
||||
// This macro is for implementing ASSERT_DEATH*, EXPECT_DEATH*,
|
||||
// ASSERT_EXIT*, and EXPECT_EXIT*.
|
||||
#define GTEST_DEATH_TEST_(statement, predicate, regex, fail) \
|
||||
GTEST_AMBIGUOUS_ELSE_BLOCKER_ \
|
||||
if (::testing::internal::AlwaysTrue()) { \
|
||||
const ::testing::internal::RE& gtest_regex = (regex); \
|
||||
::testing::internal::DeathTest* gtest_dt; \
|
||||
if (!::testing::internal::DeathTest::Create(#statement, >est_regex, \
|
||||
__FILE__, __LINE__, >est_dt)) { \
|
||||
goto GTEST_CONCAT_TOKEN_(gtest_label_, __LINE__); \
|
||||
} \
|
||||
if (gtest_dt != NULL) { \
|
||||
::testing::internal::scoped_ptr< ::testing::internal::DeathTest> \
|
||||
gtest_dt_ptr(gtest_dt); \
|
||||
switch (gtest_dt->AssumeRole()) { \
|
||||
case ::testing::internal::DeathTest::OVERSEE_TEST: \
|
||||
if (!gtest_dt->Passed(predicate(gtest_dt->Wait()))) { \
|
||||
goto GTEST_CONCAT_TOKEN_(gtest_label_, __LINE__); \
|
||||
} \
|
||||
break; \
|
||||
case ::testing::internal::DeathTest::EXECUTE_TEST: { \
|
||||
::testing::internal::DeathTest::ReturnSentinel \
|
||||
gtest_sentinel(gtest_dt); \
|
||||
GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement); \
|
||||
gtest_dt->Abort(::testing::internal::DeathTest::TEST_DID_NOT_DIE); \
|
||||
break; \
|
||||
} \
|
||||
} \
|
||||
} \
|
||||
} else \
|
||||
GTEST_CONCAT_TOKEN_(gtest_label_, __LINE__): \
|
||||
fail(::testing::internal::DeathTest::LastMessage())
|
||||
// The symbol "fail" here expands to something into which a message
|
||||
// can be streamed.
|
||||
|
||||
// A class representing the parsed contents of the
|
||||
// --gtest_internal_run_death_test flag, as it existed when
|
||||
// RUN_ALL_TESTS was called.
|
||||
class InternalRunDeathTestFlag {
|
||||
public:
|
||||
InternalRunDeathTestFlag(const String& file,
|
||||
int line,
|
||||
int index,
|
||||
int write_fd)
|
||||
: file_(file), line_(line), index_(index), write_fd_(write_fd) {}
|
||||
|
||||
~InternalRunDeathTestFlag() {
|
||||
if (write_fd_ >= 0)
|
||||
posix::Close(write_fd_);
|
||||
}
|
||||
|
||||
String file() const { return file_; }
|
||||
int line() const { return line_; }
|
||||
int index() const { return index_; }
|
||||
int write_fd() const { return write_fd_; }
|
||||
|
||||
private:
|
||||
String file_;
|
||||
int line_;
|
||||
int index_;
|
||||
int write_fd_;
|
||||
|
||||
GTEST_DISALLOW_COPY_AND_ASSIGN_(InternalRunDeathTestFlag);
|
||||
};
|
||||
|
||||
// Returns a newly created InternalRunDeathTestFlag object with fields
|
||||
// initialized from the GTEST_FLAG(internal_run_death_test) flag if
|
||||
// the flag is specified; otherwise returns NULL.
|
||||
InternalRunDeathTestFlag* ParseInternalRunDeathTestFlag();
|
||||
|
||||
#else // GTEST_HAS_DEATH_TEST
|
||||
|
||||
// This macro is used for implementing macros such as
|
||||
// EXPECT_DEATH_IF_SUPPORTED and ASSERT_DEATH_IF_SUPPORTED on systems where
|
||||
// death tests are not supported. Those macros must compile on such systems
|
||||
// iff EXPECT_DEATH and ASSERT_DEATH compile with the same parameters on
|
||||
// systems that support death tests. This allows one to write such a macro
|
||||
// on a system that does not support death tests and be sure that it will
|
||||
// compile on a death-test supporting system.
|
||||
//
|
||||
// Parameters:
|
||||
// statement - A statement that a macro such as EXPECT_DEATH would test
|
||||
// for program termination. This macro has to make sure this
|
||||
// statement is compiled but not executed, to ensure that
|
||||
// EXPECT_DEATH_IF_SUPPORTED compiles with a certain
|
||||
// parameter iff EXPECT_DEATH compiles with it.
|
||||
// regex - A regex that a macro such as EXPECT_DEATH would use to test
|
||||
// the output of statement. This parameter has to be
|
||||
// compiled but not evaluated by this macro, to ensure that
|
||||
// this macro only accepts expressions that a macro such as
|
||||
// EXPECT_DEATH would accept.
|
||||
// terminator - Must be an empty statement for EXPECT_DEATH_IF_SUPPORTED
|
||||
// and a return statement for ASSERT_DEATH_IF_SUPPORTED.
|
||||
// This ensures that ASSERT_DEATH_IF_SUPPORTED will not
|
||||
// compile inside functions where ASSERT_DEATH doesn't
|
||||
// compile.
|
||||
//
|
||||
// The branch that has an always false condition is used to ensure that
|
||||
// statement and regex are compiled (and thus syntactically correct) but
|
||||
// never executed. The unreachable code macro protects the terminator
|
||||
// statement from generating an 'unreachable code' warning in case
|
||||
// statement unconditionally returns or throws. The Message constructor at
|
||||
// the end allows the syntax of streaming additional messages into the
|
||||
// macro, for compilational compatibility with EXPECT_DEATH/ASSERT_DEATH.
|
||||
#define GTEST_UNSUPPORTED_DEATH_TEST_(statement, regex, terminator) \
|
||||
GTEST_AMBIGUOUS_ELSE_BLOCKER_ \
|
||||
if (::testing::internal::AlwaysTrue()) { \
|
||||
GTEST_LOG_(WARNING) \
|
||||
<< "Death tests are not supported on this platform.\n" \
|
||||
<< "Statement '" #statement "' cannot be verified."; \
|
||||
} else if (::testing::internal::AlwaysFalse()) { \
|
||||
::testing::internal::RE::PartialMatch(".*", (regex)); \
|
||||
GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement); \
|
||||
terminator; \
|
||||
} else \
|
||||
::testing::Message()
|
||||
|
||||
#endif // GTEST_HAS_DEATH_TEST
|
||||
|
||||
} // namespace internal
|
||||
} // namespace testing
|
||||
|
||||
#endif // GTEST_INCLUDE_GTEST_INTERNAL_GTEST_DEATH_TEST_INTERNAL_H_
|
||||
// Copyright 2005, 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.
|
||||
//
|
||||
// Authors: wan@google.com (Zhanyong Wan), eefacm@gmail.com (Sean Mcafee)
|
||||
//
|
||||
// The Google C++ Testing Framework (Google Test)
|
||||
//
|
||||
// This header file defines internal utilities needed for implementing
|
||||
// death tests. They are subject to change without notice.
|
||||
|
||||
#ifndef GTEST_INCLUDE_GTEST_INTERNAL_GTEST_DEATH_TEST_INTERNAL_H_
|
||||
#define GTEST_INCLUDE_GTEST_INTERNAL_GTEST_DEATH_TEST_INTERNAL_H_
|
||||
|
||||
#include <gtest/internal/gtest-internal.h>
|
||||
|
||||
namespace testing {
|
||||
namespace internal {
|
||||
|
||||
GTEST_DECLARE_string_(internal_run_death_test);
|
||||
|
||||
// Names of the flags (needed for parsing Google Test flags).
|
||||
const char kDeathTestStyleFlag[] = "death_test_style";
|
||||
const char kDeathTestUseFork[] = "death_test_use_fork";
|
||||
const char kInternalRunDeathTestFlag[] = "internal_run_death_test";
|
||||
|
||||
#if GTEST_HAS_DEATH_TEST
|
||||
|
||||
// DeathTest is a class that hides much of the complexity of the
|
||||
// GTEST_DEATH_TEST_ macro. It is abstract; its static Create method
|
||||
// returns a concrete class that depends on the prevailing death test
|
||||
// style, as defined by the --gtest_death_test_style and/or
|
||||
// --gtest_internal_run_death_test flags.
|
||||
|
||||
// In describing the results of death tests, these terms are used with
|
||||
// the corresponding definitions:
|
||||
//
|
||||
// exit status: The integer exit information in the format specified
|
||||
// by wait(2)
|
||||
// exit code: The integer code passed to exit(3), _exit(2), or
|
||||
// returned from main()
|
||||
class DeathTest {
|
||||
public:
|
||||
// Create returns false if there was an error determining the
|
||||
// appropriate action to take for the current death test; for example,
|
||||
// if the gtest_death_test_style flag is set to an invalid value.
|
||||
// The LastMessage method will return a more detailed message in that
|
||||
// case. Otherwise, the DeathTest pointer pointed to by the "test"
|
||||
// argument is set. If the death test should be skipped, the pointer
|
||||
// is set to NULL; otherwise, it is set to the address of a new concrete
|
||||
// DeathTest object that controls the execution of the current test.
|
||||
static bool Create(const char* statement, const RE* regex,
|
||||
const char* file, int line, DeathTest** test);
|
||||
DeathTest();
|
||||
virtual ~DeathTest() { }
|
||||
|
||||
// A helper class that aborts a death test when it's deleted.
|
||||
class ReturnSentinel {
|
||||
public:
|
||||
explicit ReturnSentinel(DeathTest* test) : test_(test) { }
|
||||
~ReturnSentinel() { test_->Abort(TEST_ENCOUNTERED_RETURN_STATEMENT); }
|
||||
private:
|
||||
DeathTest* const test_;
|
||||
GTEST_DISALLOW_COPY_AND_ASSIGN_(ReturnSentinel);
|
||||
} GTEST_ATTRIBUTE_UNUSED_;
|
||||
|
||||
// An enumeration of possible roles that may be taken when a death
|
||||
// test is encountered. EXECUTE means that the death test logic should
|
||||
// be executed immediately. OVERSEE means that the program should prepare
|
||||
// the appropriate environment for a child process to execute the death
|
||||
// test, then wait for it to complete.
|
||||
enum TestRole { OVERSEE_TEST, EXECUTE_TEST };
|
||||
|
||||
// An enumeration of the two reasons that a test might be aborted.
|
||||
enum AbortReason { TEST_ENCOUNTERED_RETURN_STATEMENT, TEST_DID_NOT_DIE };
|
||||
|
||||
// Assumes one of the above roles.
|
||||
virtual TestRole AssumeRole() = 0;
|
||||
|
||||
// Waits for the death test to finish and returns its status.
|
||||
virtual int Wait() = 0;
|
||||
|
||||
// Returns true if the death test passed; that is, the test process
|
||||
// exited during the test, its exit status matches a user-supplied
|
||||
// predicate, and its stderr output matches a user-supplied regular
|
||||
// expression.
|
||||
// The user-supplied predicate may be a macro expression rather
|
||||
// than a function pointer or functor, or else Wait and Passed could
|
||||
// be combined.
|
||||
virtual bool Passed(bool exit_status_ok) = 0;
|
||||
|
||||
// Signals that the death test did not die as expected.
|
||||
virtual void Abort(AbortReason reason) = 0;
|
||||
|
||||
// Returns a human-readable outcome message regarding the outcome of
|
||||
// the last death test.
|
||||
static const char* LastMessage();
|
||||
|
||||
static void set_last_death_test_message(const String& message);
|
||||
|
||||
private:
|
||||
// A string containing a description of the outcome of the last death test.
|
||||
static String last_death_test_message_;
|
||||
|
||||
GTEST_DISALLOW_COPY_AND_ASSIGN_(DeathTest);
|
||||
};
|
||||
|
||||
// Factory interface for death tests. May be mocked out for testing.
|
||||
class DeathTestFactory {
|
||||
public:
|
||||
virtual ~DeathTestFactory() { }
|
||||
virtual bool Create(const char* statement, const RE* regex,
|
||||
const char* file, int line, DeathTest** test) = 0;
|
||||
};
|
||||
|
||||
// A concrete DeathTestFactory implementation for normal use.
|
||||
class DefaultDeathTestFactory : public DeathTestFactory {
|
||||
public:
|
||||
virtual bool Create(const char* statement, const RE* regex,
|
||||
const char* file, int line, DeathTest** test);
|
||||
};
|
||||
|
||||
// Returns true if exit_status describes a process that was terminated
|
||||
// by a signal, or exited normally with a nonzero exit code.
|
||||
bool ExitedUnsuccessfully(int exit_status);
|
||||
|
||||
// This macro is for implementing ASSERT_DEATH*, EXPECT_DEATH*,
|
||||
// ASSERT_EXIT*, and EXPECT_EXIT*.
|
||||
#define GTEST_DEATH_TEST_(statement, predicate, regex, fail) \
|
||||
GTEST_AMBIGUOUS_ELSE_BLOCKER_ \
|
||||
if (::testing::internal::AlwaysTrue()) { \
|
||||
const ::testing::internal::RE& gtest_regex = (regex); \
|
||||
::testing::internal::DeathTest* gtest_dt; \
|
||||
if (!::testing::internal::DeathTest::Create(#statement, >est_regex, \
|
||||
__FILE__, __LINE__, >est_dt)) { \
|
||||
goto GTEST_CONCAT_TOKEN_(gtest_label_, __LINE__); \
|
||||
} \
|
||||
if (gtest_dt != NULL) { \
|
||||
::testing::internal::scoped_ptr< ::testing::internal::DeathTest> \
|
||||
gtest_dt_ptr(gtest_dt); \
|
||||
switch (gtest_dt->AssumeRole()) { \
|
||||
case ::testing::internal::DeathTest::OVERSEE_TEST: \
|
||||
if (!gtest_dt->Passed(predicate(gtest_dt->Wait()))) { \
|
||||
goto GTEST_CONCAT_TOKEN_(gtest_label_, __LINE__); \
|
||||
} \
|
||||
break; \
|
||||
case ::testing::internal::DeathTest::EXECUTE_TEST: { \
|
||||
::testing::internal::DeathTest::ReturnSentinel \
|
||||
gtest_sentinel(gtest_dt); \
|
||||
GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement); \
|
||||
gtest_dt->Abort(::testing::internal::DeathTest::TEST_DID_NOT_DIE); \
|
||||
break; \
|
||||
} \
|
||||
} \
|
||||
} \
|
||||
} else \
|
||||
GTEST_CONCAT_TOKEN_(gtest_label_, __LINE__): \
|
||||
fail(::testing::internal::DeathTest::LastMessage())
|
||||
// The symbol "fail" here expands to something into which a message
|
||||
// can be streamed.
|
||||
|
||||
// A class representing the parsed contents of the
|
||||
// --gtest_internal_run_death_test flag, as it existed when
|
||||
// RUN_ALL_TESTS was called.
|
||||
class InternalRunDeathTestFlag {
|
||||
public:
|
||||
InternalRunDeathTestFlag(const String& file,
|
||||
int line,
|
||||
int index,
|
||||
int write_fd)
|
||||
: file_(file), line_(line), index_(index), write_fd_(write_fd) {}
|
||||
|
||||
~InternalRunDeathTestFlag() {
|
||||
if (write_fd_ >= 0)
|
||||
posix::Close(write_fd_);
|
||||
}
|
||||
|
||||
String file() const { return file_; }
|
||||
int line() const { return line_; }
|
||||
int index() const { return index_; }
|
||||
int write_fd() const { return write_fd_; }
|
||||
|
||||
private:
|
||||
String file_;
|
||||
int line_;
|
||||
int index_;
|
||||
int write_fd_;
|
||||
|
||||
GTEST_DISALLOW_COPY_AND_ASSIGN_(InternalRunDeathTestFlag);
|
||||
};
|
||||
|
||||
// Returns a newly created InternalRunDeathTestFlag object with fields
|
||||
// initialized from the GTEST_FLAG(internal_run_death_test) flag if
|
||||
// the flag is specified; otherwise returns NULL.
|
||||
InternalRunDeathTestFlag* ParseInternalRunDeathTestFlag();
|
||||
|
||||
#else // GTEST_HAS_DEATH_TEST
|
||||
|
||||
// This macro is used for implementing macros such as
|
||||
// EXPECT_DEATH_IF_SUPPORTED and ASSERT_DEATH_IF_SUPPORTED on systems where
|
||||
// death tests are not supported. Those macros must compile on such systems
|
||||
// iff EXPECT_DEATH and ASSERT_DEATH compile with the same parameters on
|
||||
// systems that support death tests. This allows one to write such a macro
|
||||
// on a system that does not support death tests and be sure that it will
|
||||
// compile on a death-test supporting system.
|
||||
//
|
||||
// Parameters:
|
||||
// statement - A statement that a macro such as EXPECT_DEATH would test
|
||||
// for program termination. This macro has to make sure this
|
||||
// statement is compiled but not executed, to ensure that
|
||||
// EXPECT_DEATH_IF_SUPPORTED compiles with a certain
|
||||
// parameter iff EXPECT_DEATH compiles with it.
|
||||
// regex - A regex that a macro such as EXPECT_DEATH would use to test
|
||||
// the output of statement. This parameter has to be
|
||||
// compiled but not evaluated by this macro, to ensure that
|
||||
// this macro only accepts expressions that a macro such as
|
||||
// EXPECT_DEATH would accept.
|
||||
// terminator - Must be an empty statement for EXPECT_DEATH_IF_SUPPORTED
|
||||
// and a return statement for ASSERT_DEATH_IF_SUPPORTED.
|
||||
// This ensures that ASSERT_DEATH_IF_SUPPORTED will not
|
||||
// compile inside functions where ASSERT_DEATH doesn't
|
||||
// compile.
|
||||
//
|
||||
// The branch that has an always false condition is used to ensure that
|
||||
// statement and regex are compiled (and thus syntactically correct) but
|
||||
// never executed. The unreachable code macro protects the terminator
|
||||
// statement from generating an 'unreachable code' warning in case
|
||||
// statement unconditionally returns or throws. The Message constructor at
|
||||
// the end allows the syntax of streaming additional messages into the
|
||||
// macro, for compilational compatibility with EXPECT_DEATH/ASSERT_DEATH.
|
||||
#define GTEST_UNSUPPORTED_DEATH_TEST_(statement, regex, terminator) \
|
||||
GTEST_AMBIGUOUS_ELSE_BLOCKER_ \
|
||||
if (::testing::internal::AlwaysTrue()) { \
|
||||
GTEST_LOG_(WARNING) \
|
||||
<< "Death tests are not supported on this platform.\n" \
|
||||
<< "Statement '" #statement "' cannot be verified."; \
|
||||
} else if (::testing::internal::AlwaysFalse()) { \
|
||||
::testing::internal::RE::PartialMatch(".*", (regex)); \
|
||||
GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement); \
|
||||
terminator; \
|
||||
} else \
|
||||
::testing::Message()
|
||||
|
||||
#endif // GTEST_HAS_DEATH_TEST
|
||||
|
||||
} // namespace internal
|
||||
} // namespace testing
|
||||
|
||||
#endif // GTEST_INCLUDE_GTEST_INTERNAL_GTEST_DEATH_TEST_INTERNAL_H_
|
||||
|
||||
+201
-201
@@ -1,201 +1,201 @@
|
||||
// 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.
|
||||
//
|
||||
// Author: keith.ray@gmail.com (Keith Ray)
|
||||
//
|
||||
// Google Test filepath utilities
|
||||
//
|
||||
// This header file declares classes and functions used internally by
|
||||
// Google Test. They are subject to change without notice.
|
||||
//
|
||||
// This file is #included in <gtest/internal/gtest-internal.h>.
|
||||
// Do not include this header file separately!
|
||||
|
||||
#ifndef GTEST_INCLUDE_GTEST_INTERNAL_GTEST_FILEPATH_H_
|
||||
#define GTEST_INCLUDE_GTEST_INTERNAL_GTEST_FILEPATH_H_
|
||||
|
||||
#include <gtest/internal/gtest-string.h>
|
||||
|
||||
namespace testing {
|
||||
namespace internal {
|
||||
|
||||
// FilePath - a class for file and directory pathname manipulation which
|
||||
// handles platform-specific conventions (like the pathname separator).
|
||||
// Used for helper functions for naming files in a directory for xml output.
|
||||
// Except for Set methods, all methods are const or static, which provides an
|
||||
// "immutable value object" -- useful for peace of mind.
|
||||
// A FilePath with a value ending in a path separator ("like/this/") represents
|
||||
// a directory, otherwise it is assumed to represent a file. In either case,
|
||||
// it may or may not represent an actual file or directory in the file system.
|
||||
// Names are NOT checked for syntax correctness -- no checking for illegal
|
||||
// characters, malformed paths, etc.
|
||||
|
||||
class FilePath {
|
||||
public:
|
||||
FilePath() : pathname_("") { }
|
||||
FilePath(const FilePath& rhs) : pathname_(rhs.pathname_) { }
|
||||
|
||||
explicit FilePath(const char* pathname) : pathname_(pathname) {
|
||||
Normalize();
|
||||
}
|
||||
|
||||
explicit FilePath(const String& pathname) : pathname_(pathname) {
|
||||
Normalize();
|
||||
}
|
||||
|
||||
FilePath& operator=(const FilePath& rhs) {
|
||||
Set(rhs);
|
||||
return *this;
|
||||
}
|
||||
|
||||
void Set(const FilePath& rhs) {
|
||||
pathname_ = rhs.pathname_;
|
||||
}
|
||||
|
||||
String ToString() const { return pathname_; }
|
||||
const char* c_str() const { return pathname_.c_str(); }
|
||||
|
||||
// Returns the current working directory, or "" if unsuccessful.
|
||||
static FilePath GetCurrentDir();
|
||||
|
||||
// Given directory = "dir", base_name = "test", number = 0,
|
||||
// extension = "xml", returns "dir/test.xml". If number is greater
|
||||
// than zero (e.g., 12), returns "dir/test_12.xml".
|
||||
// On Windows platform, uses \ as the separator rather than /.
|
||||
static FilePath MakeFileName(const FilePath& directory,
|
||||
const FilePath& base_name,
|
||||
int number,
|
||||
const char* extension);
|
||||
|
||||
// Given directory = "dir", relative_path = "test.xml",
|
||||
// returns "dir/test.xml".
|
||||
// On Windows, uses \ as the separator rather than /.
|
||||
static FilePath ConcatPaths(const FilePath& directory,
|
||||
const FilePath& relative_path);
|
||||
|
||||
// Returns a pathname for a file that does not currently exist. The pathname
|
||||
// will be directory/base_name.extension or
|
||||
// directory/base_name_<number>.extension if directory/base_name.extension
|
||||
// already exists. The number will be incremented until a pathname is found
|
||||
// that does not already exist.
|
||||
// Examples: 'dir/foo_test.xml' or 'dir/foo_test_1.xml'.
|
||||
// There could be a race condition if two or more processes are calling this
|
||||
// function at the same time -- they could both pick the same filename.
|
||||
static FilePath GenerateUniqueFileName(const FilePath& directory,
|
||||
const FilePath& base_name,
|
||||
const char* extension);
|
||||
|
||||
// Returns true iff the path is NULL or "".
|
||||
bool IsEmpty() const { return c_str() == NULL || *c_str() == '\0'; }
|
||||
|
||||
// If input name has a trailing separator character, removes it and returns
|
||||
// the name, otherwise return the name string unmodified.
|
||||
// On Windows platform, uses \ as the separator, other platforms use /.
|
||||
FilePath RemoveTrailingPathSeparator() const;
|
||||
|
||||
// Returns a copy of the FilePath with the directory part removed.
|
||||
// Example: FilePath("path/to/file").RemoveDirectoryName() returns
|
||||
// FilePath("file"). If there is no directory part ("just_a_file"), it returns
|
||||
// the FilePath unmodified. If there is no file part ("just_a_dir/") it
|
||||
// returns an empty FilePath ("").
|
||||
// On Windows platform, '\' is the path separator, otherwise it is '/'.
|
||||
FilePath RemoveDirectoryName() const;
|
||||
|
||||
// RemoveFileName returns the directory path with the filename removed.
|
||||
// Example: FilePath("path/to/file").RemoveFileName() returns "path/to/".
|
||||
// If the FilePath is "a_file" or "/a_file", RemoveFileName returns
|
||||
// FilePath("./") or, on Windows, FilePath(".\\"). If the filepath does
|
||||
// not have a file, like "just/a/dir/", it returns the FilePath unmodified.
|
||||
// On Windows platform, '\' is the path separator, otherwise it is '/'.
|
||||
FilePath RemoveFileName() const;
|
||||
|
||||
// Returns a copy of the FilePath with the case-insensitive extension removed.
|
||||
// Example: FilePath("dir/file.exe").RemoveExtension("EXE") returns
|
||||
// FilePath("dir/file"). If a case-insensitive extension is not
|
||||
// found, returns a copy of the original FilePath.
|
||||
FilePath RemoveExtension(const char* extension) const;
|
||||
|
||||
// Creates directories so that path exists. Returns true if successful or if
|
||||
// the directories already exist; returns false if unable to create
|
||||
// directories for any reason. Will also return false if the FilePath does
|
||||
// not represent a directory (that is, it doesn't end with a path separator).
|
||||
bool CreateDirectoriesRecursively() const;
|
||||
|
||||
// Create the directory so that path exists. Returns true if successful or
|
||||
// if the directory already exists; returns false if unable to create the
|
||||
// directory for any reason, including if the parent directory does not
|
||||
// exist. Not named "CreateDirectory" because that's a macro on Windows.
|
||||
bool CreateFolder() const;
|
||||
|
||||
// Returns true if FilePath describes something in the file-system,
|
||||
// either a file, directory, or whatever, and that something exists.
|
||||
bool FileOrDirectoryExists() const;
|
||||
|
||||
// Returns true if pathname describes a directory in the file-system
|
||||
// that exists.
|
||||
bool DirectoryExists() const;
|
||||
|
||||
// Returns true if FilePath ends with a path separator, which indicates that
|
||||
// it is intended to represent a directory. Returns false otherwise.
|
||||
// This does NOT check that a directory (or file) actually exists.
|
||||
bool IsDirectory() const;
|
||||
|
||||
// Returns true if pathname describes a root directory. (Windows has one
|
||||
// root directory per disk drive.)
|
||||
bool IsRootDirectory() const;
|
||||
|
||||
// Returns true if pathname describes an absolute path.
|
||||
bool IsAbsolutePath() const;
|
||||
|
||||
private:
|
||||
// Replaces multiple consecutive separators with a single separator.
|
||||
// For example, "bar///foo" becomes "bar/foo". Does not eliminate other
|
||||
// redundancies that might be in a pathname involving "." or "..".
|
||||
//
|
||||
// A pathname with multiple consecutive separators may occur either through
|
||||
// user error or as a result of some scripts or APIs that generate a pathname
|
||||
// with a trailing separator. On other platforms the same API or script
|
||||
// may NOT generate a pathname with a trailing "/". Then elsewhere that
|
||||
// pathname may have another "/" and pathname components added to it,
|
||||
// without checking for the separator already being there.
|
||||
// The script language and operating system may allow paths like "foo//bar"
|
||||
// but some of the functions in FilePath will not handle that correctly. In
|
||||
// particular, RemoveTrailingPathSeparator() only removes one separator, and
|
||||
// it is called in CreateDirectoriesRecursively() assuming that it will change
|
||||
// a pathname from directory syntax (trailing separator) to filename syntax.
|
||||
|
||||
void Normalize();
|
||||
|
||||
String pathname_;
|
||||
}; // class FilePath
|
||||
|
||||
} // namespace internal
|
||||
} // namespace testing
|
||||
|
||||
#endif // GTEST_INCLUDE_GTEST_INTERNAL_GTEST_FILEPATH_H_
|
||||
// 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.
|
||||
//
|
||||
// Author: keith.ray@gmail.com (Keith Ray)
|
||||
//
|
||||
// Google Test filepath utilities
|
||||
//
|
||||
// This header file declares classes and functions used internally by
|
||||
// Google Test. They are subject to change without notice.
|
||||
//
|
||||
// This file is #included in <gtest/internal/gtest-internal.h>.
|
||||
// Do not include this header file separately!
|
||||
|
||||
#ifndef GTEST_INCLUDE_GTEST_INTERNAL_GTEST_FILEPATH_H_
|
||||
#define GTEST_INCLUDE_GTEST_INTERNAL_GTEST_FILEPATH_H_
|
||||
|
||||
#include <gtest/internal/gtest-string.h>
|
||||
|
||||
namespace testing {
|
||||
namespace internal {
|
||||
|
||||
// FilePath - a class for file and directory pathname manipulation which
|
||||
// handles platform-specific conventions (like the pathname separator).
|
||||
// Used for helper functions for naming files in a directory for xml output.
|
||||
// Except for Set methods, all methods are const or static, which provides an
|
||||
// "immutable value object" -- useful for peace of mind.
|
||||
// A FilePath with a value ending in a path separator ("like/this/") represents
|
||||
// a directory, otherwise it is assumed to represent a file. In either case,
|
||||
// it may or may not represent an actual file or directory in the file system.
|
||||
// Names are NOT checked for syntax correctness -- no checking for illegal
|
||||
// characters, malformed paths, etc.
|
||||
|
||||
class FilePath {
|
||||
public:
|
||||
FilePath() : pathname_("") { }
|
||||
FilePath(const FilePath& rhs) : pathname_(rhs.pathname_) { }
|
||||
|
||||
explicit FilePath(const char* pathname) : pathname_(pathname) {
|
||||
Normalize();
|
||||
}
|
||||
|
||||
explicit FilePath(const String& pathname) : pathname_(pathname) {
|
||||
Normalize();
|
||||
}
|
||||
|
||||
FilePath& operator=(const FilePath& rhs) {
|
||||
Set(rhs);
|
||||
return *this;
|
||||
}
|
||||
|
||||
void Set(const FilePath& rhs) {
|
||||
pathname_ = rhs.pathname_;
|
||||
}
|
||||
|
||||
String ToString() const { return pathname_; }
|
||||
const char* c_str() const { return pathname_.c_str(); }
|
||||
|
||||
// Returns the current working directory, or "" if unsuccessful.
|
||||
static FilePath GetCurrentDir();
|
||||
|
||||
// Given directory = "dir", base_name = "test", number = 0,
|
||||
// extension = "xml", returns "dir/test.xml". If number is greater
|
||||
// than zero (e.g., 12), returns "dir/test_12.xml".
|
||||
// On Windows platform, uses \ as the separator rather than /.
|
||||
static FilePath MakeFileName(const FilePath& directory,
|
||||
const FilePath& base_name,
|
||||
int number,
|
||||
const char* extension);
|
||||
|
||||
// Given directory = "dir", relative_path = "test.xml",
|
||||
// returns "dir/test.xml".
|
||||
// On Windows, uses \ as the separator rather than /.
|
||||
static FilePath ConcatPaths(const FilePath& directory,
|
||||
const FilePath& relative_path);
|
||||
|
||||
// Returns a pathname for a file that does not currently exist. The pathname
|
||||
// will be directory/base_name.extension or
|
||||
// directory/base_name_<number>.extension if directory/base_name.extension
|
||||
// already exists. The number will be incremented until a pathname is found
|
||||
// that does not already exist.
|
||||
// Examples: 'dir/foo_test.xml' or 'dir/foo_test_1.xml'.
|
||||
// There could be a race condition if two or more processes are calling this
|
||||
// function at the same time -- they could both pick the same filename.
|
||||
static FilePath GenerateUniqueFileName(const FilePath& directory,
|
||||
const FilePath& base_name,
|
||||
const char* extension);
|
||||
|
||||
// Returns true iff the path is NULL or "".
|
||||
bool IsEmpty() const { return c_str() == NULL || *c_str() == '\0'; }
|
||||
|
||||
// If input name has a trailing separator character, removes it and returns
|
||||
// the name, otherwise return the name string unmodified.
|
||||
// On Windows platform, uses \ as the separator, other platforms use /.
|
||||
FilePath RemoveTrailingPathSeparator() const;
|
||||
|
||||
// Returns a copy of the FilePath with the directory part removed.
|
||||
// Example: FilePath("path/to/file").RemoveDirectoryName() returns
|
||||
// FilePath("file"). If there is no directory part ("just_a_file"), it returns
|
||||
// the FilePath unmodified. If there is no file part ("just_a_dir/") it
|
||||
// returns an empty FilePath ("").
|
||||
// On Windows platform, '\' is the path separator, otherwise it is '/'.
|
||||
FilePath RemoveDirectoryName() const;
|
||||
|
||||
// RemoveFileName returns the directory path with the filename removed.
|
||||
// Example: FilePath("path/to/file").RemoveFileName() returns "path/to/".
|
||||
// If the FilePath is "a_file" or "/a_file", RemoveFileName returns
|
||||
// FilePath("./") or, on Windows, FilePath(".\\"). If the filepath does
|
||||
// not have a file, like "just/a/dir/", it returns the FilePath unmodified.
|
||||
// On Windows platform, '\' is the path separator, otherwise it is '/'.
|
||||
FilePath RemoveFileName() const;
|
||||
|
||||
// Returns a copy of the FilePath with the case-insensitive extension removed.
|
||||
// Example: FilePath("dir/file.exe").RemoveExtension("EXE") returns
|
||||
// FilePath("dir/file"). If a case-insensitive extension is not
|
||||
// found, returns a copy of the original FilePath.
|
||||
FilePath RemoveExtension(const char* extension) const;
|
||||
|
||||
// Creates directories so that path exists. Returns true if successful or if
|
||||
// the directories already exist; returns false if unable to create
|
||||
// directories for any reason. Will also return false if the FilePath does
|
||||
// not represent a directory (that is, it doesn't end with a path separator).
|
||||
bool CreateDirectoriesRecursively() const;
|
||||
|
||||
// Create the directory so that path exists. Returns true if successful or
|
||||
// if the directory already exists; returns false if unable to create the
|
||||
// directory for any reason, including if the parent directory does not
|
||||
// exist. Not named "CreateDirectory" because that's a macro on Windows.
|
||||
bool CreateFolder() const;
|
||||
|
||||
// Returns true if FilePath describes something in the file-system,
|
||||
// either a file, directory, or whatever, and that something exists.
|
||||
bool FileOrDirectoryExists() const;
|
||||
|
||||
// Returns true if pathname describes a directory in the file-system
|
||||
// that exists.
|
||||
bool DirectoryExists() const;
|
||||
|
||||
// Returns true if FilePath ends with a path separator, which indicates that
|
||||
// it is intended to represent a directory. Returns false otherwise.
|
||||
// This does NOT check that a directory (or file) actually exists.
|
||||
bool IsDirectory() const;
|
||||
|
||||
// Returns true if pathname describes a root directory. (Windows has one
|
||||
// root directory per disk drive.)
|
||||
bool IsRootDirectory() const;
|
||||
|
||||
// Returns true if pathname describes an absolute path.
|
||||
bool IsAbsolutePath() const;
|
||||
|
||||
private:
|
||||
// Replaces multiple consecutive separators with a single separator.
|
||||
// For example, "bar///foo" becomes "bar/foo". Does not eliminate other
|
||||
// redundancies that might be in a pathname involving "." or "..".
|
||||
//
|
||||
// A pathname with multiple consecutive separators may occur either through
|
||||
// user error or as a result of some scripts or APIs that generate a pathname
|
||||
// with a trailing separator. On other platforms the same API or script
|
||||
// may NOT generate a pathname with a trailing "/". Then elsewhere that
|
||||
// pathname may have another "/" and pathname components added to it,
|
||||
// without checking for the separator already being there.
|
||||
// The script language and operating system may allow paths like "foo//bar"
|
||||
// but some of the functions in FilePath will not handle that correctly. In
|
||||
// particular, RemoveTrailingPathSeparator() only removes one separator, and
|
||||
// it is called in CreateDirectoriesRecursively() assuming that it will change
|
||||
// a pathname from directory syntax (trailing separator) to filename syntax.
|
||||
|
||||
void Normalize();
|
||||
|
||||
String pathname_;
|
||||
}; // class FilePath
|
||||
|
||||
} // namespace internal
|
||||
} // namespace testing
|
||||
|
||||
#endif // GTEST_INCLUDE_GTEST_INTERNAL_GTEST_FILEPATH_H_
|
||||
|
||||
+910
-910
File diff suppressed because it is too large
Load Diff
+242
-242
@@ -1,242 +1,242 @@
|
||||
// Copyright 2003 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.
|
||||
//
|
||||
// Authors: Dan Egnor (egnor@google.com)
|
||||
//
|
||||
// A "smart" pointer type with reference tracking. Every pointer to a
|
||||
// particular object is kept on a circular linked list. When the last pointer
|
||||
// to an object is destroyed or reassigned, the object is deleted.
|
||||
//
|
||||
// Used properly, this deletes the object when the last reference goes away.
|
||||
// There are several caveats:
|
||||
// - Like all reference counting schemes, cycles lead to leaks.
|
||||
// - Each smart pointer is actually two pointers (8 bytes instead of 4).
|
||||
// - Every time a pointer is assigned, the entire list of pointers to that
|
||||
// object is traversed. This class is therefore NOT SUITABLE when there
|
||||
// will often be more than two or three pointers to a particular object.
|
||||
// - References are only tracked as long as linked_ptr<> objects are copied.
|
||||
// If a linked_ptr<> is converted to a raw pointer and back, BAD THINGS
|
||||
// will happen (double deletion).
|
||||
//
|
||||
// A good use of this class is storing object references in STL containers.
|
||||
// You can safely put linked_ptr<> in a vector<>.
|
||||
// Other uses may not be as good.
|
||||
//
|
||||
// Note: If you use an incomplete type with linked_ptr<>, the class
|
||||
// *containing* linked_ptr<> must have a constructor and destructor (even
|
||||
// if they do nothing!).
|
||||
//
|
||||
// Bill Gibbons suggested we use something like this.
|
||||
//
|
||||
// Thread Safety:
|
||||
// Unlike other linked_ptr implementations, in this implementation
|
||||
// a linked_ptr object is thread-safe in the sense that:
|
||||
// - it's safe to copy linked_ptr objects concurrently,
|
||||
// - it's safe to copy *from* a linked_ptr and read its underlying
|
||||
// raw pointer (e.g. via get()) concurrently, and
|
||||
// - it's safe to write to two linked_ptrs that point to the same
|
||||
// shared object concurrently.
|
||||
// TODO(wan@google.com): rename this to safe_linked_ptr to avoid
|
||||
// confusion with normal linked_ptr.
|
||||
|
||||
#ifndef GTEST_INCLUDE_GTEST_INTERNAL_GTEST_LINKED_PTR_H_
|
||||
#define GTEST_INCLUDE_GTEST_INTERNAL_GTEST_LINKED_PTR_H_
|
||||
|
||||
#include <stdlib.h>
|
||||
#include <assert.h>
|
||||
|
||||
#include <gtest/internal/gtest-port.h>
|
||||
|
||||
namespace testing {
|
||||
namespace internal {
|
||||
|
||||
// Protects copying of all linked_ptr objects.
|
||||
extern Mutex g_linked_ptr_mutex;
|
||||
|
||||
// This is used internally by all instances of linked_ptr<>. It needs to be
|
||||
// a non-template class because different types of linked_ptr<> can refer to
|
||||
// the same object (linked_ptr<Superclass>(obj) vs linked_ptr<Subclass>(obj)).
|
||||
// So, it needs to be possible for different types of linked_ptr to participate
|
||||
// in the same circular linked list, so we need a single class type here.
|
||||
//
|
||||
// DO NOT USE THIS CLASS DIRECTLY YOURSELF. Use linked_ptr<T>.
|
||||
class linked_ptr_internal {
|
||||
public:
|
||||
// Create a new circle that includes only this instance.
|
||||
void join_new() {
|
||||
next_ = this;
|
||||
}
|
||||
|
||||
// Many linked_ptr operations may change p.link_ for some linked_ptr
|
||||
// variable p in the same circle as this object. Therefore we need
|
||||
// to prevent two such operations from occurring concurrently.
|
||||
//
|
||||
// Note that different types of linked_ptr objects can coexist in a
|
||||
// circle (e.g. linked_ptr<Base>, linked_ptr<Derived1>, and
|
||||
// linked_ptr<Derived2>). Therefore we must use a single mutex to
|
||||
// protect all linked_ptr objects. This can create serious
|
||||
// contention in production code, but is acceptable in a testing
|
||||
// framework.
|
||||
|
||||
// Join an existing circle.
|
||||
// L < g_linked_ptr_mutex
|
||||
void join(linked_ptr_internal const* ptr) {
|
||||
MutexLock lock(&g_linked_ptr_mutex);
|
||||
|
||||
linked_ptr_internal const* p = ptr;
|
||||
while (p->next_ != ptr) p = p->next_;
|
||||
p->next_ = this;
|
||||
next_ = ptr;
|
||||
}
|
||||
|
||||
// Leave whatever circle we're part of. Returns true if we were the
|
||||
// last member of the circle. Once this is done, you can join() another.
|
||||
// L < g_linked_ptr_mutex
|
||||
bool depart() {
|
||||
MutexLock lock(&g_linked_ptr_mutex);
|
||||
|
||||
if (next_ == this) return true;
|
||||
linked_ptr_internal const* p = next_;
|
||||
while (p->next_ != this) p = p->next_;
|
||||
p->next_ = next_;
|
||||
return false;
|
||||
}
|
||||
|
||||
private:
|
||||
mutable linked_ptr_internal const* next_;
|
||||
};
|
||||
|
||||
template <typename T>
|
||||
class linked_ptr {
|
||||
public:
|
||||
typedef T element_type;
|
||||
|
||||
// Take over ownership of a raw pointer. This should happen as soon as
|
||||
// possible after the object is created.
|
||||
explicit linked_ptr(T* ptr = NULL) { capture(ptr); }
|
||||
~linked_ptr() { depart(); }
|
||||
|
||||
// Copy an existing linked_ptr<>, adding ourselves to the list of references.
|
||||
template <typename U> linked_ptr(linked_ptr<U> const& ptr) { copy(&ptr); }
|
||||
linked_ptr(linked_ptr const& ptr) { // NOLINT
|
||||
assert(&ptr != this);
|
||||
copy(&ptr);
|
||||
}
|
||||
|
||||
// Assignment releases the old value and acquires the new.
|
||||
template <typename U> linked_ptr& operator=(linked_ptr<U> const& ptr) {
|
||||
depart();
|
||||
copy(&ptr);
|
||||
return *this;
|
||||
}
|
||||
|
||||
linked_ptr& operator=(linked_ptr const& ptr) {
|
||||
if (&ptr != this) {
|
||||
depart();
|
||||
copy(&ptr);
|
||||
}
|
||||
return *this;
|
||||
}
|
||||
|
||||
// Smart pointer members.
|
||||
void reset(T* ptr = NULL) {
|
||||
depart();
|
||||
capture(ptr);
|
||||
}
|
||||
T* get() const { return value_; }
|
||||
T* operator->() const { return value_; }
|
||||
T& operator*() const { return *value_; }
|
||||
// Release ownership of the pointed object and returns it.
|
||||
// Sole ownership by this linked_ptr object is required.
|
||||
T* release() {
|
||||
bool last = link_.depart();
|
||||
assert(last);
|
||||
T* v = value_;
|
||||
value_ = NULL;
|
||||
return v;
|
||||
}
|
||||
|
||||
bool operator==(T* p) const { return value_ == p; }
|
||||
bool operator!=(T* p) const { return value_ != p; }
|
||||
template <typename U>
|
||||
bool operator==(linked_ptr<U> const& ptr) const {
|
||||
return value_ == ptr.get();
|
||||
}
|
||||
template <typename U>
|
||||
bool operator!=(linked_ptr<U> const& ptr) const {
|
||||
return value_ != ptr.get();
|
||||
}
|
||||
|
||||
private:
|
||||
template <typename U>
|
||||
friend class linked_ptr;
|
||||
|
||||
T* value_;
|
||||
linked_ptr_internal link_;
|
||||
|
||||
void depart() {
|
||||
if (link_.depart()) delete value_;
|
||||
}
|
||||
|
||||
void capture(T* ptr) {
|
||||
value_ = ptr;
|
||||
link_.join_new();
|
||||
}
|
||||
|
||||
template <typename U> void copy(linked_ptr<U> const* ptr) {
|
||||
value_ = ptr->get();
|
||||
if (value_)
|
||||
link_.join(&ptr->link_);
|
||||
else
|
||||
link_.join_new();
|
||||
}
|
||||
};
|
||||
|
||||
template<typename T> inline
|
||||
bool operator==(T* ptr, const linked_ptr<T>& x) {
|
||||
return ptr == x.get();
|
||||
}
|
||||
|
||||
template<typename T> inline
|
||||
bool operator!=(T* ptr, const linked_ptr<T>& x) {
|
||||
return ptr != x.get();
|
||||
}
|
||||
|
||||
// A function to convert T* into linked_ptr<T>
|
||||
// Doing e.g. make_linked_ptr(new FooBarBaz<type>(arg)) is a shorter notation
|
||||
// for linked_ptr<FooBarBaz<type> >(new FooBarBaz<type>(arg))
|
||||
template <typename T>
|
||||
linked_ptr<T> make_linked_ptr(T* ptr) {
|
||||
return linked_ptr<T>(ptr);
|
||||
}
|
||||
|
||||
} // namespace internal
|
||||
} // namespace testing
|
||||
|
||||
#endif // GTEST_INCLUDE_GTEST_INTERNAL_GTEST_LINKED_PTR_H_
|
||||
// Copyright 2003 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.
|
||||
//
|
||||
// Authors: Dan Egnor (egnor@google.com)
|
||||
//
|
||||
// A "smart" pointer type with reference tracking. Every pointer to a
|
||||
// particular object is kept on a circular linked list. When the last pointer
|
||||
// to an object is destroyed or reassigned, the object is deleted.
|
||||
//
|
||||
// Used properly, this deletes the object when the last reference goes away.
|
||||
// There are several caveats:
|
||||
// - Like all reference counting schemes, cycles lead to leaks.
|
||||
// - Each smart pointer is actually two pointers (8 bytes instead of 4).
|
||||
// - Every time a pointer is assigned, the entire list of pointers to that
|
||||
// object is traversed. This class is therefore NOT SUITABLE when there
|
||||
// will often be more than two or three pointers to a particular object.
|
||||
// - References are only tracked as long as linked_ptr<> objects are copied.
|
||||
// If a linked_ptr<> is converted to a raw pointer and back, BAD THINGS
|
||||
// will happen (double deletion).
|
||||
//
|
||||
// A good use of this class is storing object references in STL containers.
|
||||
// You can safely put linked_ptr<> in a vector<>.
|
||||
// Other uses may not be as good.
|
||||
//
|
||||
// Note: If you use an incomplete type with linked_ptr<>, the class
|
||||
// *containing* linked_ptr<> must have a constructor and destructor (even
|
||||
// if they do nothing!).
|
||||
//
|
||||
// Bill Gibbons suggested we use something like this.
|
||||
//
|
||||
// Thread Safety:
|
||||
// Unlike other linked_ptr implementations, in this implementation
|
||||
// a linked_ptr object is thread-safe in the sense that:
|
||||
// - it's safe to copy linked_ptr objects concurrently,
|
||||
// - it's safe to copy *from* a linked_ptr and read its underlying
|
||||
// raw pointer (e.g. via get()) concurrently, and
|
||||
// - it's safe to write to two linked_ptrs that point to the same
|
||||
// shared object concurrently.
|
||||
// TODO(wan@google.com): rename this to safe_linked_ptr to avoid
|
||||
// confusion with normal linked_ptr.
|
||||
|
||||
#ifndef GTEST_INCLUDE_GTEST_INTERNAL_GTEST_LINKED_PTR_H_
|
||||
#define GTEST_INCLUDE_GTEST_INTERNAL_GTEST_LINKED_PTR_H_
|
||||
|
||||
#include <stdlib.h>
|
||||
#include <assert.h>
|
||||
|
||||
#include <gtest/internal/gtest-port.h>
|
||||
|
||||
namespace testing {
|
||||
namespace internal {
|
||||
|
||||
// Protects copying of all linked_ptr objects.
|
||||
extern Mutex g_linked_ptr_mutex;
|
||||
|
||||
// This is used internally by all instances of linked_ptr<>. It needs to be
|
||||
// a non-template class because different types of linked_ptr<> can refer to
|
||||
// the same object (linked_ptr<Superclass>(obj) vs linked_ptr<Subclass>(obj)).
|
||||
// So, it needs to be possible for different types of linked_ptr to participate
|
||||
// in the same circular linked list, so we need a single class type here.
|
||||
//
|
||||
// DO NOT USE THIS CLASS DIRECTLY YOURSELF. Use linked_ptr<T>.
|
||||
class linked_ptr_internal {
|
||||
public:
|
||||
// Create a new circle that includes only this instance.
|
||||
void join_new() {
|
||||
next_ = this;
|
||||
}
|
||||
|
||||
// Many linked_ptr operations may change p.link_ for some linked_ptr
|
||||
// variable p in the same circle as this object. Therefore we need
|
||||
// to prevent two such operations from occurring concurrently.
|
||||
//
|
||||
// Note that different types of linked_ptr objects can coexist in a
|
||||
// circle (e.g. linked_ptr<Base>, linked_ptr<Derived1>, and
|
||||
// linked_ptr<Derived2>). Therefore we must use a single mutex to
|
||||
// protect all linked_ptr objects. This can create serious
|
||||
// contention in production code, but is acceptable in a testing
|
||||
// framework.
|
||||
|
||||
// Join an existing circle.
|
||||
// L < g_linked_ptr_mutex
|
||||
void join(linked_ptr_internal const* ptr) {
|
||||
MutexLock lock(&g_linked_ptr_mutex);
|
||||
|
||||
linked_ptr_internal const* p = ptr;
|
||||
while (p->next_ != ptr) p = p->next_;
|
||||
p->next_ = this;
|
||||
next_ = ptr;
|
||||
}
|
||||
|
||||
// Leave whatever circle we're part of. Returns true if we were the
|
||||
// last member of the circle. Once this is done, you can join() another.
|
||||
// L < g_linked_ptr_mutex
|
||||
bool depart() {
|
||||
MutexLock lock(&g_linked_ptr_mutex);
|
||||
|
||||
if (next_ == this) return true;
|
||||
linked_ptr_internal const* p = next_;
|
||||
while (p->next_ != this) p = p->next_;
|
||||
p->next_ = next_;
|
||||
return false;
|
||||
}
|
||||
|
||||
private:
|
||||
mutable linked_ptr_internal const* next_;
|
||||
};
|
||||
|
||||
template <typename T>
|
||||
class linked_ptr {
|
||||
public:
|
||||
typedef T element_type;
|
||||
|
||||
// Take over ownership of a raw pointer. This should happen as soon as
|
||||
// possible after the object is created.
|
||||
explicit linked_ptr(T* ptr = NULL) { capture(ptr); }
|
||||
~linked_ptr() { depart(); }
|
||||
|
||||
// Copy an existing linked_ptr<>, adding ourselves to the list of references.
|
||||
template <typename U> linked_ptr(linked_ptr<U> const& ptr) { copy(&ptr); }
|
||||
linked_ptr(linked_ptr const& ptr) { // NOLINT
|
||||
assert(&ptr != this);
|
||||
copy(&ptr);
|
||||
}
|
||||
|
||||
// Assignment releases the old value and acquires the new.
|
||||
template <typename U> linked_ptr& operator=(linked_ptr<U> const& ptr) {
|
||||
depart();
|
||||
copy(&ptr);
|
||||
return *this;
|
||||
}
|
||||
|
||||
linked_ptr& operator=(linked_ptr const& ptr) {
|
||||
if (&ptr != this) {
|
||||
depart();
|
||||
copy(&ptr);
|
||||
}
|
||||
return *this;
|
||||
}
|
||||
|
||||
// Smart pointer members.
|
||||
void reset(T* ptr = NULL) {
|
||||
depart();
|
||||
capture(ptr);
|
||||
}
|
||||
T* get() const { return value_; }
|
||||
T* operator->() const { return value_; }
|
||||
T& operator*() const { return *value_; }
|
||||
// Release ownership of the pointed object and returns it.
|
||||
// Sole ownership by this linked_ptr object is required.
|
||||
T* release() {
|
||||
bool last = link_.depart();
|
||||
assert(last);
|
||||
T* v = value_;
|
||||
value_ = NULL;
|
||||
return v;
|
||||
}
|
||||
|
||||
bool operator==(T* p) const { return value_ == p; }
|
||||
bool operator!=(T* p) const { return value_ != p; }
|
||||
template <typename U>
|
||||
bool operator==(linked_ptr<U> const& ptr) const {
|
||||
return value_ == ptr.get();
|
||||
}
|
||||
template <typename U>
|
||||
bool operator!=(linked_ptr<U> const& ptr) const {
|
||||
return value_ != ptr.get();
|
||||
}
|
||||
|
||||
private:
|
||||
template <typename U>
|
||||
friend class linked_ptr;
|
||||
|
||||
T* value_;
|
||||
linked_ptr_internal link_;
|
||||
|
||||
void depart() {
|
||||
if (link_.depart()) delete value_;
|
||||
}
|
||||
|
||||
void capture(T* ptr) {
|
||||
value_ = ptr;
|
||||
link_.join_new();
|
||||
}
|
||||
|
||||
template <typename U> void copy(linked_ptr<U> const* ptr) {
|
||||
value_ = ptr->get();
|
||||
if (value_)
|
||||
link_.join(&ptr->link_);
|
||||
else
|
||||
link_.join_new();
|
||||
}
|
||||
};
|
||||
|
||||
template<typename T> inline
|
||||
bool operator==(T* ptr, const linked_ptr<T>& x) {
|
||||
return ptr == x.get();
|
||||
}
|
||||
|
||||
template<typename T> inline
|
||||
bool operator!=(T* ptr, const linked_ptr<T>& x) {
|
||||
return ptr != x.get();
|
||||
}
|
||||
|
||||
// A function to convert T* into linked_ptr<T>
|
||||
// Doing e.g. make_linked_ptr(new FooBarBaz<type>(arg)) is a shorter notation
|
||||
// for linked_ptr<FooBarBaz<type> >(new FooBarBaz<type>(arg))
|
||||
template <typename T>
|
||||
linked_ptr<T> make_linked_ptr(T* ptr) {
|
||||
return linked_ptr<T>(ptr);
|
||||
}
|
||||
|
||||
} // namespace internal
|
||||
} // namespace testing
|
||||
|
||||
#endif // GTEST_INCLUDE_GTEST_INTERNAL_GTEST_LINKED_PTR_H_
|
||||
|
||||
+4803
-4803
File diff suppressed because it is too large
Load Diff
+638
-638
File diff suppressed because it is too large
Load Diff
+1084
-1084
File diff suppressed because it is too large
Load Diff
+348
-348
@@ -1,348 +1,348 @@
|
||||
// Copyright 2005, 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.
|
||||
//
|
||||
// Authors: wan@google.com (Zhanyong Wan), eefacm@gmail.com (Sean Mcafee)
|
||||
//
|
||||
// The Google C++ Testing Framework (Google Test)
|
||||
//
|
||||
// This header file declares the String class and functions used internally by
|
||||
// Google Test. They are subject to change without notice. They should not used
|
||||
// by code external to Google Test.
|
||||
//
|
||||
// This header file is #included by <gtest/internal/gtest-internal.h>.
|
||||
// It should not be #included by other files.
|
||||
|
||||
#ifndef GTEST_INCLUDE_GTEST_INTERNAL_GTEST_STRING_H_
|
||||
#define GTEST_INCLUDE_GTEST_INTERNAL_GTEST_STRING_H_
|
||||
|
||||
#include <string.h>
|
||||
#include <gtest/internal/gtest-port.h>
|
||||
|
||||
#if GTEST_HAS_GLOBAL_STRING || GTEST_HAS_STD_STRING
|
||||
#include <string>
|
||||
#endif // GTEST_HAS_GLOBAL_STRING || GTEST_HAS_STD_STRING
|
||||
|
||||
namespace testing {
|
||||
namespace internal {
|
||||
|
||||
// String - a UTF-8 string class.
|
||||
//
|
||||
// We cannot use std::string as Microsoft's STL implementation in
|
||||
// Visual C++ 7.1 has problems when exception is disabled. There is a
|
||||
// hack to work around this, but we've seen cases where the hack fails
|
||||
// to work.
|
||||
//
|
||||
// Also, String is different from std::string in that it can represent
|
||||
// both NULL and the empty string, while std::string cannot represent
|
||||
// NULL.
|
||||
//
|
||||
// NULL and the empty string are considered different. NULL is less
|
||||
// than anything (including the empty string) except itself.
|
||||
//
|
||||
// This class only provides minimum functionality necessary for
|
||||
// implementing Google Test. We do not intend to implement a full-fledged
|
||||
// string class here.
|
||||
//
|
||||
// Since the purpose of this class is to provide a substitute for
|
||||
// std::string on platforms where it cannot be used, we define a copy
|
||||
// constructor and assignment operators such that we don't need
|
||||
// conditional compilation in a lot of places.
|
||||
//
|
||||
// In order to make the representation efficient, the d'tor of String
|
||||
// is not virtual. Therefore DO NOT INHERIT FROM String.
|
||||
class String {
|
||||
public:
|
||||
// Static utility methods
|
||||
|
||||
// Returns the input enclosed in double quotes if it's not NULL;
|
||||
// otherwise returns "(null)". For example, "\"Hello\"" is returned
|
||||
// for input "Hello".
|
||||
//
|
||||
// This is useful for printing a C string in the syntax of a literal.
|
||||
//
|
||||
// Known issue: escape sequences are not handled yet.
|
||||
static String ShowCStringQuoted(const char* c_str);
|
||||
|
||||
// Clones a 0-terminated C string, allocating memory using new. The
|
||||
// caller is responsible for deleting the return value using
|
||||
// delete[]. Returns the cloned string, or NULL if the input is
|
||||
// NULL.
|
||||
//
|
||||
// This is different from strdup() in string.h, which allocates
|
||||
// memory using malloc().
|
||||
static const char* CloneCString(const char* c_str);
|
||||
|
||||
#if GTEST_OS_WINDOWS_MOBILE
|
||||
// Windows CE does not have the 'ANSI' versions of Win32 APIs. To be
|
||||
// able to pass strings to Win32 APIs on CE we need to convert them
|
||||
// to 'Unicode', UTF-16.
|
||||
|
||||
// Creates a UTF-16 wide string from the given ANSI string, allocating
|
||||
// memory using new. The caller is responsible for deleting the return
|
||||
// value using delete[]. Returns the wide string, or NULL if the
|
||||
// input is NULL.
|
||||
//
|
||||
// The wide string is created using the ANSI codepage (CP_ACP) to
|
||||
// match the behaviour of the ANSI versions of Win32 calls and the
|
||||
// C runtime.
|
||||
static LPCWSTR AnsiToUtf16(const char* c_str);
|
||||
|
||||
// Creates an ANSI string from the given wide string, allocating
|
||||
// memory using new. The caller is responsible for deleting the return
|
||||
// value using delete[]. Returns the ANSI string, or NULL if the
|
||||
// input is NULL.
|
||||
//
|
||||
// The returned string is created using the ANSI codepage (CP_ACP) to
|
||||
// match the behaviour of the ANSI versions of Win32 calls and the
|
||||
// C runtime.
|
||||
static const char* Utf16ToAnsi(LPCWSTR utf16_str);
|
||||
#endif
|
||||
|
||||
// Compares two C strings. Returns true iff they have the same content.
|
||||
//
|
||||
// Unlike strcmp(), this function can handle NULL argument(s). A
|
||||
// NULL C string is considered different to any non-NULL C string,
|
||||
// including the empty string.
|
||||
static bool CStringEquals(const char* lhs, const char* rhs);
|
||||
|
||||
// Converts a wide C string to a String using the UTF-8 encoding.
|
||||
// NULL will be converted to "(null)". If an error occurred during
|
||||
// the conversion, "(failed to convert from wide string)" is
|
||||
// returned.
|
||||
static String ShowWideCString(const wchar_t* wide_c_str);
|
||||
|
||||
// Similar to ShowWideCString(), except that this function encloses
|
||||
// the converted string in double quotes.
|
||||
static String ShowWideCStringQuoted(const wchar_t* wide_c_str);
|
||||
|
||||
// Compares two wide C strings. Returns true iff they have the same
|
||||
// content.
|
||||
//
|
||||
// Unlike wcscmp(), this function can handle NULL argument(s). A
|
||||
// NULL C string is considered different to any non-NULL C string,
|
||||
// including the empty string.
|
||||
static bool WideCStringEquals(const wchar_t* lhs, const wchar_t* rhs);
|
||||
|
||||
// Compares two C strings, ignoring case. Returns true iff they
|
||||
// have the same content.
|
||||
//
|
||||
// Unlike strcasecmp(), this function can handle NULL argument(s).
|
||||
// A NULL C string is considered different to any non-NULL C string,
|
||||
// including the empty string.
|
||||
static bool CaseInsensitiveCStringEquals(const char* lhs,
|
||||
const char* rhs);
|
||||
|
||||
// Compares two wide C strings, ignoring case. Returns true iff they
|
||||
// have the same content.
|
||||
//
|
||||
// Unlike wcscasecmp(), this function can handle NULL argument(s).
|
||||
// A NULL C string is considered different to any non-NULL wide C string,
|
||||
// including the empty string.
|
||||
// NB: The implementations on different platforms slightly differ.
|
||||
// On windows, this method uses _wcsicmp which compares according to LC_CTYPE
|
||||
// environment variable. On GNU platform this method uses wcscasecmp
|
||||
// which compares according to LC_CTYPE category of the current locale.
|
||||
// On MacOS X, it uses towlower, which also uses LC_CTYPE category of the
|
||||
// current locale.
|
||||
static bool CaseInsensitiveWideCStringEquals(const wchar_t* lhs,
|
||||
const wchar_t* rhs);
|
||||
|
||||
// Formats a list of arguments to a String, using the same format
|
||||
// spec string as for printf.
|
||||
//
|
||||
// We do not use the StringPrintf class as it is not universally
|
||||
// available.
|
||||
//
|
||||
// The result is limited to 4096 characters (including the tailing
|
||||
// 0). If 4096 characters are not enough to format the input,
|
||||
// "<buffer exceeded>" is returned.
|
||||
static String Format(const char* format, ...);
|
||||
|
||||
// C'tors
|
||||
|
||||
// The default c'tor constructs a NULL string.
|
||||
String() : c_str_(NULL), length_(0) {}
|
||||
|
||||
// Constructs a String by cloning a 0-terminated C string.
|
||||
String(const char* c_str) { // NOLINT
|
||||
if (c_str == NULL) {
|
||||
c_str_ = NULL;
|
||||
length_ = 0;
|
||||
} else {
|
||||
ConstructNonNull(c_str, strlen(c_str));
|
||||
}
|
||||
}
|
||||
|
||||
// Constructs a String by copying a given number of chars from a
|
||||
// buffer. E.g. String("hello", 3) creates the string "hel",
|
||||
// String("a\0bcd", 4) creates "a\0bc", String(NULL, 0) creates "",
|
||||
// and String(NULL, 1) results in access violation.
|
||||
String(const char* buffer, size_t length) {
|
||||
ConstructNonNull(buffer, length);
|
||||
}
|
||||
|
||||
// The copy c'tor creates a new copy of the string. The two
|
||||
// String objects do not share content.
|
||||
String(const String& str) : c_str_(NULL), length_(0) { *this = str; }
|
||||
|
||||
// D'tor. String is intended to be a final class, so the d'tor
|
||||
// doesn't need to be virtual.
|
||||
~String() { delete[] c_str_; }
|
||||
|
||||
// Allows a String to be implicitly converted to an ::std::string or
|
||||
// ::string, and vice versa. Converting a String containing a NULL
|
||||
// pointer to ::std::string or ::string is undefined behavior.
|
||||
// Converting a ::std::string or ::string containing an embedded NUL
|
||||
// character to a String will result in the prefix up to the first
|
||||
// NUL character.
|
||||
#if GTEST_HAS_STD_STRING
|
||||
String(const ::std::string& str) {
|
||||
ConstructNonNull(str.c_str(), str.length());
|
||||
}
|
||||
|
||||
operator ::std::string() const { return ::std::string(c_str(), length()); }
|
||||
#endif // GTEST_HAS_STD_STRING
|
||||
|
||||
#if GTEST_HAS_GLOBAL_STRING
|
||||
String(const ::string& str) {
|
||||
ConstructNonNull(str.c_str(), str.length());
|
||||
}
|
||||
|
||||
operator ::string() const { return ::string(c_str(), length()); }
|
||||
#endif // GTEST_HAS_GLOBAL_STRING
|
||||
|
||||
// Returns true iff this is an empty string (i.e. "").
|
||||
bool empty() const { return (c_str() != NULL) && (length() == 0); }
|
||||
|
||||
// Compares this with another String.
|
||||
// Returns < 0 if this is less than rhs, 0 if this is equal to rhs, or > 0
|
||||
// if this is greater than rhs.
|
||||
int Compare(const String& rhs) const;
|
||||
|
||||
// Returns true iff this String equals the given C string. A NULL
|
||||
// string and a non-NULL string are considered not equal.
|
||||
bool operator==(const char* c_str) const { return Compare(c_str) == 0; }
|
||||
|
||||
// Returns true iff this String is less than the given String. A
|
||||
// NULL string is considered less than "".
|
||||
bool operator<(const String& rhs) const { return Compare(rhs) < 0; }
|
||||
|
||||
// Returns true iff this String doesn't equal the given C string. A NULL
|
||||
// string and a non-NULL string are considered not equal.
|
||||
bool operator!=(const char* c_str) const { return !(*this == c_str); }
|
||||
|
||||
// Returns true iff this String ends with the given suffix. *Any*
|
||||
// String is considered to end with a NULL or empty suffix.
|
||||
bool EndsWith(const char* suffix) const;
|
||||
|
||||
// Returns true iff this String ends with the given suffix, not considering
|
||||
// case. Any String is considered to end with a NULL or empty suffix.
|
||||
bool EndsWithCaseInsensitive(const char* suffix) const;
|
||||
|
||||
// Returns the length of the encapsulated string, or 0 if the
|
||||
// string is NULL.
|
||||
size_t length() const { return length_; }
|
||||
|
||||
// Gets the 0-terminated C string this String object represents.
|
||||
// The String object still owns the string. Therefore the caller
|
||||
// should NOT delete the return value.
|
||||
const char* c_str() const { return c_str_; }
|
||||
|
||||
// Assigns a C string to this object. Self-assignment works.
|
||||
const String& operator=(const char* c_str) { return *this = String(c_str); }
|
||||
|
||||
// Assigns a String object to this object. Self-assignment works.
|
||||
const String& operator=(const String& rhs) {
|
||||
if (this != &rhs) {
|
||||
delete[] c_str_;
|
||||
if (rhs.c_str() == NULL) {
|
||||
c_str_ = NULL;
|
||||
length_ = 0;
|
||||
} else {
|
||||
ConstructNonNull(rhs.c_str(), rhs.length());
|
||||
}
|
||||
}
|
||||
|
||||
return *this;
|
||||
}
|
||||
|
||||
private:
|
||||
// Constructs a non-NULL String from the given content. This
|
||||
// function can only be called when data_ has not been allocated.
|
||||
// ConstructNonNull(NULL, 0) results in an empty string ("").
|
||||
// ConstructNonNull(NULL, non_zero) is undefined behavior.
|
||||
void ConstructNonNull(const char* buffer, size_t length) {
|
||||
char* const str = new char[length + 1];
|
||||
memcpy(str, buffer, length);
|
||||
str[length] = '\0';
|
||||
c_str_ = str;
|
||||
length_ = length;
|
||||
}
|
||||
|
||||
const char* c_str_;
|
||||
size_t length_;
|
||||
}; // class String
|
||||
|
||||
// Streams a String to an ostream. Each '\0' character in the String
|
||||
// is replaced with "\\0".
|
||||
inline ::std::ostream& operator<<(::std::ostream& os, const String& str) {
|
||||
if (str.c_str() == NULL) {
|
||||
os << "(null)";
|
||||
} else {
|
||||
const char* const c_str = str.c_str();
|
||||
for (size_t i = 0; i != str.length(); i++) {
|
||||
if (c_str[i] == '\0') {
|
||||
os << "\\0";
|
||||
} else {
|
||||
os << c_str[i];
|
||||
}
|
||||
}
|
||||
}
|
||||
return os;
|
||||
}
|
||||
|
||||
// Gets the content of the StrStream's buffer as a String. Each '\0'
|
||||
// character in the buffer is replaced with "\\0".
|
||||
String StrStreamToString(StrStream* stream);
|
||||
|
||||
// Converts a streamable value to a String. A NULL pointer is
|
||||
// converted to "(null)". When the input value is a ::string,
|
||||
// ::std::string, ::wstring, or ::std::wstring object, each NUL
|
||||
// character in it is replaced with "\\0".
|
||||
|
||||
// Declared here but defined in gtest.h, so that it has access
|
||||
// to the definition of the Message class, required by the ARM
|
||||
// compiler.
|
||||
template <typename T>
|
||||
String StreamableToString(const T& streamable);
|
||||
|
||||
} // namespace internal
|
||||
} // namespace testing
|
||||
|
||||
#endif // GTEST_INCLUDE_GTEST_INTERNAL_GTEST_STRING_H_
|
||||
// Copyright 2005, 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.
|
||||
//
|
||||
// Authors: wan@google.com (Zhanyong Wan), eefacm@gmail.com (Sean Mcafee)
|
||||
//
|
||||
// The Google C++ Testing Framework (Google Test)
|
||||
//
|
||||
// This header file declares the String class and functions used internally by
|
||||
// Google Test. They are subject to change without notice. They should not used
|
||||
// by code external to Google Test.
|
||||
//
|
||||
// This header file is #included by <gtest/internal/gtest-internal.h>.
|
||||
// It should not be #included by other files.
|
||||
|
||||
#ifndef GTEST_INCLUDE_GTEST_INTERNAL_GTEST_STRING_H_
|
||||
#define GTEST_INCLUDE_GTEST_INTERNAL_GTEST_STRING_H_
|
||||
|
||||
#include <string.h>
|
||||
#include <gtest/internal/gtest-port.h>
|
||||
|
||||
#if GTEST_HAS_GLOBAL_STRING || GTEST_HAS_STD_STRING
|
||||
#include <string>
|
||||
#endif // GTEST_HAS_GLOBAL_STRING || GTEST_HAS_STD_STRING
|
||||
|
||||
namespace testing {
|
||||
namespace internal {
|
||||
|
||||
// String - a UTF-8 string class.
|
||||
//
|
||||
// We cannot use std::string as Microsoft's STL implementation in
|
||||
// Visual C++ 7.1 has problems when exception is disabled. There is a
|
||||
// hack to work around this, but we've seen cases where the hack fails
|
||||
// to work.
|
||||
//
|
||||
// Also, String is different from std::string in that it can represent
|
||||
// both NULL and the empty string, while std::string cannot represent
|
||||
// NULL.
|
||||
//
|
||||
// NULL and the empty string are considered different. NULL is less
|
||||
// than anything (including the empty string) except itself.
|
||||
//
|
||||
// This class only provides minimum functionality necessary for
|
||||
// implementing Google Test. We do not intend to implement a full-fledged
|
||||
// string class here.
|
||||
//
|
||||
// Since the purpose of this class is to provide a substitute for
|
||||
// std::string on platforms where it cannot be used, we define a copy
|
||||
// constructor and assignment operators such that we don't need
|
||||
// conditional compilation in a lot of places.
|
||||
//
|
||||
// In order to make the representation efficient, the d'tor of String
|
||||
// is not virtual. Therefore DO NOT INHERIT FROM String.
|
||||
class String {
|
||||
public:
|
||||
// Static utility methods
|
||||
|
||||
// Returns the input enclosed in double quotes if it's not NULL;
|
||||
// otherwise returns "(null)". For example, "\"Hello\"" is returned
|
||||
// for input "Hello".
|
||||
//
|
||||
// This is useful for printing a C string in the syntax of a literal.
|
||||
//
|
||||
// Known issue: escape sequences are not handled yet.
|
||||
static String ShowCStringQuoted(const char* c_str);
|
||||
|
||||
// Clones a 0-terminated C string, allocating memory using new. The
|
||||
// caller is responsible for deleting the return value using
|
||||
// delete[]. Returns the cloned string, or NULL if the input is
|
||||
// NULL.
|
||||
//
|
||||
// This is different from strdup() in string.h, which allocates
|
||||
// memory using malloc().
|
||||
static const char* CloneCString(const char* c_str);
|
||||
|
||||
#if GTEST_OS_WINDOWS_MOBILE
|
||||
// Windows CE does not have the 'ANSI' versions of Win32 APIs. To be
|
||||
// able to pass strings to Win32 APIs on CE we need to convert them
|
||||
// to 'Unicode', UTF-16.
|
||||
|
||||
// Creates a UTF-16 wide string from the given ANSI string, allocating
|
||||
// memory using new. The caller is responsible for deleting the return
|
||||
// value using delete[]. Returns the wide string, or NULL if the
|
||||
// input is NULL.
|
||||
//
|
||||
// The wide string is created using the ANSI codepage (CP_ACP) to
|
||||
// match the behaviour of the ANSI versions of Win32 calls and the
|
||||
// C runtime.
|
||||
static LPCWSTR AnsiToUtf16(const char* c_str);
|
||||
|
||||
// Creates an ANSI string from the given wide string, allocating
|
||||
// memory using new. The caller is responsible for deleting the return
|
||||
// value using delete[]. Returns the ANSI string, or NULL if the
|
||||
// input is NULL.
|
||||
//
|
||||
// The returned string is created using the ANSI codepage (CP_ACP) to
|
||||
// match the behaviour of the ANSI versions of Win32 calls and the
|
||||
// C runtime.
|
||||
static const char* Utf16ToAnsi(LPCWSTR utf16_str);
|
||||
#endif
|
||||
|
||||
// Compares two C strings. Returns true iff they have the same content.
|
||||
//
|
||||
// Unlike strcmp(), this function can handle NULL argument(s). A
|
||||
// NULL C string is considered different to any non-NULL C string,
|
||||
// including the empty string.
|
||||
static bool CStringEquals(const char* lhs, const char* rhs);
|
||||
|
||||
// Converts a wide C string to a String using the UTF-8 encoding.
|
||||
// NULL will be converted to "(null)". If an error occurred during
|
||||
// the conversion, "(failed to convert from wide string)" is
|
||||
// returned.
|
||||
static String ShowWideCString(const wchar_t* wide_c_str);
|
||||
|
||||
// Similar to ShowWideCString(), except that this function encloses
|
||||
// the converted string in double quotes.
|
||||
static String ShowWideCStringQuoted(const wchar_t* wide_c_str);
|
||||
|
||||
// Compares two wide C strings. Returns true iff they have the same
|
||||
// content.
|
||||
//
|
||||
// Unlike wcscmp(), this function can handle NULL argument(s). A
|
||||
// NULL C string is considered different to any non-NULL C string,
|
||||
// including the empty string.
|
||||
static bool WideCStringEquals(const wchar_t* lhs, const wchar_t* rhs);
|
||||
|
||||
// Compares two C strings, ignoring case. Returns true iff they
|
||||
// have the same content.
|
||||
//
|
||||
// Unlike strcasecmp(), this function can handle NULL argument(s).
|
||||
// A NULL C string is considered different to any non-NULL C string,
|
||||
// including the empty string.
|
||||
static bool CaseInsensitiveCStringEquals(const char* lhs,
|
||||
const char* rhs);
|
||||
|
||||
// Compares two wide C strings, ignoring case. Returns true iff they
|
||||
// have the same content.
|
||||
//
|
||||
// Unlike wcscasecmp(), this function can handle NULL argument(s).
|
||||
// A NULL C string is considered different to any non-NULL wide C string,
|
||||
// including the empty string.
|
||||
// NB: The implementations on different platforms slightly differ.
|
||||
// On windows, this method uses _wcsicmp which compares according to LC_CTYPE
|
||||
// environment variable. On GNU platform this method uses wcscasecmp
|
||||
// which compares according to LC_CTYPE category of the current locale.
|
||||
// On MacOS X, it uses towlower, which also uses LC_CTYPE category of the
|
||||
// current locale.
|
||||
static bool CaseInsensitiveWideCStringEquals(const wchar_t* lhs,
|
||||
const wchar_t* rhs);
|
||||
|
||||
// Formats a list of arguments to a String, using the same format
|
||||
// spec string as for printf.
|
||||
//
|
||||
// We do not use the StringPrintf class as it is not universally
|
||||
// available.
|
||||
//
|
||||
// The result is limited to 4096 characters (including the tailing
|
||||
// 0). If 4096 characters are not enough to format the input,
|
||||
// "<buffer exceeded>" is returned.
|
||||
static String Format(const char* format, ...);
|
||||
|
||||
// C'tors
|
||||
|
||||
// The default c'tor constructs a NULL string.
|
||||
String() : c_str_(NULL), length_(0) {}
|
||||
|
||||
// Constructs a String by cloning a 0-terminated C string.
|
||||
String(const char* c_str) { // NOLINT
|
||||
if (c_str == NULL) {
|
||||
c_str_ = NULL;
|
||||
length_ = 0;
|
||||
} else {
|
||||
ConstructNonNull(c_str, strlen(c_str));
|
||||
}
|
||||
}
|
||||
|
||||
// Constructs a String by copying a given number of chars from a
|
||||
// buffer. E.g. String("hello", 3) creates the string "hel",
|
||||
// String("a\0bcd", 4) creates "a\0bc", String(NULL, 0) creates "",
|
||||
// and String(NULL, 1) results in access violation.
|
||||
String(const char* buffer, size_t length) {
|
||||
ConstructNonNull(buffer, length);
|
||||
}
|
||||
|
||||
// The copy c'tor creates a new copy of the string. The two
|
||||
// String objects do not share content.
|
||||
String(const String& str) : c_str_(NULL), length_(0) { *this = str; }
|
||||
|
||||
// D'tor. String is intended to be a final class, so the d'tor
|
||||
// doesn't need to be virtual.
|
||||
~String() { delete[] c_str_; }
|
||||
|
||||
// Allows a String to be implicitly converted to an ::std::string or
|
||||
// ::string, and vice versa. Converting a String containing a NULL
|
||||
// pointer to ::std::string or ::string is undefined behavior.
|
||||
// Converting a ::std::string or ::string containing an embedded NUL
|
||||
// character to a String will result in the prefix up to the first
|
||||
// NUL character.
|
||||
#if GTEST_HAS_STD_STRING
|
||||
String(const ::std::string& str) {
|
||||
ConstructNonNull(str.c_str(), str.length());
|
||||
}
|
||||
|
||||
operator ::std::string() const { return ::std::string(c_str(), length()); }
|
||||
#endif // GTEST_HAS_STD_STRING
|
||||
|
||||
#if GTEST_HAS_GLOBAL_STRING
|
||||
String(const ::string& str) {
|
||||
ConstructNonNull(str.c_str(), str.length());
|
||||
}
|
||||
|
||||
operator ::string() const { return ::string(c_str(), length()); }
|
||||
#endif // GTEST_HAS_GLOBAL_STRING
|
||||
|
||||
// Returns true iff this is an empty string (i.e. "").
|
||||
bool empty() const { return (c_str() != NULL) && (length() == 0); }
|
||||
|
||||
// Compares this with another String.
|
||||
// Returns < 0 if this is less than rhs, 0 if this is equal to rhs, or > 0
|
||||
// if this is greater than rhs.
|
||||
int Compare(const String& rhs) const;
|
||||
|
||||
// Returns true iff this String equals the given C string. A NULL
|
||||
// string and a non-NULL string are considered not equal.
|
||||
bool operator==(const char* c_str) const { return Compare(c_str) == 0; }
|
||||
|
||||
// Returns true iff this String is less than the given String. A
|
||||
// NULL string is considered less than "".
|
||||
bool operator<(const String& rhs) const { return Compare(rhs) < 0; }
|
||||
|
||||
// Returns true iff this String doesn't equal the given C string. A NULL
|
||||
// string and a non-NULL string are considered not equal.
|
||||
bool operator!=(const char* c_str) const { return !(*this == c_str); }
|
||||
|
||||
// Returns true iff this String ends with the given suffix. *Any*
|
||||
// String is considered to end with a NULL or empty suffix.
|
||||
bool EndsWith(const char* suffix) const;
|
||||
|
||||
// Returns true iff this String ends with the given suffix, not considering
|
||||
// case. Any String is considered to end with a NULL or empty suffix.
|
||||
bool EndsWithCaseInsensitive(const char* suffix) const;
|
||||
|
||||
// Returns the length of the encapsulated string, or 0 if the
|
||||
// string is NULL.
|
||||
size_t length() const { return length_; }
|
||||
|
||||
// Gets the 0-terminated C string this String object represents.
|
||||
// The String object still owns the string. Therefore the caller
|
||||
// should NOT delete the return value.
|
||||
const char* c_str() const { return c_str_; }
|
||||
|
||||
// Assigns a C string to this object. Self-assignment works.
|
||||
const String& operator=(const char* c_str) { return *this = String(c_str); }
|
||||
|
||||
// Assigns a String object to this object. Self-assignment works.
|
||||
const String& operator=(const String& rhs) {
|
||||
if (this != &rhs) {
|
||||
delete[] c_str_;
|
||||
if (rhs.c_str() == NULL) {
|
||||
c_str_ = NULL;
|
||||
length_ = 0;
|
||||
} else {
|
||||
ConstructNonNull(rhs.c_str(), rhs.length());
|
||||
}
|
||||
}
|
||||
|
||||
return *this;
|
||||
}
|
||||
|
||||
private:
|
||||
// Constructs a non-NULL String from the given content. This
|
||||
// function can only be called when data_ has not been allocated.
|
||||
// ConstructNonNull(NULL, 0) results in an empty string ("").
|
||||
// ConstructNonNull(NULL, non_zero) is undefined behavior.
|
||||
void ConstructNonNull(const char* buffer, size_t length) {
|
||||
char* const str = new char[length + 1];
|
||||
memcpy(str, buffer, length);
|
||||
str[length] = '\0';
|
||||
c_str_ = str;
|
||||
length_ = length;
|
||||
}
|
||||
|
||||
const char* c_str_;
|
||||
size_t length_;
|
||||
}; // class String
|
||||
|
||||
// Streams a String to an ostream. Each '\0' character in the String
|
||||
// is replaced with "\\0".
|
||||
inline ::std::ostream& operator<<(::std::ostream& os, const String& str) {
|
||||
if (str.c_str() == NULL) {
|
||||
os << "(null)";
|
||||
} else {
|
||||
const char* const c_str = str.c_str();
|
||||
for (size_t i = 0; i != str.length(); i++) {
|
||||
if (c_str[i] == '\0') {
|
||||
os << "\\0";
|
||||
} else {
|
||||
os << c_str[i];
|
||||
}
|
||||
}
|
||||
}
|
||||
return os;
|
||||
}
|
||||
|
||||
// Gets the content of the StrStream's buffer as a String. Each '\0'
|
||||
// character in the buffer is replaced with "\\0".
|
||||
String StrStreamToString(StrStream* stream);
|
||||
|
||||
// Converts a streamable value to a String. A NULL pointer is
|
||||
// converted to "(null)". When the input value is a ::string,
|
||||
// ::std::string, ::wstring, or ::std::wstring object, each NUL
|
||||
// character in it is replaced with "\\0".
|
||||
|
||||
// Declared here but defined in gtest.h, so that it has access
|
||||
// to the definition of the Message class, required by the ARM
|
||||
// compiler.
|
||||
template <typename T>
|
||||
String StreamableToString(const T& streamable);
|
||||
|
||||
} // namespace internal
|
||||
} // namespace testing
|
||||
|
||||
#endif // GTEST_INCLUDE_GTEST_INTERNAL_GTEST_STRING_H_
|
||||
|
||||
+966
-966
File diff suppressed because it is too large
Load Diff
+3321
-3321
File diff suppressed because it is too large
Load Diff
+120
-120
@@ -1,120 +1,120 @@
|
||||
// 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.
|
||||
//
|
||||
// Author: wan@google.com (Zhanyong Wan)
|
||||
// Author: vladl@google.com (Vlad Losev)
|
||||
|
||||
// This provides interface PrimeTable that determines whether a number is a
|
||||
// prime and determines a next prime number. This interface is used
|
||||
// in Google Test samples demonstrating use of parameterized tests.
|
||||
|
||||
#ifndef GTEST_SAMPLES_PRIME_TABLES_H_
|
||||
#define GTEST_SAMPLES_PRIME_TABLES_H_
|
||||
|
||||
#include <algorithm>
|
||||
|
||||
// The prime table interface.
|
||||
class PrimeTable {
|
||||
public:
|
||||
virtual ~PrimeTable() {}
|
||||
|
||||
// Returns true iff n is a prime number.
|
||||
virtual bool IsPrime(int n) const = 0;
|
||||
|
||||
// Returns the smallest prime number greater than p; or returns -1
|
||||
// if the next prime is beyond the capacity of the table.
|
||||
virtual int GetNextPrime(int p) const = 0;
|
||||
};
|
||||
|
||||
// Implementation #1 calculates the primes on-the-fly.
|
||||
class OnTheFlyPrimeTable : public PrimeTable {
|
||||
public:
|
||||
virtual bool IsPrime(int n) const {
|
||||
if (n <= 1) return false;
|
||||
|
||||
for (int i = 2; i*i <= n; i++) {
|
||||
// n is divisible by an integer other than 1 and itself.
|
||||
if ((n % i) == 0) return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
virtual int GetNextPrime(int p) const {
|
||||
for (int n = p + 1; n > 0; n++) {
|
||||
if (IsPrime(n)) return n;
|
||||
}
|
||||
|
||||
return -1;
|
||||
}
|
||||
};
|
||||
|
||||
// Implementation #2 pre-calculates the primes and stores the result
|
||||
// in an array.
|
||||
class PreCalculatedPrimeTable : public PrimeTable {
|
||||
public:
|
||||
// 'max' specifies the maximum number the prime table holds.
|
||||
explicit PreCalculatedPrimeTable(int max)
|
||||
: is_prime_size_(max + 1), is_prime_(new bool[max + 1]) {
|
||||
CalculatePrimesUpTo(max);
|
||||
}
|
||||
virtual ~PreCalculatedPrimeTable() { delete[] is_prime_; }
|
||||
|
||||
virtual bool IsPrime(int n) const {
|
||||
return 0 <= n && n < is_prime_size_ && is_prime_[n];
|
||||
}
|
||||
|
||||
virtual int GetNextPrime(int p) const {
|
||||
for (int n = p + 1; n < is_prime_size_; n++) {
|
||||
if (is_prime_[n]) return n;
|
||||
}
|
||||
|
||||
return -1;
|
||||
}
|
||||
|
||||
private:
|
||||
void CalculatePrimesUpTo(int max) {
|
||||
::std::fill(is_prime_, is_prime_ + is_prime_size_, true);
|
||||
is_prime_[0] = is_prime_[1] = false;
|
||||
|
||||
for (int i = 2; i <= max; i++) {
|
||||
if (!is_prime_[i]) continue;
|
||||
|
||||
// Marks all multiples of i (except i itself) as non-prime.
|
||||
for (int j = 2*i; j <= max; j += i) {
|
||||
is_prime_[j] = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const int is_prime_size_;
|
||||
bool* const is_prime_;
|
||||
};
|
||||
|
||||
#endif // GTEST_SAMPLES_PRIME_TABLES_H_
|
||||
// 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.
|
||||
//
|
||||
// Author: wan@google.com (Zhanyong Wan)
|
||||
// Author: vladl@google.com (Vlad Losev)
|
||||
|
||||
// This provides interface PrimeTable that determines whether a number is a
|
||||
// prime and determines a next prime number. This interface is used
|
||||
// in Google Test samples demonstrating use of parameterized tests.
|
||||
|
||||
#ifndef GTEST_SAMPLES_PRIME_TABLES_H_
|
||||
#define GTEST_SAMPLES_PRIME_TABLES_H_
|
||||
|
||||
#include <algorithm>
|
||||
|
||||
// The prime table interface.
|
||||
class PrimeTable {
|
||||
public:
|
||||
virtual ~PrimeTable() {}
|
||||
|
||||
// Returns true iff n is a prime number.
|
||||
virtual bool IsPrime(int n) const = 0;
|
||||
|
||||
// Returns the smallest prime number greater than p; or returns -1
|
||||
// if the next prime is beyond the capacity of the table.
|
||||
virtual int GetNextPrime(int p) const = 0;
|
||||
};
|
||||
|
||||
// Implementation #1 calculates the primes on-the-fly.
|
||||
class OnTheFlyPrimeTable : public PrimeTable {
|
||||
public:
|
||||
virtual bool IsPrime(int n) const {
|
||||
if (n <= 1) return false;
|
||||
|
||||
for (int i = 2; i*i <= n; i++) {
|
||||
// n is divisible by an integer other than 1 and itself.
|
||||
if ((n % i) == 0) return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
virtual int GetNextPrime(int p) const {
|
||||
for (int n = p + 1; n > 0; n++) {
|
||||
if (IsPrime(n)) return n;
|
||||
}
|
||||
|
||||
return -1;
|
||||
}
|
||||
};
|
||||
|
||||
// Implementation #2 pre-calculates the primes and stores the result
|
||||
// in an array.
|
||||
class PreCalculatedPrimeTable : public PrimeTable {
|
||||
public:
|
||||
// 'max' specifies the maximum number the prime table holds.
|
||||
explicit PreCalculatedPrimeTable(int max)
|
||||
: is_prime_size_(max + 1), is_prime_(new bool[max + 1]) {
|
||||
CalculatePrimesUpTo(max);
|
||||
}
|
||||
virtual ~PreCalculatedPrimeTable() { delete[] is_prime_; }
|
||||
|
||||
virtual bool IsPrime(int n) const {
|
||||
return 0 <= n && n < is_prime_size_ && is_prime_[n];
|
||||
}
|
||||
|
||||
virtual int GetNextPrime(int p) const {
|
||||
for (int n = p + 1; n < is_prime_size_; n++) {
|
||||
if (is_prime_[n]) return n;
|
||||
}
|
||||
|
||||
return -1;
|
||||
}
|
||||
|
||||
private:
|
||||
void CalculatePrimesUpTo(int max) {
|
||||
::std::fill(is_prime_, is_prime_ + is_prime_size_, true);
|
||||
is_prime_[0] = is_prime_[1] = false;
|
||||
|
||||
for (int i = 2; i <= max; i++) {
|
||||
if (!is_prime_[i]) continue;
|
||||
|
||||
// Marks all multiples of i (except i itself) as non-prime.
|
||||
for (int j = 2*i; j <= max; j += i) {
|
||||
is_prime_[j] = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const int is_prime_size_;
|
||||
bool* const is_prime_;
|
||||
};
|
||||
|
||||
#endif // GTEST_SAMPLES_PRIME_TABLES_H_
|
||||
|
||||
+43
-43
@@ -1,43 +1,43 @@
|
||||
// Copyright 2005, 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.
|
||||
|
||||
// A sample program demonstrating using Google C++ testing framework.
|
||||
//
|
||||
// Author: wan@google.com (Zhanyong Wan)
|
||||
|
||||
#ifndef GTEST_SAMPLES_SAMPLE1_H_
|
||||
#define GTEST_SAMPLES_SAMPLE1_H_
|
||||
|
||||
// Returns n! (the factorial of n). For negative n, n! is defined to be 1.
|
||||
int Factorial(int n);
|
||||
|
||||
// Returns true iff n is a prime number.
|
||||
bool IsPrime(int n);
|
||||
|
||||
#endif // GTEST_SAMPLES_SAMPLE1_H_
|
||||
// Copyright 2005, 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.
|
||||
|
||||
// A sample program demonstrating using Google C++ testing framework.
|
||||
//
|
||||
// Author: wan@google.com (Zhanyong Wan)
|
||||
|
||||
#ifndef GTEST_SAMPLES_SAMPLE1_H_
|
||||
#define GTEST_SAMPLES_SAMPLE1_H_
|
||||
|
||||
// Returns n! (the factorial of n). For negative n, n! is defined to be 1.
|
||||
int Factorial(int n);
|
||||
|
||||
// Returns true iff n is a prime number.
|
||||
bool IsPrime(int n);
|
||||
|
||||
#endif // GTEST_SAMPLES_SAMPLE1_H_
|
||||
|
||||
+86
-86
@@ -1,86 +1,86 @@
|
||||
// Copyright 2005, 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.
|
||||
|
||||
// A sample program demonstrating using Google C++ testing framework.
|
||||
//
|
||||
// Author: wan@google.com (Zhanyong Wan)
|
||||
|
||||
#ifndef GTEST_SAMPLES_SAMPLE2_H_
|
||||
#define GTEST_SAMPLES_SAMPLE2_H_
|
||||
|
||||
#include <string.h>
|
||||
|
||||
|
||||
// A simple string class.
|
||||
class MyString {
|
||||
private:
|
||||
const char * c_string_;
|
||||
const MyString& operator=(const MyString& rhs);
|
||||
|
||||
public:
|
||||
|
||||
// Clones a 0-terminated C string, allocating memory using new.
|
||||
static const char * CloneCString(const char * c_string);
|
||||
|
||||
////////////////////////////////////////////////////////////
|
||||
//
|
||||
// C'tors
|
||||
|
||||
// The default c'tor constructs a NULL string.
|
||||
MyString() : c_string_(NULL) {}
|
||||
|
||||
// Constructs a MyString by cloning a 0-terminated C string.
|
||||
explicit MyString(const char * c_string) : c_string_(NULL) {
|
||||
Set(c_string);
|
||||
}
|
||||
|
||||
// Copy c'tor
|
||||
MyString(const MyString& string) : c_string_(NULL) {
|
||||
Set(string.c_string_);
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////////////////
|
||||
//
|
||||
// D'tor. MyString is intended to be a final class, so the d'tor
|
||||
// doesn't need to be virtual.
|
||||
~MyString() { delete[] c_string_; }
|
||||
|
||||
// Gets the 0-terminated C string this MyString object represents.
|
||||
const char * c_string() const { return c_string_; }
|
||||
|
||||
size_t Length() const {
|
||||
return c_string_ == NULL ? 0 : strlen(c_string_);
|
||||
}
|
||||
|
||||
// Sets the 0-terminated C string this MyString object represents.
|
||||
void Set(const char * c_string);
|
||||
};
|
||||
|
||||
|
||||
#endif // GTEST_SAMPLES_SAMPLE2_H_
|
||||
// Copyright 2005, 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.
|
||||
|
||||
// A sample program demonstrating using Google C++ testing framework.
|
||||
//
|
||||
// Author: wan@google.com (Zhanyong Wan)
|
||||
|
||||
#ifndef GTEST_SAMPLES_SAMPLE2_H_
|
||||
#define GTEST_SAMPLES_SAMPLE2_H_
|
||||
|
||||
#include <string.h>
|
||||
|
||||
|
||||
// A simple string class.
|
||||
class MyString {
|
||||
private:
|
||||
const char * c_string_;
|
||||
const MyString& operator=(const MyString& rhs);
|
||||
|
||||
public:
|
||||
|
||||
// Clones a 0-terminated C string, allocating memory using new.
|
||||
static const char * CloneCString(const char * c_string);
|
||||
|
||||
////////////////////////////////////////////////////////////
|
||||
//
|
||||
// C'tors
|
||||
|
||||
// The default c'tor constructs a NULL string.
|
||||
MyString() : c_string_(NULL) {}
|
||||
|
||||
// Constructs a MyString by cloning a 0-terminated C string.
|
||||
explicit MyString(const char * c_string) : c_string_(NULL) {
|
||||
Set(c_string);
|
||||
}
|
||||
|
||||
// Copy c'tor
|
||||
MyString(const MyString& string) : c_string_(NULL) {
|
||||
Set(string.c_string_);
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////////////////
|
||||
//
|
||||
// D'tor. MyString is intended to be a final class, so the d'tor
|
||||
// doesn't need to be virtual.
|
||||
~MyString() { delete[] c_string_; }
|
||||
|
||||
// Gets the 0-terminated C string this MyString object represents.
|
||||
const char * c_string() const { return c_string_; }
|
||||
|
||||
size_t Length() const {
|
||||
return c_string_ == NULL ? 0 : strlen(c_string_);
|
||||
}
|
||||
|
||||
// Sets the 0-terminated C string this MyString object represents.
|
||||
void Set(const char * c_string);
|
||||
};
|
||||
|
||||
|
||||
#endif // GTEST_SAMPLES_SAMPLE2_H_
|
||||
|
||||
+173
-173
@@ -1,173 +1,173 @@
|
||||
// Copyright 2005, 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.
|
||||
|
||||
// A sample program demonstrating using Google C++ testing framework.
|
||||
//
|
||||
// Author: wan@google.com (Zhanyong Wan)
|
||||
|
||||
#ifndef GTEST_SAMPLES_SAMPLE3_INL_H_
|
||||
#define GTEST_SAMPLES_SAMPLE3_INL_H_
|
||||
|
||||
#include <stddef.h>
|
||||
|
||||
|
||||
// Queue is a simple queue implemented as a singled-linked list.
|
||||
//
|
||||
// The element type must support copy constructor.
|
||||
template <typename E> // E is the element type
|
||||
class Queue;
|
||||
|
||||
// QueueNode is a node in a Queue, which consists of an element of
|
||||
// type E and a pointer to the next node.
|
||||
template <typename E> // E is the element type
|
||||
class QueueNode {
|
||||
friend class Queue<E>;
|
||||
|
||||
public:
|
||||
// Gets the element in this node.
|
||||
const E & element() const { return element_; }
|
||||
|
||||
// Gets the next node in the queue.
|
||||
QueueNode * next() { return next_; }
|
||||
const QueueNode * next() const { return next_; }
|
||||
|
||||
private:
|
||||
// Creates a node with a given element value. The next pointer is
|
||||
// set to NULL.
|
||||
QueueNode(const E & element) : element_(element), next_(NULL) {}
|
||||
|
||||
// We disable the default assignment operator and copy c'tor.
|
||||
const QueueNode & operator = (const QueueNode &);
|
||||
QueueNode(const QueueNode &);
|
||||
|
||||
E element_;
|
||||
QueueNode * next_;
|
||||
};
|
||||
|
||||
template <typename E> // E is the element type.
|
||||
class Queue {
|
||||
public:
|
||||
|
||||
// Creates an empty queue.
|
||||
Queue() : head_(NULL), last_(NULL), size_(0) {}
|
||||
|
||||
// D'tor. Clears the queue.
|
||||
~Queue() { Clear(); }
|
||||
|
||||
// Clears the queue.
|
||||
void Clear() {
|
||||
if (size_ > 0) {
|
||||
// 1. Deletes every node.
|
||||
QueueNode<E> * node = head_;
|
||||
QueueNode<E> * next = node->next();
|
||||
for (; ;) {
|
||||
delete node;
|
||||
node = next;
|
||||
if (node == NULL) break;
|
||||
next = node->next();
|
||||
}
|
||||
|
||||
// 2. Resets the member variables.
|
||||
head_ = last_ = NULL;
|
||||
size_ = 0;
|
||||
}
|
||||
}
|
||||
|
||||
// Gets the number of elements.
|
||||
size_t Size() const { return size_; }
|
||||
|
||||
// Gets the first element of the queue, or NULL if the queue is empty.
|
||||
QueueNode<E> * Head() { return head_; }
|
||||
const QueueNode<E> * Head() const { return head_; }
|
||||
|
||||
// Gets the last element of the queue, or NULL if the queue is empty.
|
||||
QueueNode<E> * Last() { return last_; }
|
||||
const QueueNode<E> * Last() const { return last_; }
|
||||
|
||||
// Adds an element to the end of the queue. A copy of the element is
|
||||
// created using the copy constructor, and then stored in the queue.
|
||||
// Changes made to the element in the queue doesn't affect the source
|
||||
// object, and vice versa.
|
||||
void Enqueue(const E & element) {
|
||||
QueueNode<E> * new_node = new QueueNode<E>(element);
|
||||
|
||||
if (size_ == 0) {
|
||||
head_ = last_ = new_node;
|
||||
size_ = 1;
|
||||
} else {
|
||||
last_->next_ = new_node;
|
||||
last_ = new_node;
|
||||
size_++;
|
||||
}
|
||||
}
|
||||
|
||||
// Removes the head of the queue and returns it. Returns NULL if
|
||||
// the queue is empty.
|
||||
E * Dequeue() {
|
||||
if (size_ == 0) {
|
||||
return NULL;
|
||||
}
|
||||
|
||||
const QueueNode<E> * const old_head = head_;
|
||||
head_ = head_->next_;
|
||||
size_--;
|
||||
if (size_ == 0) {
|
||||
last_ = NULL;
|
||||
}
|
||||
|
||||
E * element = new E(old_head->element());
|
||||
delete old_head;
|
||||
|
||||
return element;
|
||||
}
|
||||
|
||||
// Applies a function/functor on each element of the queue, and
|
||||
// returns the result in a new queue. The original queue is not
|
||||
// affected.
|
||||
template <typename F>
|
||||
Queue * Map(F function) const {
|
||||
Queue * new_queue = new Queue();
|
||||
for (const QueueNode<E> * node = head_; node != NULL; node = node->next_) {
|
||||
new_queue->Enqueue(function(node->element()));
|
||||
}
|
||||
|
||||
return new_queue;
|
||||
}
|
||||
|
||||
private:
|
||||
QueueNode<E> * head_; // The first node of the queue.
|
||||
QueueNode<E> * last_; // The last node of the queue.
|
||||
size_t size_; // The number of elements in the queue.
|
||||
|
||||
// We disallow copying a queue.
|
||||
Queue(const Queue &);
|
||||
const Queue & operator = (const Queue &);
|
||||
};
|
||||
|
||||
#endif // GTEST_SAMPLES_SAMPLE3_INL_H_
|
||||
// Copyright 2005, 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.
|
||||
|
||||
// A sample program demonstrating using Google C++ testing framework.
|
||||
//
|
||||
// Author: wan@google.com (Zhanyong Wan)
|
||||
|
||||
#ifndef GTEST_SAMPLES_SAMPLE3_INL_H_
|
||||
#define GTEST_SAMPLES_SAMPLE3_INL_H_
|
||||
|
||||
#include <stddef.h>
|
||||
|
||||
|
||||
// Queue is a simple queue implemented as a singled-linked list.
|
||||
//
|
||||
// The element type must support copy constructor.
|
||||
template <typename E> // E is the element type
|
||||
class Queue;
|
||||
|
||||
// QueueNode is a node in a Queue, which consists of an element of
|
||||
// type E and a pointer to the next node.
|
||||
template <typename E> // E is the element type
|
||||
class QueueNode {
|
||||
friend class Queue<E>;
|
||||
|
||||
public:
|
||||
// Gets the element in this node.
|
||||
const E & element() const { return element_; }
|
||||
|
||||
// Gets the next node in the queue.
|
||||
QueueNode * next() { return next_; }
|
||||
const QueueNode * next() const { return next_; }
|
||||
|
||||
private:
|
||||
// Creates a node with a given element value. The next pointer is
|
||||
// set to NULL.
|
||||
QueueNode(const E & element) : element_(element), next_(NULL) {}
|
||||
|
||||
// We disable the default assignment operator and copy c'tor.
|
||||
const QueueNode & operator = (const QueueNode &);
|
||||
QueueNode(const QueueNode &);
|
||||
|
||||
E element_;
|
||||
QueueNode * next_;
|
||||
};
|
||||
|
||||
template <typename E> // E is the element type.
|
||||
class Queue {
|
||||
public:
|
||||
|
||||
// Creates an empty queue.
|
||||
Queue() : head_(NULL), last_(NULL), size_(0) {}
|
||||
|
||||
// D'tor. Clears the queue.
|
||||
~Queue() { Clear(); }
|
||||
|
||||
// Clears the queue.
|
||||
void Clear() {
|
||||
if (size_ > 0) {
|
||||
// 1. Deletes every node.
|
||||
QueueNode<E> * node = head_;
|
||||
QueueNode<E> * next = node->next();
|
||||
for (; ;) {
|
||||
delete node;
|
||||
node = next;
|
||||
if (node == NULL) break;
|
||||
next = node->next();
|
||||
}
|
||||
|
||||
// 2. Resets the member variables.
|
||||
head_ = last_ = NULL;
|
||||
size_ = 0;
|
||||
}
|
||||
}
|
||||
|
||||
// Gets the number of elements.
|
||||
size_t Size() const { return size_; }
|
||||
|
||||
// Gets the first element of the queue, or NULL if the queue is empty.
|
||||
QueueNode<E> * Head() { return head_; }
|
||||
const QueueNode<E> * Head() const { return head_; }
|
||||
|
||||
// Gets the last element of the queue, or NULL if the queue is empty.
|
||||
QueueNode<E> * Last() { return last_; }
|
||||
const QueueNode<E> * Last() const { return last_; }
|
||||
|
||||
// Adds an element to the end of the queue. A copy of the element is
|
||||
// created using the copy constructor, and then stored in the queue.
|
||||
// Changes made to the element in the queue doesn't affect the source
|
||||
// object, and vice versa.
|
||||
void Enqueue(const E & element) {
|
||||
QueueNode<E> * new_node = new QueueNode<E>(element);
|
||||
|
||||
if (size_ == 0) {
|
||||
head_ = last_ = new_node;
|
||||
size_ = 1;
|
||||
} else {
|
||||
last_->next_ = new_node;
|
||||
last_ = new_node;
|
||||
size_++;
|
||||
}
|
||||
}
|
||||
|
||||
// Removes the head of the queue and returns it. Returns NULL if
|
||||
// the queue is empty.
|
||||
E * Dequeue() {
|
||||
if (size_ == 0) {
|
||||
return NULL;
|
||||
}
|
||||
|
||||
const QueueNode<E> * const old_head = head_;
|
||||
head_ = head_->next_;
|
||||
size_--;
|
||||
if (size_ == 0) {
|
||||
last_ = NULL;
|
||||
}
|
||||
|
||||
E * element = new E(old_head->element());
|
||||
delete old_head;
|
||||
|
||||
return element;
|
||||
}
|
||||
|
||||
// Applies a function/functor on each element of the queue, and
|
||||
// returns the result in a new queue. The original queue is not
|
||||
// affected.
|
||||
template <typename F>
|
||||
Queue * Map(F function) const {
|
||||
Queue * new_queue = new Queue();
|
||||
for (const QueueNode<E> * node = head_; node != NULL; node = node->next_) {
|
||||
new_queue->Enqueue(function(node->element()));
|
||||
}
|
||||
|
||||
return new_queue;
|
||||
}
|
||||
|
||||
private:
|
||||
QueueNode<E> * head_; // The first node of the queue.
|
||||
QueueNode<E> * last_; // The last node of the queue.
|
||||
size_t size_; // The number of elements in the queue.
|
||||
|
||||
// We disallow copying a queue.
|
||||
Queue(const Queue &);
|
||||
const Queue & operator = (const Queue &);
|
||||
};
|
||||
|
||||
#endif // GTEST_SAMPLES_SAMPLE3_INL_H_
|
||||
|
||||
+53
-53
@@ -1,53 +1,53 @@
|
||||
// Copyright 2005, 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.
|
||||
|
||||
// A sample program demonstrating using Google C++ testing framework.
|
||||
//
|
||||
// Author: wan@google.com (Zhanyong Wan)
|
||||
|
||||
#ifndef GTEST_SAMPLES_SAMPLE4_H_
|
||||
#define GTEST_SAMPLES_SAMPLE4_H_
|
||||
|
||||
// A simple monotonic counter.
|
||||
class Counter {
|
||||
private:
|
||||
int counter_;
|
||||
|
||||
public:
|
||||
// Creates a counter that starts at 0.
|
||||
Counter() : counter_(0) {}
|
||||
|
||||
// Returns the current counter value, and increments it.
|
||||
int Increment();
|
||||
|
||||
// Prints the current counter value to STDOUT.
|
||||
void Print() const;
|
||||
};
|
||||
|
||||
#endif // GTEST_SAMPLES_SAMPLE4_H_
|
||||
// Copyright 2005, 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.
|
||||
|
||||
// A sample program demonstrating using Google C++ testing framework.
|
||||
//
|
||||
// Author: wan@google.com (Zhanyong Wan)
|
||||
|
||||
#ifndef GTEST_SAMPLES_SAMPLE4_H_
|
||||
#define GTEST_SAMPLES_SAMPLE4_H_
|
||||
|
||||
// A simple monotonic counter.
|
||||
class Counter {
|
||||
private:
|
||||
int counter_;
|
||||
|
||||
public:
|
||||
// Creates a counter that starts at 0.
|
||||
Counter() : counter_(0) {}
|
||||
|
||||
// Returns the current counter value, and increments it.
|
||||
int Increment();
|
||||
|
||||
// Prints the current counter value to STDOUT.
|
||||
void Print() const;
|
||||
};
|
||||
|
||||
#endif // GTEST_SAMPLES_SAMPLE4_H_
|
||||
|
||||
+250
-250
@@ -1,250 +1,250 @@
|
||||
#!/usr/bin/env python
|
||||
#
|
||||
# Copyright 2009, 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.
|
||||
|
||||
"""fuse_gtest_files.py v0.2.0
|
||||
Fuses Google Test source code into a .h file and a .cc file.
|
||||
|
||||
SYNOPSIS
|
||||
fuse_gtest_files.py [GTEST_ROOT_DIR] OUTPUT_DIR
|
||||
|
||||
Scans GTEST_ROOT_DIR for Google Test source code, and generates
|
||||
two files: OUTPUT_DIR/gtest/gtest.h and OUTPUT_DIR/gtest/gtest-all.cc.
|
||||
Then you can build your tests by adding OUTPUT_DIR to the include
|
||||
search path and linking with OUTPUT_DIR/gtest/gtest-all.cc. These
|
||||
two files contain everything you need to use Google Test. Hence
|
||||
you can "install" Google Test by copying them to wherever you want.
|
||||
|
||||
GTEST_ROOT_DIR can be omitted and defaults to the parent
|
||||
directory of the directory holding this script.
|
||||
|
||||
EXAMPLES
|
||||
./fuse_gtest_files.py fused_gtest
|
||||
./fuse_gtest_files.py path/to/unpacked/gtest fused_gtest
|
||||
|
||||
This tool is experimental. In particular, it assumes that there is no
|
||||
conditional inclusion of Google Test headers. Please report any
|
||||
problems to googletestframework@googlegroups.com. You can read
|
||||
http://code.google.com/p/googletest/wiki/GoogleTestAdvancedGuide for
|
||||
more information.
|
||||
"""
|
||||
|
||||
__author__ = 'wan@google.com (Zhanyong Wan)'
|
||||
|
||||
import os
|
||||
import re
|
||||
import sets
|
||||
import sys
|
||||
|
||||
# We assume that this file is in the scripts/ directory in the Google
|
||||
# Test root directory.
|
||||
DEFAULT_GTEST_ROOT_DIR = os.path.join(os.path.dirname(__file__), '..')
|
||||
|
||||
# Regex for matching '#include <gtest/...>'.
|
||||
INCLUDE_GTEST_FILE_REGEX = re.compile(r'^\s*#\s*include\s*<(gtest/.+)>')
|
||||
|
||||
# Regex for matching '#include "src/..."'.
|
||||
INCLUDE_SRC_FILE_REGEX = re.compile(r'^\s*#\s*include\s*"(src/.+)"')
|
||||
|
||||
# Where to find the source seed files.
|
||||
GTEST_H_SEED = 'include/gtest/gtest.h'
|
||||
GTEST_SPI_H_SEED = 'include/gtest/gtest-spi.h'
|
||||
GTEST_ALL_CC_SEED = 'src/gtest-all.cc'
|
||||
|
||||
# Where to put the generated files.
|
||||
GTEST_H_OUTPUT = 'gtest/gtest.h'
|
||||
GTEST_ALL_CC_OUTPUT = 'gtest/gtest-all.cc'
|
||||
|
||||
|
||||
def VerifyFileExists(directory, relative_path):
|
||||
"""Verifies that the given file exists; aborts on failure.
|
||||
|
||||
relative_path is the file path relative to the given directory.
|
||||
"""
|
||||
|
||||
if not os.path.isfile(os.path.join(directory, relative_path)):
|
||||
print 'ERROR: Cannot find %s in directory %s.' % (relative_path,
|
||||
directory)
|
||||
print ('Please either specify a valid project root directory '
|
||||
'or omit it on the command line.')
|
||||
sys.exit(1)
|
||||
|
||||
|
||||
def ValidateGTestRootDir(gtest_root):
|
||||
"""Makes sure gtest_root points to a valid gtest root directory.
|
||||
|
||||
The function aborts the program on failure.
|
||||
"""
|
||||
|
||||
VerifyFileExists(gtest_root, GTEST_H_SEED)
|
||||
VerifyFileExists(gtest_root, GTEST_ALL_CC_SEED)
|
||||
|
||||
|
||||
def VerifyOutputFile(output_dir, relative_path):
|
||||
"""Verifies that the given output file path is valid.
|
||||
|
||||
relative_path is relative to the output_dir directory.
|
||||
"""
|
||||
|
||||
# Makes sure the output file either doesn't exist or can be overwritten.
|
||||
output_file = os.path.join(output_dir, relative_path)
|
||||
if os.path.exists(output_file):
|
||||
# TODO(wan@google.com): The following user-interaction doesn't
|
||||
# work with automated processes. We should provide a way for the
|
||||
# Makefile to force overwriting the files.
|
||||
print ('%s already exists in directory %s - overwrite it? (y/N) ' %
|
||||
(relative_path, output_dir))
|
||||
answer = sys.stdin.readline().strip()
|
||||
if answer not in ['y', 'Y']:
|
||||
print 'ABORTED.'
|
||||
sys.exit(1)
|
||||
|
||||
# Makes sure the directory holding the output file exists; creates
|
||||
# it and all its ancestors if necessary.
|
||||
parent_directory = os.path.dirname(output_file)
|
||||
if not os.path.isdir(parent_directory):
|
||||
os.makedirs(parent_directory)
|
||||
|
||||
|
||||
def ValidateOutputDir(output_dir):
|
||||
"""Makes sure output_dir points to a valid output directory.
|
||||
|
||||
The function aborts the program on failure.
|
||||
"""
|
||||
|
||||
VerifyOutputFile(output_dir, GTEST_H_OUTPUT)
|
||||
VerifyOutputFile(output_dir, GTEST_ALL_CC_OUTPUT)
|
||||
|
||||
|
||||
def FuseGTestH(gtest_root, output_dir):
|
||||
"""Scans folder gtest_root to generate gtest/gtest.h in output_dir."""
|
||||
|
||||
output_file = file(os.path.join(output_dir, GTEST_H_OUTPUT), 'w')
|
||||
processed_files = sets.Set() # Holds all gtest headers we've processed.
|
||||
|
||||
def ProcessFile(gtest_header_path):
|
||||
"""Processes the given gtest header file."""
|
||||
|
||||
# We don't process the same header twice.
|
||||
if gtest_header_path in processed_files:
|
||||
return
|
||||
|
||||
processed_files.add(gtest_header_path)
|
||||
|
||||
# Reads each line in the given gtest header.
|
||||
for line in file(os.path.join(gtest_root, gtest_header_path), 'r'):
|
||||
m = INCLUDE_GTEST_FILE_REGEX.match(line)
|
||||
if m:
|
||||
# It's '#include <gtest/...>' - let's process it recursively.
|
||||
ProcessFile('include/' + m.group(1))
|
||||
else:
|
||||
# Otherwise we copy the line unchanged to the output file.
|
||||
output_file.write(line)
|
||||
|
||||
ProcessFile(GTEST_H_SEED)
|
||||
output_file.close()
|
||||
|
||||
|
||||
def FuseGTestAllCcToFile(gtest_root, output_file):
|
||||
"""Scans folder gtest_root to generate gtest/gtest-all.cc in output_file."""
|
||||
|
||||
processed_files = sets.Set()
|
||||
|
||||
def ProcessFile(gtest_source_file):
|
||||
"""Processes the given gtest source file."""
|
||||
|
||||
# We don't process the same #included file twice.
|
||||
if gtest_source_file in processed_files:
|
||||
return
|
||||
|
||||
processed_files.add(gtest_source_file)
|
||||
|
||||
# Reads each line in the given gtest source file.
|
||||
for line in file(os.path.join(gtest_root, gtest_source_file), 'r'):
|
||||
m = INCLUDE_GTEST_FILE_REGEX.match(line)
|
||||
if m:
|
||||
if 'include/' + m.group(1) == GTEST_SPI_H_SEED:
|
||||
# It's '#include <gtest/gtest-spi.h>'. This file is not
|
||||
# #included by <gtest/gtest.h>, so we need to process it.
|
||||
ProcessFile(GTEST_SPI_H_SEED)
|
||||
else:
|
||||
# It's '#include <gtest/foo.h>' where foo is not gtest-spi.
|
||||
# We treat it as '#include <gtest/gtest.h>', as all other
|
||||
# gtest headers are being fused into gtest.h and cannot be
|
||||
# #included directly.
|
||||
|
||||
# There is no need to #include <gtest/gtest.h> more than once.
|
||||
if not GTEST_H_SEED in processed_files:
|
||||
processed_files.add(GTEST_H_SEED)
|
||||
output_file.write('#include <%s>\n' % (GTEST_H_OUTPUT,))
|
||||
else:
|
||||
m = INCLUDE_SRC_FILE_REGEX.match(line)
|
||||
if m:
|
||||
# It's '#include "src/foo"' - let's process it recursively.
|
||||
ProcessFile(m.group(1))
|
||||
else:
|
||||
output_file.write(line)
|
||||
|
||||
ProcessFile(GTEST_ALL_CC_SEED)
|
||||
|
||||
|
||||
def FuseGTestAllCc(gtest_root, output_dir):
|
||||
"""Scans folder gtest_root to generate gtest/gtest-all.cc in output_dir."""
|
||||
|
||||
output_file = file(os.path.join(output_dir, GTEST_ALL_CC_OUTPUT), 'w')
|
||||
FuseGTestAllCcToFile(gtest_root, output_file)
|
||||
output_file.close()
|
||||
|
||||
|
||||
def FuseGTest(gtest_root, output_dir):
|
||||
"""Fuses gtest.h and gtest-all.cc."""
|
||||
|
||||
ValidateGTestRootDir(gtest_root)
|
||||
ValidateOutputDir(output_dir)
|
||||
|
||||
FuseGTestH(gtest_root, output_dir)
|
||||
FuseGTestAllCc(gtest_root, output_dir)
|
||||
|
||||
|
||||
def main():
|
||||
argc = len(sys.argv)
|
||||
if argc == 2:
|
||||
# fuse_gtest_files.py OUTPUT_DIR
|
||||
FuseGTest(DEFAULT_GTEST_ROOT_DIR, sys.argv[1])
|
||||
elif argc == 3:
|
||||
# fuse_gtest_files.py GTEST_ROOT_DIR OUTPUT_DIR
|
||||
FuseGTest(sys.argv[1], sys.argv[2])
|
||||
else:
|
||||
print __doc__
|
||||
sys.exit(1)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
#!/usr/bin/env python
|
||||
#
|
||||
# Copyright 2009, 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.
|
||||
|
||||
"""fuse_gtest_files.py v0.2.0
|
||||
Fuses Google Test source code into a .h file and a .cc file.
|
||||
|
||||
SYNOPSIS
|
||||
fuse_gtest_files.py [GTEST_ROOT_DIR] OUTPUT_DIR
|
||||
|
||||
Scans GTEST_ROOT_DIR for Google Test source code, and generates
|
||||
two files: OUTPUT_DIR/gtest/gtest.h and OUTPUT_DIR/gtest/gtest-all.cc.
|
||||
Then you can build your tests by adding OUTPUT_DIR to the include
|
||||
search path and linking with OUTPUT_DIR/gtest/gtest-all.cc. These
|
||||
two files contain everything you need to use Google Test. Hence
|
||||
you can "install" Google Test by copying them to wherever you want.
|
||||
|
||||
GTEST_ROOT_DIR can be omitted and defaults to the parent
|
||||
directory of the directory holding this script.
|
||||
|
||||
EXAMPLES
|
||||
./fuse_gtest_files.py fused_gtest
|
||||
./fuse_gtest_files.py path/to/unpacked/gtest fused_gtest
|
||||
|
||||
This tool is experimental. In particular, it assumes that there is no
|
||||
conditional inclusion of Google Test headers. Please report any
|
||||
problems to googletestframework@googlegroups.com. You can read
|
||||
http://code.google.com/p/googletest/wiki/GoogleTestAdvancedGuide for
|
||||
more information.
|
||||
"""
|
||||
|
||||
__author__ = 'wan@google.com (Zhanyong Wan)'
|
||||
|
||||
import os
|
||||
import re
|
||||
import sets
|
||||
import sys
|
||||
|
||||
# We assume that this file is in the scripts/ directory in the Google
|
||||
# Test root directory.
|
||||
DEFAULT_GTEST_ROOT_DIR = os.path.join(os.path.dirname(__file__), '..')
|
||||
|
||||
# Regex for matching '#include <gtest/...>'.
|
||||
INCLUDE_GTEST_FILE_REGEX = re.compile(r'^\s*#\s*include\s*<(gtest/.+)>')
|
||||
|
||||
# Regex for matching '#include "src/..."'.
|
||||
INCLUDE_SRC_FILE_REGEX = re.compile(r'^\s*#\s*include\s*"(src/.+)"')
|
||||
|
||||
# Where to find the source seed files.
|
||||
GTEST_H_SEED = 'include/gtest/gtest.h'
|
||||
GTEST_SPI_H_SEED = 'include/gtest/gtest-spi.h'
|
||||
GTEST_ALL_CC_SEED = 'src/gtest-all.cc'
|
||||
|
||||
# Where to put the generated files.
|
||||
GTEST_H_OUTPUT = 'gtest/gtest.h'
|
||||
GTEST_ALL_CC_OUTPUT = 'gtest/gtest-all.cc'
|
||||
|
||||
|
||||
def VerifyFileExists(directory, relative_path):
|
||||
"""Verifies that the given file exists; aborts on failure.
|
||||
|
||||
relative_path is the file path relative to the given directory.
|
||||
"""
|
||||
|
||||
if not os.path.isfile(os.path.join(directory, relative_path)):
|
||||
print 'ERROR: Cannot find %s in directory %s.' % (relative_path,
|
||||
directory)
|
||||
print ('Please either specify a valid project root directory '
|
||||
'or omit it on the command line.')
|
||||
sys.exit(1)
|
||||
|
||||
|
||||
def ValidateGTestRootDir(gtest_root):
|
||||
"""Makes sure gtest_root points to a valid gtest root directory.
|
||||
|
||||
The function aborts the program on failure.
|
||||
"""
|
||||
|
||||
VerifyFileExists(gtest_root, GTEST_H_SEED)
|
||||
VerifyFileExists(gtest_root, GTEST_ALL_CC_SEED)
|
||||
|
||||
|
||||
def VerifyOutputFile(output_dir, relative_path):
|
||||
"""Verifies that the given output file path is valid.
|
||||
|
||||
relative_path is relative to the output_dir directory.
|
||||
"""
|
||||
|
||||
# Makes sure the output file either doesn't exist or can be overwritten.
|
||||
output_file = os.path.join(output_dir, relative_path)
|
||||
if os.path.exists(output_file):
|
||||
# TODO(wan@google.com): The following user-interaction doesn't
|
||||
# work with automated processes. We should provide a way for the
|
||||
# Makefile to force overwriting the files.
|
||||
print ('%s already exists in directory %s - overwrite it? (y/N) ' %
|
||||
(relative_path, output_dir))
|
||||
answer = sys.stdin.readline().strip()
|
||||
if answer not in ['y', 'Y']:
|
||||
print 'ABORTED.'
|
||||
sys.exit(1)
|
||||
|
||||
# Makes sure the directory holding the output file exists; creates
|
||||
# it and all its ancestors if necessary.
|
||||
parent_directory = os.path.dirname(output_file)
|
||||
if not os.path.isdir(parent_directory):
|
||||
os.makedirs(parent_directory)
|
||||
|
||||
|
||||
def ValidateOutputDir(output_dir):
|
||||
"""Makes sure output_dir points to a valid output directory.
|
||||
|
||||
The function aborts the program on failure.
|
||||
"""
|
||||
|
||||
VerifyOutputFile(output_dir, GTEST_H_OUTPUT)
|
||||
VerifyOutputFile(output_dir, GTEST_ALL_CC_OUTPUT)
|
||||
|
||||
|
||||
def FuseGTestH(gtest_root, output_dir):
|
||||
"""Scans folder gtest_root to generate gtest/gtest.h in output_dir."""
|
||||
|
||||
output_file = file(os.path.join(output_dir, GTEST_H_OUTPUT), 'w')
|
||||
processed_files = sets.Set() # Holds all gtest headers we've processed.
|
||||
|
||||
def ProcessFile(gtest_header_path):
|
||||
"""Processes the given gtest header file."""
|
||||
|
||||
# We don't process the same header twice.
|
||||
if gtest_header_path in processed_files:
|
||||
return
|
||||
|
||||
processed_files.add(gtest_header_path)
|
||||
|
||||
# Reads each line in the given gtest header.
|
||||
for line in file(os.path.join(gtest_root, gtest_header_path), 'r'):
|
||||
m = INCLUDE_GTEST_FILE_REGEX.match(line)
|
||||
if m:
|
||||
# It's '#include <gtest/...>' - let's process it recursively.
|
||||
ProcessFile('include/' + m.group(1))
|
||||
else:
|
||||
# Otherwise we copy the line unchanged to the output file.
|
||||
output_file.write(line)
|
||||
|
||||
ProcessFile(GTEST_H_SEED)
|
||||
output_file.close()
|
||||
|
||||
|
||||
def FuseGTestAllCcToFile(gtest_root, output_file):
|
||||
"""Scans folder gtest_root to generate gtest/gtest-all.cc in output_file."""
|
||||
|
||||
processed_files = sets.Set()
|
||||
|
||||
def ProcessFile(gtest_source_file):
|
||||
"""Processes the given gtest source file."""
|
||||
|
||||
# We don't process the same #included file twice.
|
||||
if gtest_source_file in processed_files:
|
||||
return
|
||||
|
||||
processed_files.add(gtest_source_file)
|
||||
|
||||
# Reads each line in the given gtest source file.
|
||||
for line in file(os.path.join(gtest_root, gtest_source_file), 'r'):
|
||||
m = INCLUDE_GTEST_FILE_REGEX.match(line)
|
||||
if m:
|
||||
if 'include/' + m.group(1) == GTEST_SPI_H_SEED:
|
||||
# It's '#include <gtest/gtest-spi.h>'. This file is not
|
||||
# #included by <gtest/gtest.h>, so we need to process it.
|
||||
ProcessFile(GTEST_SPI_H_SEED)
|
||||
else:
|
||||
# It's '#include <gtest/foo.h>' where foo is not gtest-spi.
|
||||
# We treat it as '#include <gtest/gtest.h>', as all other
|
||||
# gtest headers are being fused into gtest.h and cannot be
|
||||
# #included directly.
|
||||
|
||||
# There is no need to #include <gtest/gtest.h> more than once.
|
||||
if not GTEST_H_SEED in processed_files:
|
||||
processed_files.add(GTEST_H_SEED)
|
||||
output_file.write('#include <%s>\n' % (GTEST_H_OUTPUT,))
|
||||
else:
|
||||
m = INCLUDE_SRC_FILE_REGEX.match(line)
|
||||
if m:
|
||||
# It's '#include "src/foo"' - let's process it recursively.
|
||||
ProcessFile(m.group(1))
|
||||
else:
|
||||
output_file.write(line)
|
||||
|
||||
ProcessFile(GTEST_ALL_CC_SEED)
|
||||
|
||||
|
||||
def FuseGTestAllCc(gtest_root, output_dir):
|
||||
"""Scans folder gtest_root to generate gtest/gtest-all.cc in output_dir."""
|
||||
|
||||
output_file = file(os.path.join(output_dir, GTEST_ALL_CC_OUTPUT), 'w')
|
||||
FuseGTestAllCcToFile(gtest_root, output_file)
|
||||
output_file.close()
|
||||
|
||||
|
||||
def FuseGTest(gtest_root, output_dir):
|
||||
"""Fuses gtest.h and gtest-all.cc."""
|
||||
|
||||
ValidateGTestRootDir(gtest_root)
|
||||
ValidateOutputDir(output_dir)
|
||||
|
||||
FuseGTestH(gtest_root, output_dir)
|
||||
FuseGTestAllCc(gtest_root, output_dir)
|
||||
|
||||
|
||||
def main():
|
||||
argc = len(sys.argv)
|
||||
if argc == 2:
|
||||
# fuse_gtest_files.py OUTPUT_DIR
|
||||
FuseGTest(DEFAULT_GTEST_ROOT_DIR, sys.argv[1])
|
||||
elif argc == 3:
|
||||
# fuse_gtest_files.py GTEST_ROOT_DIR OUTPUT_DIR
|
||||
FuseGTest(sys.argv[1], sys.argv[2])
|
||||
else:
|
||||
print __doc__
|
||||
sys.exit(1)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
|
||||
+733
-733
File diff suppressed because it is too large
Load Diff
+1247
-1247
File diff suppressed because it is too large
Load Diff
@@ -1,55 +1,55 @@
|
||||
// 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.
|
||||
//
|
||||
// Authors: vladl@google.com (Vlad Losev)
|
||||
//
|
||||
// The Google C++ Testing Framework (Google Test)
|
||||
//
|
||||
// This header file provides classes and functions used internally
|
||||
// for testing Google Test itself.
|
||||
|
||||
#ifndef GTEST_TEST_GTEST_PARAM_TEST_TEST_H_
|
||||
#define GTEST_TEST_GTEST_PARAM_TEST_TEST_H_
|
||||
|
||||
#include <gtest/gtest.h>
|
||||
|
||||
#if GTEST_HAS_PARAM_TEST
|
||||
|
||||
// Test fixture for testing definition and instantiation of a test
|
||||
// in separate translation units.
|
||||
class ExternalInstantiationTest : public ::testing::TestWithParam<int> {};
|
||||
|
||||
// Test fixture for testing instantiation of a test in multiple
|
||||
// translation units.
|
||||
class InstantiationInMultipleTranslaionUnitsTest
|
||||
: public ::testing::TestWithParam<int> {};
|
||||
|
||||
#endif // GTEST_HAS_PARAM_TEST
|
||||
|
||||
#endif // GTEST_TEST_GTEST_PARAM_TEST_TEST_H_
|
||||
// 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.
|
||||
//
|
||||
// Authors: vladl@google.com (Vlad Losev)
|
||||
//
|
||||
// The Google C++ Testing Framework (Google Test)
|
||||
//
|
||||
// This header file provides classes and functions used internally
|
||||
// for testing Google Test itself.
|
||||
|
||||
#ifndef GTEST_TEST_GTEST_PARAM_TEST_TEST_H_
|
||||
#define GTEST_TEST_GTEST_PARAM_TEST_TEST_H_
|
||||
|
||||
#include <gtest/gtest.h>
|
||||
|
||||
#if GTEST_HAS_PARAM_TEST
|
||||
|
||||
// Test fixture for testing definition and instantiation of a test
|
||||
// in separate translation units.
|
||||
class ExternalInstantiationTest : public ::testing::TestWithParam<int> {};
|
||||
|
||||
// Test fixture for testing instantiation of a test in multiple
|
||||
// translation units.
|
||||
class InstantiationInMultipleTranslaionUnitsTest
|
||||
: public ::testing::TestWithParam<int> {};
|
||||
|
||||
#endif // GTEST_HAS_PARAM_TEST
|
||||
|
||||
#endif // GTEST_TEST_GTEST_PARAM_TEST_TEST_H_
|
||||
|
||||
@@ -1,66 +1,66 @@
|
||||
// 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.
|
||||
//
|
||||
// Author: wan@google.com (Zhanyong Wan)
|
||||
|
||||
#ifndef GTEST_TEST_GTEST_TYPED_TEST_TEST_H_
|
||||
#define GTEST_TEST_GTEST_TYPED_TEST_TEST_H_
|
||||
|
||||
#include <gtest/gtest.h>
|
||||
|
||||
#if GTEST_HAS_TYPED_TEST_P
|
||||
|
||||
using testing::Test;
|
||||
|
||||
// For testing that the same type-parameterized test case can be
|
||||
// instantiated in different translation units linked together.
|
||||
// ContainerTest will be instantiated in both gtest-typed-test_test.cc
|
||||
// and gtest-typed-test2_test.cc.
|
||||
|
||||
template <typename T>
|
||||
class ContainerTest : public Test {
|
||||
};
|
||||
|
||||
TYPED_TEST_CASE_P(ContainerTest);
|
||||
|
||||
TYPED_TEST_P(ContainerTest, CanBeDefaultConstructed) {
|
||||
TypeParam container;
|
||||
}
|
||||
|
||||
TYPED_TEST_P(ContainerTest, InitialSizeIsZero) {
|
||||
TypeParam container;
|
||||
EXPECT_EQ(0U, container.size());
|
||||
}
|
||||
|
||||
REGISTER_TYPED_TEST_CASE_P(ContainerTest,
|
||||
CanBeDefaultConstructed, InitialSizeIsZero);
|
||||
|
||||
#endif // GTEST_HAS_TYPED_TEST_P
|
||||
|
||||
#endif // GTEST_TEST_GTEST_TYPED_TEST_TEST_H_
|
||||
// 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.
|
||||
//
|
||||
// Author: wan@google.com (Zhanyong Wan)
|
||||
|
||||
#ifndef GTEST_TEST_GTEST_TYPED_TEST_TEST_H_
|
||||
#define GTEST_TEST_GTEST_TYPED_TEST_TEST_H_
|
||||
|
||||
#include <gtest/gtest.h>
|
||||
|
||||
#if GTEST_HAS_TYPED_TEST_P
|
||||
|
||||
using testing::Test;
|
||||
|
||||
// For testing that the same type-parameterized test case can be
|
||||
// instantiated in different translation units linked together.
|
||||
// ContainerTest will be instantiated in both gtest-typed-test_test.cc
|
||||
// and gtest-typed-test2_test.cc.
|
||||
|
||||
template <typename T>
|
||||
class ContainerTest : public Test {
|
||||
};
|
||||
|
||||
TYPED_TEST_CASE_P(ContainerTest);
|
||||
|
||||
TYPED_TEST_P(ContainerTest, CanBeDefaultConstructed) {
|
||||
TypeParam container;
|
||||
}
|
||||
|
||||
TYPED_TEST_P(ContainerTest, InitialSizeIsZero) {
|
||||
TypeParam container;
|
||||
EXPECT_EQ(0U, container.size());
|
||||
}
|
||||
|
||||
REGISTER_TYPED_TEST_CASE_P(ContainerTest,
|
||||
CanBeDefaultConstructed, InitialSizeIsZero);
|
||||
|
||||
#endif // GTEST_HAS_TYPED_TEST_P
|
||||
|
||||
#endif // GTEST_TEST_GTEST_TYPED_TEST_TEST_H_
|
||||
|
||||
+215
-215
@@ -1,215 +1,215 @@
|
||||
#!/usr/bin/env python
|
||||
#
|
||||
# Copyright 2006, 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.
|
||||
|
||||
"""Unit test for Google Test's break-on-failure mode.
|
||||
|
||||
A user can ask Google Test to seg-fault when an assertion fails, using
|
||||
either the GTEST_BREAK_ON_FAILURE environment variable or the
|
||||
--gtest_break_on_failure flag. This script tests such functionality
|
||||
by invoking gtest_break_on_failure_unittest_ (a program written with
|
||||
Google Test) with different environments and command line flags.
|
||||
"""
|
||||
|
||||
__author__ = 'wan@google.com (Zhanyong Wan)'
|
||||
|
||||
import gtest_test_utils
|
||||
import os
|
||||
import sys
|
||||
|
||||
|
||||
# Constants.
|
||||
|
||||
IS_WINDOWS = os.name == 'nt'
|
||||
|
||||
# The environment variable for enabling/disabling the break-on-failure mode.
|
||||
BREAK_ON_FAILURE_ENV_VAR = 'GTEST_BREAK_ON_FAILURE'
|
||||
|
||||
# The command line flag for enabling/disabling the break-on-failure mode.
|
||||
BREAK_ON_FAILURE_FLAG = 'gtest_break_on_failure'
|
||||
|
||||
# The environment variable for enabling/disabling the throw-on-failure mode.
|
||||
THROW_ON_FAILURE_ENV_VAR = 'GTEST_THROW_ON_FAILURE'
|
||||
|
||||
# The environment variable for enabling/disabling the catch-exceptions mode.
|
||||
CATCH_EXCEPTIONS_ENV_VAR = 'GTEST_CATCH_EXCEPTIONS'
|
||||
|
||||
# Path to the gtest_break_on_failure_unittest_ program.
|
||||
EXE_PATH = gtest_test_utils.GetTestExecutablePath(
|
||||
'gtest_break_on_failure_unittest_')
|
||||
|
||||
|
||||
# Utilities.
|
||||
|
||||
|
||||
def SetEnvVar(env_var, value):
|
||||
"""Sets an environment variable to a given value; unsets it when the
|
||||
given value is None.
|
||||
"""
|
||||
|
||||
if value is not None:
|
||||
os.environ[env_var] = value
|
||||
elif env_var in os.environ:
|
||||
del os.environ[env_var]
|
||||
|
||||
|
||||
def Run(command):
|
||||
"""Runs a command; returns 1 if it was killed by a signal, or 0 otherwise."""
|
||||
|
||||
p = gtest_test_utils.Subprocess(command)
|
||||
if p.terminated_by_signal:
|
||||
return 1
|
||||
else:
|
||||
return 0
|
||||
|
||||
|
||||
# The tests.
|
||||
|
||||
|
||||
class GTestBreakOnFailureUnitTest(gtest_test_utils.TestCase):
|
||||
"""Tests using the GTEST_BREAK_ON_FAILURE environment variable or
|
||||
the --gtest_break_on_failure flag to turn assertion failures into
|
||||
segmentation faults.
|
||||
"""
|
||||
|
||||
def RunAndVerify(self, env_var_value, flag_value, expect_seg_fault):
|
||||
"""Runs gtest_break_on_failure_unittest_ and verifies that it does
|
||||
(or does not) have a seg-fault.
|
||||
|
||||
Args:
|
||||
env_var_value: value of the GTEST_BREAK_ON_FAILURE environment
|
||||
variable; None if the variable should be unset.
|
||||
flag_value: value of the --gtest_break_on_failure flag;
|
||||
None if the flag should not be present.
|
||||
expect_seg_fault: 1 if the program is expected to generate a seg-fault;
|
||||
0 otherwise.
|
||||
"""
|
||||
|
||||
SetEnvVar(BREAK_ON_FAILURE_ENV_VAR, env_var_value)
|
||||
|
||||
if env_var_value is None:
|
||||
env_var_value_msg = ' is not set'
|
||||
else:
|
||||
env_var_value_msg = '=' + env_var_value
|
||||
|
||||
if flag_value is None:
|
||||
flag = ''
|
||||
elif flag_value == '0':
|
||||
flag = '--%s=0' % BREAK_ON_FAILURE_FLAG
|
||||
else:
|
||||
flag = '--%s' % BREAK_ON_FAILURE_FLAG
|
||||
|
||||
command = [EXE_PATH]
|
||||
if flag:
|
||||
command.append(flag)
|
||||
|
||||
if expect_seg_fault:
|
||||
should_or_not = 'should'
|
||||
else:
|
||||
should_or_not = 'should not'
|
||||
|
||||
has_seg_fault = Run(command)
|
||||
|
||||
SetEnvVar(BREAK_ON_FAILURE_ENV_VAR, None)
|
||||
|
||||
msg = ('when %s%s, an assertion failure in "%s" %s cause a seg-fault.' %
|
||||
(BREAK_ON_FAILURE_ENV_VAR, env_var_value_msg, ' '.join(command),
|
||||
should_or_not))
|
||||
self.assert_(has_seg_fault == expect_seg_fault, msg)
|
||||
|
||||
def testDefaultBehavior(self):
|
||||
"""Tests the behavior of the default mode."""
|
||||
|
||||
self.RunAndVerify(env_var_value=None,
|
||||
flag_value=None,
|
||||
expect_seg_fault=0)
|
||||
|
||||
def testEnvVar(self):
|
||||
"""Tests using the GTEST_BREAK_ON_FAILURE environment variable."""
|
||||
|
||||
self.RunAndVerify(env_var_value='0',
|
||||
flag_value=None,
|
||||
expect_seg_fault=0)
|
||||
self.RunAndVerify(env_var_value='1',
|
||||
flag_value=None,
|
||||
expect_seg_fault=1)
|
||||
|
||||
def testFlag(self):
|
||||
"""Tests using the --gtest_break_on_failure flag."""
|
||||
|
||||
self.RunAndVerify(env_var_value=None,
|
||||
flag_value='0',
|
||||
expect_seg_fault=0)
|
||||
self.RunAndVerify(env_var_value=None,
|
||||
flag_value='1',
|
||||
expect_seg_fault=1)
|
||||
|
||||
def testFlagOverridesEnvVar(self):
|
||||
"""Tests that the flag overrides the environment variable."""
|
||||
|
||||
self.RunAndVerify(env_var_value='0',
|
||||
flag_value='0',
|
||||
expect_seg_fault=0)
|
||||
self.RunAndVerify(env_var_value='0',
|
||||
flag_value='1',
|
||||
expect_seg_fault=1)
|
||||
self.RunAndVerify(env_var_value='1',
|
||||
flag_value='0',
|
||||
expect_seg_fault=0)
|
||||
self.RunAndVerify(env_var_value='1',
|
||||
flag_value='1',
|
||||
expect_seg_fault=1)
|
||||
|
||||
def testBreakOnFailureOverridesThrowOnFailure(self):
|
||||
"""Tests that gtest_break_on_failure overrides gtest_throw_on_failure."""
|
||||
|
||||
SetEnvVar(THROW_ON_FAILURE_ENV_VAR, '1')
|
||||
try:
|
||||
self.RunAndVerify(env_var_value=None,
|
||||
flag_value='1',
|
||||
expect_seg_fault=1)
|
||||
finally:
|
||||
SetEnvVar(THROW_ON_FAILURE_ENV_VAR, None)
|
||||
|
||||
if IS_WINDOWS:
|
||||
def testCatchExceptionsDoesNotInterfere(self):
|
||||
"""Tests that gtest_catch_exceptions doesn't interfere."""
|
||||
|
||||
SetEnvVar(CATCH_EXCEPTIONS_ENV_VAR, '1')
|
||||
try:
|
||||
self.RunAndVerify(env_var_value='1',
|
||||
flag_value='1',
|
||||
expect_seg_fault=1)
|
||||
finally:
|
||||
SetEnvVar(CATCH_EXCEPTIONS_ENV_VAR, None)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
gtest_test_utils.Main()
|
||||
#!/usr/bin/env python
|
||||
#
|
||||
# Copyright 2006, 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.
|
||||
|
||||
"""Unit test for Google Test's break-on-failure mode.
|
||||
|
||||
A user can ask Google Test to seg-fault when an assertion fails, using
|
||||
either the GTEST_BREAK_ON_FAILURE environment variable or the
|
||||
--gtest_break_on_failure flag. This script tests such functionality
|
||||
by invoking gtest_break_on_failure_unittest_ (a program written with
|
||||
Google Test) with different environments and command line flags.
|
||||
"""
|
||||
|
||||
__author__ = 'wan@google.com (Zhanyong Wan)'
|
||||
|
||||
import gtest_test_utils
|
||||
import os
|
||||
import sys
|
||||
|
||||
|
||||
# Constants.
|
||||
|
||||
IS_WINDOWS = os.name == 'nt'
|
||||
|
||||
# The environment variable for enabling/disabling the break-on-failure mode.
|
||||
BREAK_ON_FAILURE_ENV_VAR = 'GTEST_BREAK_ON_FAILURE'
|
||||
|
||||
# The command line flag for enabling/disabling the break-on-failure mode.
|
||||
BREAK_ON_FAILURE_FLAG = 'gtest_break_on_failure'
|
||||
|
||||
# The environment variable for enabling/disabling the throw-on-failure mode.
|
||||
THROW_ON_FAILURE_ENV_VAR = 'GTEST_THROW_ON_FAILURE'
|
||||
|
||||
# The environment variable for enabling/disabling the catch-exceptions mode.
|
||||
CATCH_EXCEPTIONS_ENV_VAR = 'GTEST_CATCH_EXCEPTIONS'
|
||||
|
||||
# Path to the gtest_break_on_failure_unittest_ program.
|
||||
EXE_PATH = gtest_test_utils.GetTestExecutablePath(
|
||||
'gtest_break_on_failure_unittest_')
|
||||
|
||||
|
||||
# Utilities.
|
||||
|
||||
|
||||
def SetEnvVar(env_var, value):
|
||||
"""Sets an environment variable to a given value; unsets it when the
|
||||
given value is None.
|
||||
"""
|
||||
|
||||
if value is not None:
|
||||
os.environ[env_var] = value
|
||||
elif env_var in os.environ:
|
||||
del os.environ[env_var]
|
||||
|
||||
|
||||
def Run(command):
|
||||
"""Runs a command; returns 1 if it was killed by a signal, or 0 otherwise."""
|
||||
|
||||
p = gtest_test_utils.Subprocess(command)
|
||||
if p.terminated_by_signal:
|
||||
return 1
|
||||
else:
|
||||
return 0
|
||||
|
||||
|
||||
# The tests.
|
||||
|
||||
|
||||
class GTestBreakOnFailureUnitTest(gtest_test_utils.TestCase):
|
||||
"""Tests using the GTEST_BREAK_ON_FAILURE environment variable or
|
||||
the --gtest_break_on_failure flag to turn assertion failures into
|
||||
segmentation faults.
|
||||
"""
|
||||
|
||||
def RunAndVerify(self, env_var_value, flag_value, expect_seg_fault):
|
||||
"""Runs gtest_break_on_failure_unittest_ and verifies that it does
|
||||
(or does not) have a seg-fault.
|
||||
|
||||
Args:
|
||||
env_var_value: value of the GTEST_BREAK_ON_FAILURE environment
|
||||
variable; None if the variable should be unset.
|
||||
flag_value: value of the --gtest_break_on_failure flag;
|
||||
None if the flag should not be present.
|
||||
expect_seg_fault: 1 if the program is expected to generate a seg-fault;
|
||||
0 otherwise.
|
||||
"""
|
||||
|
||||
SetEnvVar(BREAK_ON_FAILURE_ENV_VAR, env_var_value)
|
||||
|
||||
if env_var_value is None:
|
||||
env_var_value_msg = ' is not set'
|
||||
else:
|
||||
env_var_value_msg = '=' + env_var_value
|
||||
|
||||
if flag_value is None:
|
||||
flag = ''
|
||||
elif flag_value == '0':
|
||||
flag = '--%s=0' % BREAK_ON_FAILURE_FLAG
|
||||
else:
|
||||
flag = '--%s' % BREAK_ON_FAILURE_FLAG
|
||||
|
||||
command = [EXE_PATH]
|
||||
if flag:
|
||||
command.append(flag)
|
||||
|
||||
if expect_seg_fault:
|
||||
should_or_not = 'should'
|
||||
else:
|
||||
should_or_not = 'should not'
|
||||
|
||||
has_seg_fault = Run(command)
|
||||
|
||||
SetEnvVar(BREAK_ON_FAILURE_ENV_VAR, None)
|
||||
|
||||
msg = ('when %s%s, an assertion failure in "%s" %s cause a seg-fault.' %
|
||||
(BREAK_ON_FAILURE_ENV_VAR, env_var_value_msg, ' '.join(command),
|
||||
should_or_not))
|
||||
self.assert_(has_seg_fault == expect_seg_fault, msg)
|
||||
|
||||
def testDefaultBehavior(self):
|
||||
"""Tests the behavior of the default mode."""
|
||||
|
||||
self.RunAndVerify(env_var_value=None,
|
||||
flag_value=None,
|
||||
expect_seg_fault=0)
|
||||
|
||||
def testEnvVar(self):
|
||||
"""Tests using the GTEST_BREAK_ON_FAILURE environment variable."""
|
||||
|
||||
self.RunAndVerify(env_var_value='0',
|
||||
flag_value=None,
|
||||
expect_seg_fault=0)
|
||||
self.RunAndVerify(env_var_value='1',
|
||||
flag_value=None,
|
||||
expect_seg_fault=1)
|
||||
|
||||
def testFlag(self):
|
||||
"""Tests using the --gtest_break_on_failure flag."""
|
||||
|
||||
self.RunAndVerify(env_var_value=None,
|
||||
flag_value='0',
|
||||
expect_seg_fault=0)
|
||||
self.RunAndVerify(env_var_value=None,
|
||||
flag_value='1',
|
||||
expect_seg_fault=1)
|
||||
|
||||
def testFlagOverridesEnvVar(self):
|
||||
"""Tests that the flag overrides the environment variable."""
|
||||
|
||||
self.RunAndVerify(env_var_value='0',
|
||||
flag_value='0',
|
||||
expect_seg_fault=0)
|
||||
self.RunAndVerify(env_var_value='0',
|
||||
flag_value='1',
|
||||
expect_seg_fault=1)
|
||||
self.RunAndVerify(env_var_value='1',
|
||||
flag_value='0',
|
||||
expect_seg_fault=0)
|
||||
self.RunAndVerify(env_var_value='1',
|
||||
flag_value='1',
|
||||
expect_seg_fault=1)
|
||||
|
||||
def testBreakOnFailureOverridesThrowOnFailure(self):
|
||||
"""Tests that gtest_break_on_failure overrides gtest_throw_on_failure."""
|
||||
|
||||
SetEnvVar(THROW_ON_FAILURE_ENV_VAR, '1')
|
||||
try:
|
||||
self.RunAndVerify(env_var_value=None,
|
||||
flag_value='1',
|
||||
expect_seg_fault=1)
|
||||
finally:
|
||||
SetEnvVar(THROW_ON_FAILURE_ENV_VAR, None)
|
||||
|
||||
if IS_WINDOWS:
|
||||
def testCatchExceptionsDoesNotInterfere(self):
|
||||
"""Tests that gtest_catch_exceptions doesn't interfere."""
|
||||
|
||||
SetEnvVar(CATCH_EXCEPTIONS_ENV_VAR, '1')
|
||||
try:
|
||||
self.RunAndVerify(env_var_value='1',
|
||||
flag_value='1',
|
||||
expect_seg_fault=1)
|
||||
finally:
|
||||
SetEnvVar(CATCH_EXCEPTIONS_ENV_VAR, None)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
gtest_test_utils.Main()
|
||||
|
||||
+130
-130
@@ -1,130 +1,130 @@
|
||||
#!/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.
|
||||
|
||||
"""Verifies that Google Test correctly determines whether to use colors."""
|
||||
|
||||
__author__ = 'wan@google.com (Zhanyong Wan)'
|
||||
|
||||
import os
|
||||
import gtest_test_utils
|
||||
|
||||
|
||||
IS_WINDOWS = os.name = 'nt'
|
||||
|
||||
COLOR_ENV_VAR = 'GTEST_COLOR'
|
||||
COLOR_FLAG = 'gtest_color'
|
||||
COMMAND = gtest_test_utils.GetTestExecutablePath('gtest_color_test_')
|
||||
|
||||
|
||||
def SetEnvVar(env_var, value):
|
||||
"""Sets the env variable to 'value'; unsets it when 'value' is None."""
|
||||
|
||||
if value is not None:
|
||||
os.environ[env_var] = value
|
||||
elif env_var in os.environ:
|
||||
del os.environ[env_var]
|
||||
|
||||
|
||||
def UsesColor(term, color_env_var, color_flag):
|
||||
"""Runs gtest_color_test_ and returns its exit code."""
|
||||
|
||||
SetEnvVar('TERM', term)
|
||||
SetEnvVar(COLOR_ENV_VAR, color_env_var)
|
||||
|
||||
if color_flag is None:
|
||||
args = []
|
||||
else:
|
||||
args = ['--%s=%s' % (COLOR_FLAG, color_flag)]
|
||||
p = gtest_test_utils.Subprocess([COMMAND] + args)
|
||||
return not p.exited or p.exit_code
|
||||
|
||||
|
||||
class GTestColorTest(gtest_test_utils.TestCase):
|
||||
def testNoEnvVarNoFlag(self):
|
||||
"""Tests the case when there's neither GTEST_COLOR nor --gtest_color."""
|
||||
|
||||
if not IS_WINDOWS:
|
||||
self.assert_(not UsesColor('dumb', None, None))
|
||||
self.assert_(not UsesColor('emacs', None, None))
|
||||
self.assert_(not UsesColor('xterm-mono', None, None))
|
||||
self.assert_(not UsesColor('unknown', None, None))
|
||||
self.assert_(not UsesColor(None, None, None))
|
||||
self.assert_(UsesColor('linux', None, None))
|
||||
self.assert_(UsesColor('cygwin', None, None))
|
||||
self.assert_(UsesColor('xterm', None, None))
|
||||
self.assert_(UsesColor('xterm-color', None, None))
|
||||
self.assert_(UsesColor('xterm-256color', None, None))
|
||||
|
||||
def testFlagOnly(self):
|
||||
"""Tests the case when there's --gtest_color but not GTEST_COLOR."""
|
||||
|
||||
self.assert_(not UsesColor('dumb', None, 'no'))
|
||||
self.assert_(not UsesColor('xterm-color', None, 'no'))
|
||||
if not IS_WINDOWS:
|
||||
self.assert_(not UsesColor('emacs', None, 'auto'))
|
||||
self.assert_(UsesColor('xterm', None, 'auto'))
|
||||
self.assert_(UsesColor('dumb', None, 'yes'))
|
||||
self.assert_(UsesColor('xterm', None, 'yes'))
|
||||
|
||||
def testEnvVarOnly(self):
|
||||
"""Tests the case when there's GTEST_COLOR but not --gtest_color."""
|
||||
|
||||
self.assert_(not UsesColor('dumb', 'no', None))
|
||||
self.assert_(not UsesColor('xterm-color', 'no', None))
|
||||
if not IS_WINDOWS:
|
||||
self.assert_(not UsesColor('dumb', 'auto', None))
|
||||
self.assert_(UsesColor('xterm-color', 'auto', None))
|
||||
self.assert_(UsesColor('dumb', 'yes', None))
|
||||
self.assert_(UsesColor('xterm-color', 'yes', None))
|
||||
|
||||
def testEnvVarAndFlag(self):
|
||||
"""Tests the case when there are both GTEST_COLOR and --gtest_color."""
|
||||
|
||||
self.assert_(not UsesColor('xterm-color', 'no', 'no'))
|
||||
self.assert_(UsesColor('dumb', 'no', 'yes'))
|
||||
self.assert_(UsesColor('xterm-color', 'no', 'auto'))
|
||||
|
||||
def testAliasesOfYesAndNo(self):
|
||||
"""Tests using aliases in specifying --gtest_color."""
|
||||
|
||||
self.assert_(UsesColor('dumb', None, 'true'))
|
||||
self.assert_(UsesColor('dumb', None, 'YES'))
|
||||
self.assert_(UsesColor('dumb', None, 'T'))
|
||||
self.assert_(UsesColor('dumb', None, '1'))
|
||||
|
||||
self.assert_(not UsesColor('xterm', None, 'f'))
|
||||
self.assert_(not UsesColor('xterm', None, 'false'))
|
||||
self.assert_(not UsesColor('xterm', None, '0'))
|
||||
self.assert_(not UsesColor('xterm', None, 'unknown'))
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
gtest_test_utils.Main()
|
||||
#!/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.
|
||||
|
||||
"""Verifies that Google Test correctly determines whether to use colors."""
|
||||
|
||||
__author__ = 'wan@google.com (Zhanyong Wan)'
|
||||
|
||||
import os
|
||||
import gtest_test_utils
|
||||
|
||||
|
||||
IS_WINDOWS = os.name = 'nt'
|
||||
|
||||
COLOR_ENV_VAR = 'GTEST_COLOR'
|
||||
COLOR_FLAG = 'gtest_color'
|
||||
COMMAND = gtest_test_utils.GetTestExecutablePath('gtest_color_test_')
|
||||
|
||||
|
||||
def SetEnvVar(env_var, value):
|
||||
"""Sets the env variable to 'value'; unsets it when 'value' is None."""
|
||||
|
||||
if value is not None:
|
||||
os.environ[env_var] = value
|
||||
elif env_var in os.environ:
|
||||
del os.environ[env_var]
|
||||
|
||||
|
||||
def UsesColor(term, color_env_var, color_flag):
|
||||
"""Runs gtest_color_test_ and returns its exit code."""
|
||||
|
||||
SetEnvVar('TERM', term)
|
||||
SetEnvVar(COLOR_ENV_VAR, color_env_var)
|
||||
|
||||
if color_flag is None:
|
||||
args = []
|
||||
else:
|
||||
args = ['--%s=%s' % (COLOR_FLAG, color_flag)]
|
||||
p = gtest_test_utils.Subprocess([COMMAND] + args)
|
||||
return not p.exited or p.exit_code
|
||||
|
||||
|
||||
class GTestColorTest(gtest_test_utils.TestCase):
|
||||
def testNoEnvVarNoFlag(self):
|
||||
"""Tests the case when there's neither GTEST_COLOR nor --gtest_color."""
|
||||
|
||||
if not IS_WINDOWS:
|
||||
self.assert_(not UsesColor('dumb', None, None))
|
||||
self.assert_(not UsesColor('emacs', None, None))
|
||||
self.assert_(not UsesColor('xterm-mono', None, None))
|
||||
self.assert_(not UsesColor('unknown', None, None))
|
||||
self.assert_(not UsesColor(None, None, None))
|
||||
self.assert_(UsesColor('linux', None, None))
|
||||
self.assert_(UsesColor('cygwin', None, None))
|
||||
self.assert_(UsesColor('xterm', None, None))
|
||||
self.assert_(UsesColor('xterm-color', None, None))
|
||||
self.assert_(UsesColor('xterm-256color', None, None))
|
||||
|
||||
def testFlagOnly(self):
|
||||
"""Tests the case when there's --gtest_color but not GTEST_COLOR."""
|
||||
|
||||
self.assert_(not UsesColor('dumb', None, 'no'))
|
||||
self.assert_(not UsesColor('xterm-color', None, 'no'))
|
||||
if not IS_WINDOWS:
|
||||
self.assert_(not UsesColor('emacs', None, 'auto'))
|
||||
self.assert_(UsesColor('xterm', None, 'auto'))
|
||||
self.assert_(UsesColor('dumb', None, 'yes'))
|
||||
self.assert_(UsesColor('xterm', None, 'yes'))
|
||||
|
||||
def testEnvVarOnly(self):
|
||||
"""Tests the case when there's GTEST_COLOR but not --gtest_color."""
|
||||
|
||||
self.assert_(not UsesColor('dumb', 'no', None))
|
||||
self.assert_(not UsesColor('xterm-color', 'no', None))
|
||||
if not IS_WINDOWS:
|
||||
self.assert_(not UsesColor('dumb', 'auto', None))
|
||||
self.assert_(UsesColor('xterm-color', 'auto', None))
|
||||
self.assert_(UsesColor('dumb', 'yes', None))
|
||||
self.assert_(UsesColor('xterm-color', 'yes', None))
|
||||
|
||||
def testEnvVarAndFlag(self):
|
||||
"""Tests the case when there are both GTEST_COLOR and --gtest_color."""
|
||||
|
||||
self.assert_(not UsesColor('xterm-color', 'no', 'no'))
|
||||
self.assert_(UsesColor('dumb', 'no', 'yes'))
|
||||
self.assert_(UsesColor('xterm-color', 'no', 'auto'))
|
||||
|
||||
def testAliasesOfYesAndNo(self):
|
||||
"""Tests using aliases in specifying --gtest_color."""
|
||||
|
||||
self.assert_(UsesColor('dumb', None, 'true'))
|
||||
self.assert_(UsesColor('dumb', None, 'YES'))
|
||||
self.assert_(UsesColor('dumb', None, 'T'))
|
||||
self.assert_(UsesColor('dumb', None, '1'))
|
||||
|
||||
self.assert_(not UsesColor('xterm', None, 'f'))
|
||||
self.assert_(not UsesColor('xterm', None, 'false'))
|
||||
self.assert_(not UsesColor('xterm', None, '0'))
|
||||
self.assert_(not UsesColor('xterm', None, 'unknown'))
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
gtest_test_utils.Main()
|
||||
|
||||
+103
-103
@@ -1,103 +1,103 @@
|
||||
#!/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.
|
||||
|
||||
"""Verifies that Google Test correctly parses environment variables."""
|
||||
|
||||
__author__ = 'wan@google.com (Zhanyong Wan)'
|
||||
|
||||
import os
|
||||
import gtest_test_utils
|
||||
|
||||
|
||||
IS_WINDOWS = os.name == 'nt'
|
||||
IS_LINUX = os.name == 'posix' and os.uname()[0] == 'Linux'
|
||||
|
||||
COMMAND = gtest_test_utils.GetTestExecutablePath('gtest_env_var_test_')
|
||||
|
||||
|
||||
def AssertEq(expected, actual):
|
||||
if expected != actual:
|
||||
print 'Expected: %s' % (expected,)
|
||||
print ' Actual: %s' % (actual,)
|
||||
raise AssertionError
|
||||
|
||||
|
||||
def SetEnvVar(env_var, value):
|
||||
"""Sets the env variable to 'value'; unsets it when 'value' is None."""
|
||||
|
||||
if value is not None:
|
||||
os.environ[env_var] = value
|
||||
elif env_var in os.environ:
|
||||
del os.environ[env_var]
|
||||
|
||||
|
||||
def GetFlag(flag):
|
||||
"""Runs gtest_env_var_test_ and returns its output."""
|
||||
|
||||
args = [COMMAND]
|
||||
if flag is not None:
|
||||
args += [flag]
|
||||
return gtest_test_utils.Subprocess(args).output
|
||||
|
||||
|
||||
def TestFlag(flag, test_val, default_val):
|
||||
"""Verifies that the given flag is affected by the corresponding env var."""
|
||||
|
||||
env_var = 'GTEST_' + flag.upper()
|
||||
SetEnvVar(env_var, test_val)
|
||||
AssertEq(test_val, GetFlag(flag))
|
||||
SetEnvVar(env_var, None)
|
||||
AssertEq(default_val, GetFlag(flag))
|
||||
|
||||
|
||||
class GTestEnvVarTest(gtest_test_utils.TestCase):
|
||||
def testEnvVarAffectsFlag(self):
|
||||
"""Tests that environment variable should affect the corresponding flag."""
|
||||
|
||||
TestFlag('break_on_failure', '1', '0')
|
||||
TestFlag('color', 'yes', 'auto')
|
||||
TestFlag('filter', 'FooTest.Bar', '*')
|
||||
TestFlag('output', 'xml:tmp/foo.xml', '')
|
||||
TestFlag('print_time', '0', '1')
|
||||
TestFlag('repeat', '999', '1')
|
||||
TestFlag('throw_on_failure', '1', '0')
|
||||
TestFlag('death_test_style', 'threadsafe', 'fast')
|
||||
|
||||
if IS_WINDOWS:
|
||||
TestFlag('catch_exceptions', '1', '0')
|
||||
|
||||
if IS_LINUX:
|
||||
TestFlag('death_test_use_fork', '1', '0')
|
||||
TestFlag('stack_trace_depth', '0', '100')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
gtest_test_utils.Main()
|
||||
#!/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.
|
||||
|
||||
"""Verifies that Google Test correctly parses environment variables."""
|
||||
|
||||
__author__ = 'wan@google.com (Zhanyong Wan)'
|
||||
|
||||
import os
|
||||
import gtest_test_utils
|
||||
|
||||
|
||||
IS_WINDOWS = os.name == 'nt'
|
||||
IS_LINUX = os.name == 'posix' and os.uname()[0] == 'Linux'
|
||||
|
||||
COMMAND = gtest_test_utils.GetTestExecutablePath('gtest_env_var_test_')
|
||||
|
||||
|
||||
def AssertEq(expected, actual):
|
||||
if expected != actual:
|
||||
print 'Expected: %s' % (expected,)
|
||||
print ' Actual: %s' % (actual,)
|
||||
raise AssertionError
|
||||
|
||||
|
||||
def SetEnvVar(env_var, value):
|
||||
"""Sets the env variable to 'value'; unsets it when 'value' is None."""
|
||||
|
||||
if value is not None:
|
||||
os.environ[env_var] = value
|
||||
elif env_var in os.environ:
|
||||
del os.environ[env_var]
|
||||
|
||||
|
||||
def GetFlag(flag):
|
||||
"""Runs gtest_env_var_test_ and returns its output."""
|
||||
|
||||
args = [COMMAND]
|
||||
if flag is not None:
|
||||
args += [flag]
|
||||
return gtest_test_utils.Subprocess(args).output
|
||||
|
||||
|
||||
def TestFlag(flag, test_val, default_val):
|
||||
"""Verifies that the given flag is affected by the corresponding env var."""
|
||||
|
||||
env_var = 'GTEST_' + flag.upper()
|
||||
SetEnvVar(env_var, test_val)
|
||||
AssertEq(test_val, GetFlag(flag))
|
||||
SetEnvVar(env_var, None)
|
||||
AssertEq(default_val, GetFlag(flag))
|
||||
|
||||
|
||||
class GTestEnvVarTest(gtest_test_utils.TestCase):
|
||||
def testEnvVarAffectsFlag(self):
|
||||
"""Tests that environment variable should affect the corresponding flag."""
|
||||
|
||||
TestFlag('break_on_failure', '1', '0')
|
||||
TestFlag('color', 'yes', 'auto')
|
||||
TestFlag('filter', 'FooTest.Bar', '*')
|
||||
TestFlag('output', 'xml:tmp/foo.xml', '')
|
||||
TestFlag('print_time', '0', '1')
|
||||
TestFlag('repeat', '999', '1')
|
||||
TestFlag('throw_on_failure', '1', '0')
|
||||
TestFlag('death_test_style', 'threadsafe', 'fast')
|
||||
|
||||
if IS_WINDOWS:
|
||||
TestFlag('catch_exceptions', '1', '0')
|
||||
|
||||
if IS_LINUX:
|
||||
TestFlag('death_test_use_fork', '1', '0')
|
||||
TestFlag('stack_trace_depth', '0', '100')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
gtest_test_utils.Main()
|
||||
|
||||
+594
-594
File diff suppressed because it is too large
Load Diff
+126
-126
@@ -1,126 +1,126 @@
|
||||
#!/usr/bin/env python
|
||||
#
|
||||
# Copyright 2009, 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.
|
||||
|
||||
"""Tests the --help flag of Google C++ Testing Framework.
|
||||
|
||||
SYNOPSIS
|
||||
gtest_help_test.py --gtest_build_dir=BUILD/DIR
|
||||
# where BUILD/DIR contains the built gtest_help_test_ file.
|
||||
gtest_help_test.py
|
||||
"""
|
||||
|
||||
__author__ = 'wan@google.com (Zhanyong Wan)'
|
||||
|
||||
import os
|
||||
import re
|
||||
import gtest_test_utils
|
||||
|
||||
|
||||
IS_WINDOWS = os.name == 'nt'
|
||||
|
||||
PROGRAM_PATH = gtest_test_utils.GetTestExecutablePath('gtest_help_test_')
|
||||
FLAG_PREFIX = '--gtest_'
|
||||
CATCH_EXCEPTIONS_FLAG = FLAG_PREFIX + 'catch_exceptions'
|
||||
DEATH_TEST_STYLE_FLAG = FLAG_PREFIX + 'death_test_style'
|
||||
|
||||
# The help message must match this regex.
|
||||
HELP_REGEX = re.compile(
|
||||
FLAG_PREFIX + r'list_tests.*' +
|
||||
FLAG_PREFIX + r'filter=.*' +
|
||||
FLAG_PREFIX + r'also_run_disabled_tests.*' +
|
||||
FLAG_PREFIX + r'repeat=.*' +
|
||||
FLAG_PREFIX + r'shuffle.*' +
|
||||
FLAG_PREFIX + r'random_seed=.*' +
|
||||
FLAG_PREFIX + r'color=.*' +
|
||||
FLAG_PREFIX + r'print_time.*' +
|
||||
FLAG_PREFIX + r'output=.*' +
|
||||
FLAG_PREFIX + r'break_on_failure.*' +
|
||||
FLAG_PREFIX + r'throw_on_failure.*',
|
||||
re.DOTALL)
|
||||
|
||||
|
||||
def RunWithFlag(flag):
|
||||
"""Runs gtest_help_test_ with the given flag.
|
||||
|
||||
Returns:
|
||||
the exit code and the text output as a tuple.
|
||||
Args:
|
||||
flag: the command-line flag to pass to gtest_help_test_, or None.
|
||||
"""
|
||||
|
||||
if flag is None:
|
||||
command = [PROGRAM_PATH]
|
||||
else:
|
||||
command = [PROGRAM_PATH, flag]
|
||||
child = gtest_test_utils.Subprocess(command)
|
||||
return child.exit_code, child.output
|
||||
|
||||
|
||||
class GTestHelpTest(gtest_test_utils.TestCase):
|
||||
"""Tests the --help flag and its equivalent forms."""
|
||||
|
||||
def TestHelpFlag(self, flag):
|
||||
"""Verifies that the right message is printed and the tests are
|
||||
skipped when the given flag is specified."""
|
||||
|
||||
exit_code, output = RunWithFlag(flag)
|
||||
self.assertEquals(0, exit_code)
|
||||
self.assert_(HELP_REGEX.search(output), output)
|
||||
if IS_WINDOWS:
|
||||
self.assert_(CATCH_EXCEPTIONS_FLAG in output, output)
|
||||
self.assert_(DEATH_TEST_STYLE_FLAG not in output, output)
|
||||
else:
|
||||
self.assert_(CATCH_EXCEPTIONS_FLAG not in output, output)
|
||||
self.assert_(DEATH_TEST_STYLE_FLAG in output, output)
|
||||
|
||||
def testPrintsHelpWithFullFlag(self):
|
||||
self.TestHelpFlag('--help')
|
||||
|
||||
def testPrintsHelpWithShortFlag(self):
|
||||
self.TestHelpFlag('-h')
|
||||
|
||||
def testPrintsHelpWithQuestionFlag(self):
|
||||
self.TestHelpFlag('-?')
|
||||
|
||||
def testPrintsHelpWithWindowsStyleQuestionFlag(self):
|
||||
self.TestHelpFlag('/?')
|
||||
|
||||
def testRunsTestsWithoutHelpFlag(self):
|
||||
"""Verifies that when no help flag is specified, the tests are run
|
||||
and the help message is not printed."""
|
||||
|
||||
exit_code, output = RunWithFlag(None)
|
||||
self.assert_(exit_code != 0)
|
||||
self.assert_(not HELP_REGEX.search(output), output)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
gtest_test_utils.Main()
|
||||
#!/usr/bin/env python
|
||||
#
|
||||
# Copyright 2009, 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.
|
||||
|
||||
"""Tests the --help flag of Google C++ Testing Framework.
|
||||
|
||||
SYNOPSIS
|
||||
gtest_help_test.py --gtest_build_dir=BUILD/DIR
|
||||
# where BUILD/DIR contains the built gtest_help_test_ file.
|
||||
gtest_help_test.py
|
||||
"""
|
||||
|
||||
__author__ = 'wan@google.com (Zhanyong Wan)'
|
||||
|
||||
import os
|
||||
import re
|
||||
import gtest_test_utils
|
||||
|
||||
|
||||
IS_WINDOWS = os.name == 'nt'
|
||||
|
||||
PROGRAM_PATH = gtest_test_utils.GetTestExecutablePath('gtest_help_test_')
|
||||
FLAG_PREFIX = '--gtest_'
|
||||
CATCH_EXCEPTIONS_FLAG = FLAG_PREFIX + 'catch_exceptions'
|
||||
DEATH_TEST_STYLE_FLAG = FLAG_PREFIX + 'death_test_style'
|
||||
|
||||
# The help message must match this regex.
|
||||
HELP_REGEX = re.compile(
|
||||
FLAG_PREFIX + r'list_tests.*' +
|
||||
FLAG_PREFIX + r'filter=.*' +
|
||||
FLAG_PREFIX + r'also_run_disabled_tests.*' +
|
||||
FLAG_PREFIX + r'repeat=.*' +
|
||||
FLAG_PREFIX + r'shuffle.*' +
|
||||
FLAG_PREFIX + r'random_seed=.*' +
|
||||
FLAG_PREFIX + r'color=.*' +
|
||||
FLAG_PREFIX + r'print_time.*' +
|
||||
FLAG_PREFIX + r'output=.*' +
|
||||
FLAG_PREFIX + r'break_on_failure.*' +
|
||||
FLAG_PREFIX + r'throw_on_failure.*',
|
||||
re.DOTALL)
|
||||
|
||||
|
||||
def RunWithFlag(flag):
|
||||
"""Runs gtest_help_test_ with the given flag.
|
||||
|
||||
Returns:
|
||||
the exit code and the text output as a tuple.
|
||||
Args:
|
||||
flag: the command-line flag to pass to gtest_help_test_, or None.
|
||||
"""
|
||||
|
||||
if flag is None:
|
||||
command = [PROGRAM_PATH]
|
||||
else:
|
||||
command = [PROGRAM_PATH, flag]
|
||||
child = gtest_test_utils.Subprocess(command)
|
||||
return child.exit_code, child.output
|
||||
|
||||
|
||||
class GTestHelpTest(gtest_test_utils.TestCase):
|
||||
"""Tests the --help flag and its equivalent forms."""
|
||||
|
||||
def TestHelpFlag(self, flag):
|
||||
"""Verifies that the right message is printed and the tests are
|
||||
skipped when the given flag is specified."""
|
||||
|
||||
exit_code, output = RunWithFlag(flag)
|
||||
self.assertEquals(0, exit_code)
|
||||
self.assert_(HELP_REGEX.search(output), output)
|
||||
if IS_WINDOWS:
|
||||
self.assert_(CATCH_EXCEPTIONS_FLAG in output, output)
|
||||
self.assert_(DEATH_TEST_STYLE_FLAG not in output, output)
|
||||
else:
|
||||
self.assert_(CATCH_EXCEPTIONS_FLAG not in output, output)
|
||||
self.assert_(DEATH_TEST_STYLE_FLAG in output, output)
|
||||
|
||||
def testPrintsHelpWithFullFlag(self):
|
||||
self.TestHelpFlag('--help')
|
||||
|
||||
def testPrintsHelpWithShortFlag(self):
|
||||
self.TestHelpFlag('-h')
|
||||
|
||||
def testPrintsHelpWithQuestionFlag(self):
|
||||
self.TestHelpFlag('-?')
|
||||
|
||||
def testPrintsHelpWithWindowsStyleQuestionFlag(self):
|
||||
self.TestHelpFlag('/?')
|
||||
|
||||
def testRunsTestsWithoutHelpFlag(self):
|
||||
"""Verifies that when no help flag is specified, the tests are run
|
||||
and the help message is not printed."""
|
||||
|
||||
exit_code, output = RunWithFlag(None)
|
||||
self.assert_(exit_code != 0)
|
||||
self.assert_(not HELP_REGEX.search(output), output)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
gtest_test_utils.Main()
|
||||
|
||||
+177
-177
@@ -1,177 +1,177 @@
|
||||
#!/usr/bin/env python
|
||||
#
|
||||
# Copyright 2006, 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.
|
||||
|
||||
"""Unit test for Google Test's --gtest_list_tests flag.
|
||||
|
||||
A user can ask Google Test to list all tests by specifying the
|
||||
--gtest_list_tests flag. This script tests such functionality
|
||||
by invoking gtest_list_tests_unittest_ (a program written with
|
||||
Google Test) the command line flags.
|
||||
"""
|
||||
|
||||
__author__ = 'phanna@google.com (Patrick Hanna)'
|
||||
|
||||
import gtest_test_utils
|
||||
|
||||
|
||||
# Constants.
|
||||
|
||||
# The command line flag for enabling/disabling listing all tests.
|
||||
LIST_TESTS_FLAG = 'gtest_list_tests'
|
||||
|
||||
# Path to the gtest_list_tests_unittest_ program.
|
||||
EXE_PATH = gtest_test_utils.GetTestExecutablePath('gtest_list_tests_unittest_')
|
||||
|
||||
# The expected output when running gtest_list_tests_unittest_ with
|
||||
# --gtest_list_tests
|
||||
EXPECTED_OUTPUT_NO_FILTER = """FooDeathTest.
|
||||
Test1
|
||||
Foo.
|
||||
Bar1
|
||||
Bar2
|
||||
DISABLED_Bar3
|
||||
Abc.
|
||||
Xyz
|
||||
Def
|
||||
FooBar.
|
||||
Baz
|
||||
FooTest.
|
||||
Test1
|
||||
DISABLED_Test2
|
||||
Test3
|
||||
"""
|
||||
|
||||
# The expected output when running gtest_list_tests_unittest_ with
|
||||
# --gtest_list_tests and --gtest_filter=Foo*.
|
||||
EXPECTED_OUTPUT_FILTER_FOO = """FooDeathTest.
|
||||
Test1
|
||||
Foo.
|
||||
Bar1
|
||||
Bar2
|
||||
DISABLED_Bar3
|
||||
FooBar.
|
||||
Baz
|
||||
FooTest.
|
||||
Test1
|
||||
DISABLED_Test2
|
||||
Test3
|
||||
"""
|
||||
|
||||
# Utilities.
|
||||
|
||||
|
||||
def Run(args):
|
||||
"""Runs gtest_list_tests_unittest_ and returns the list of tests printed."""
|
||||
|
||||
return gtest_test_utils.Subprocess([EXE_PATH] + args,
|
||||
capture_stderr=False).output
|
||||
|
||||
|
||||
# The unit test.
|
||||
|
||||
class GTestListTestsUnitTest(gtest_test_utils.TestCase):
|
||||
"""Tests using the --gtest_list_tests flag to list all tests."""
|
||||
|
||||
def RunAndVerify(self, flag_value, expected_output, other_flag):
|
||||
"""Runs gtest_list_tests_unittest_ and verifies that it prints
|
||||
the correct tests.
|
||||
|
||||
Args:
|
||||
flag_value: value of the --gtest_list_tests flag;
|
||||
None if the flag should not be present.
|
||||
|
||||
expected_output: the expected output after running command;
|
||||
|
||||
other_flag: a different flag to be passed to command
|
||||
along with gtest_list_tests;
|
||||
None if the flag should not be present.
|
||||
"""
|
||||
|
||||
if flag_value is None:
|
||||
flag = ''
|
||||
flag_expression = 'not set'
|
||||
elif flag_value == '0':
|
||||
flag = '--%s=0' % LIST_TESTS_FLAG
|
||||
flag_expression = '0'
|
||||
else:
|
||||
flag = '--%s' % LIST_TESTS_FLAG
|
||||
flag_expression = '1'
|
||||
|
||||
args = [flag]
|
||||
|
||||
if other_flag is not None:
|
||||
args += [other_flag]
|
||||
|
||||
output = Run(args)
|
||||
|
||||
msg = ('when %s is %s, the output of "%s" is "%s".' %
|
||||
(LIST_TESTS_FLAG, flag_expression, ' '.join(args), output))
|
||||
|
||||
if expected_output is not None:
|
||||
self.assert_(output == expected_output, msg)
|
||||
else:
|
||||
self.assert_(output != EXPECTED_OUTPUT_NO_FILTER, msg)
|
||||
|
||||
def testDefaultBehavior(self):
|
||||
"""Tests the behavior of the default mode."""
|
||||
|
||||
self.RunAndVerify(flag_value=None,
|
||||
expected_output=None,
|
||||
other_flag=None)
|
||||
|
||||
def testFlag(self):
|
||||
"""Tests using the --gtest_list_tests flag."""
|
||||
|
||||
self.RunAndVerify(flag_value='0',
|
||||
expected_output=None,
|
||||
other_flag=None)
|
||||
self.RunAndVerify(flag_value='1',
|
||||
expected_output=EXPECTED_OUTPUT_NO_FILTER,
|
||||
other_flag=None)
|
||||
|
||||
def testOverrideNonFilterFlags(self):
|
||||
"""Tests that --gtest_list_tests overrides the non-filter flags."""
|
||||
|
||||
self.RunAndVerify(flag_value='1',
|
||||
expected_output=EXPECTED_OUTPUT_NO_FILTER,
|
||||
other_flag='--gtest_break_on_failure')
|
||||
|
||||
def testWithFilterFlags(self):
|
||||
"""Tests that --gtest_list_tests takes into account the
|
||||
--gtest_filter flag."""
|
||||
|
||||
self.RunAndVerify(flag_value='1',
|
||||
expected_output=EXPECTED_OUTPUT_FILTER_FOO,
|
||||
other_flag='--gtest_filter=Foo*')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
gtest_test_utils.Main()
|
||||
#!/usr/bin/env python
|
||||
#
|
||||
# Copyright 2006, 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.
|
||||
|
||||
"""Unit test for Google Test's --gtest_list_tests flag.
|
||||
|
||||
A user can ask Google Test to list all tests by specifying the
|
||||
--gtest_list_tests flag. This script tests such functionality
|
||||
by invoking gtest_list_tests_unittest_ (a program written with
|
||||
Google Test) the command line flags.
|
||||
"""
|
||||
|
||||
__author__ = 'phanna@google.com (Patrick Hanna)'
|
||||
|
||||
import gtest_test_utils
|
||||
|
||||
|
||||
# Constants.
|
||||
|
||||
# The command line flag for enabling/disabling listing all tests.
|
||||
LIST_TESTS_FLAG = 'gtest_list_tests'
|
||||
|
||||
# Path to the gtest_list_tests_unittest_ program.
|
||||
EXE_PATH = gtest_test_utils.GetTestExecutablePath('gtest_list_tests_unittest_')
|
||||
|
||||
# The expected output when running gtest_list_tests_unittest_ with
|
||||
# --gtest_list_tests
|
||||
EXPECTED_OUTPUT_NO_FILTER = """FooDeathTest.
|
||||
Test1
|
||||
Foo.
|
||||
Bar1
|
||||
Bar2
|
||||
DISABLED_Bar3
|
||||
Abc.
|
||||
Xyz
|
||||
Def
|
||||
FooBar.
|
||||
Baz
|
||||
FooTest.
|
||||
Test1
|
||||
DISABLED_Test2
|
||||
Test3
|
||||
"""
|
||||
|
||||
# The expected output when running gtest_list_tests_unittest_ with
|
||||
# --gtest_list_tests and --gtest_filter=Foo*.
|
||||
EXPECTED_OUTPUT_FILTER_FOO = """FooDeathTest.
|
||||
Test1
|
||||
Foo.
|
||||
Bar1
|
||||
Bar2
|
||||
DISABLED_Bar3
|
||||
FooBar.
|
||||
Baz
|
||||
FooTest.
|
||||
Test1
|
||||
DISABLED_Test2
|
||||
Test3
|
||||
"""
|
||||
|
||||
# Utilities.
|
||||
|
||||
|
||||
def Run(args):
|
||||
"""Runs gtest_list_tests_unittest_ and returns the list of tests printed."""
|
||||
|
||||
return gtest_test_utils.Subprocess([EXE_PATH] + args,
|
||||
capture_stderr=False).output
|
||||
|
||||
|
||||
# The unit test.
|
||||
|
||||
class GTestListTestsUnitTest(gtest_test_utils.TestCase):
|
||||
"""Tests using the --gtest_list_tests flag to list all tests."""
|
||||
|
||||
def RunAndVerify(self, flag_value, expected_output, other_flag):
|
||||
"""Runs gtest_list_tests_unittest_ and verifies that it prints
|
||||
the correct tests.
|
||||
|
||||
Args:
|
||||
flag_value: value of the --gtest_list_tests flag;
|
||||
None if the flag should not be present.
|
||||
|
||||
expected_output: the expected output after running command;
|
||||
|
||||
other_flag: a different flag to be passed to command
|
||||
along with gtest_list_tests;
|
||||
None if the flag should not be present.
|
||||
"""
|
||||
|
||||
if flag_value is None:
|
||||
flag = ''
|
||||
flag_expression = 'not set'
|
||||
elif flag_value == '0':
|
||||
flag = '--%s=0' % LIST_TESTS_FLAG
|
||||
flag_expression = '0'
|
||||
else:
|
||||
flag = '--%s' % LIST_TESTS_FLAG
|
||||
flag_expression = '1'
|
||||
|
||||
args = [flag]
|
||||
|
||||
if other_flag is not None:
|
||||
args += [other_flag]
|
||||
|
||||
output = Run(args)
|
||||
|
||||
msg = ('when %s is %s, the output of "%s" is "%s".' %
|
||||
(LIST_TESTS_FLAG, flag_expression, ' '.join(args), output))
|
||||
|
||||
if expected_output is not None:
|
||||
self.assert_(output == expected_output, msg)
|
||||
else:
|
||||
self.assert_(output != EXPECTED_OUTPUT_NO_FILTER, msg)
|
||||
|
||||
def testDefaultBehavior(self):
|
||||
"""Tests the behavior of the default mode."""
|
||||
|
||||
self.RunAndVerify(flag_value=None,
|
||||
expected_output=None,
|
||||
other_flag=None)
|
||||
|
||||
def testFlag(self):
|
||||
"""Tests using the --gtest_list_tests flag."""
|
||||
|
||||
self.RunAndVerify(flag_value='0',
|
||||
expected_output=None,
|
||||
other_flag=None)
|
||||
self.RunAndVerify(flag_value='1',
|
||||
expected_output=EXPECTED_OUTPUT_NO_FILTER,
|
||||
other_flag=None)
|
||||
|
||||
def testOverrideNonFilterFlags(self):
|
||||
"""Tests that --gtest_list_tests overrides the non-filter flags."""
|
||||
|
||||
self.RunAndVerify(flag_value='1',
|
||||
expected_output=EXPECTED_OUTPUT_NO_FILTER,
|
||||
other_flag='--gtest_break_on_failure')
|
||||
|
||||
def testWithFilterFlags(self):
|
||||
"""Tests that --gtest_list_tests takes into account the
|
||||
--gtest_filter flag."""
|
||||
|
||||
self.RunAndVerify(flag_value='1',
|
||||
expected_output=EXPECTED_OUTPUT_FILTER_FOO,
|
||||
other_flag='--gtest_filter=Foo*')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
gtest_test_utils.Main()
|
||||
|
||||
+106
-106
@@ -1,106 +1,106 @@
|
||||
#!/usr/bin/env python
|
||||
#
|
||||
# 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.
|
||||
|
||||
"""Negative compilation test for Google Test."""
|
||||
|
||||
__author__ = 'wan@google.com (Zhanyong Wan)'
|
||||
|
||||
import os
|
||||
import sys
|
||||
import unittest
|
||||
|
||||
|
||||
IS_LINUX = os.name == 'posix' and os.uname()[0] == 'Linux'
|
||||
if not IS_LINUX:
|
||||
sys.exit(0) # Negative compilation tests are not supported on Windows & Mac.
|
||||
|
||||
|
||||
class GTestNCTest(unittest.TestCase):
|
||||
"""Negative compilation test for Google Test."""
|
||||
|
||||
def testCompilerError(self):
|
||||
"""Verifies that erroneous code leads to expected compiler
|
||||
messages."""
|
||||
|
||||
# Defines a list of test specs, where each element is a tuple
|
||||
# (test name, list of regexes for matching the compiler errors).
|
||||
test_specs = [
|
||||
('CANNOT_IGNORE_RUN_ALL_TESTS_RESULT',
|
||||
[r'ignoring return value']),
|
||||
|
||||
('USER_CANNOT_INCLUDE_GTEST_INTERNAL_INL_H',
|
||||
[r'must not be included except by Google Test itself']),
|
||||
|
||||
('CATCHES_DECLARING_SETUP_IN_TEST_FIXTURE_WITH_TYPO',
|
||||
[r'Setup_should_be_spelled_SetUp']),
|
||||
|
||||
('CATCHES_CALLING_SETUP_IN_TEST_WITH_TYPO',
|
||||
[r'Setup_should_be_spelled_SetUp']),
|
||||
|
||||
('CATCHES_DECLARING_SETUP_IN_ENVIRONMENT_WITH_TYPO',
|
||||
[r'Setup_should_be_spelled_SetUp']),
|
||||
|
||||
('CATCHES_CALLING_SETUP_IN_ENVIRONMENT_WITH_TYPO',
|
||||
[r'Setup_should_be_spelled_SetUp']),
|
||||
|
||||
('CATCHES_WRONG_CASE_IN_TYPED_TEST_P',
|
||||
[r'BarTest.*was not declared']),
|
||||
|
||||
('CATCHES_WRONG_CASE_IN_REGISTER_TYPED_TEST_CASE_P',
|
||||
[r'BarTest.*was not declared']),
|
||||
|
||||
('CATCHES_WRONG_CASE_IN_INSTANTIATE_TYPED_TEST_CASE_P',
|
||||
[r'BarTest.*not declared']),
|
||||
|
||||
('CATCHES_INSTANTIATE_TYPED_TESET_CASE_P_WITH_SAME_NAME_PREFIX',
|
||||
[r'redefinition of.*My.*FooTest']),
|
||||
|
||||
('STATIC_ASSERT_TYPE_EQ_IS_NOT_A_TYPE',
|
||||
[r'StaticAssertTypeEq.* does not name a type']),
|
||||
|
||||
('STATIC_ASSERT_TYPE_EQ_WORKS_IN_NAMESPACE',
|
||||
[r'StaticAssertTypeEq.*int.*const int']),
|
||||
|
||||
('STATIC_ASSERT_TYPE_EQ_WORKS_IN_CLASS',
|
||||
[r'StaticAssertTypeEq.*int.*bool']),
|
||||
|
||||
('STATIC_ASSERT_TYPE_EQ_WORKS_IN_FUNCTION',
|
||||
[r'StaticAssertTypeEq.*const int.*int']),
|
||||
|
||||
('SANITY',
|
||||
None)
|
||||
]
|
||||
|
||||
# TODO(wan@google.com): verify that the test specs are satisfied.
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
#!/usr/bin/env python
|
||||
#
|
||||
# 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.
|
||||
|
||||
"""Negative compilation test for Google Test."""
|
||||
|
||||
__author__ = 'wan@google.com (Zhanyong Wan)'
|
||||
|
||||
import os
|
||||
import sys
|
||||
import unittest
|
||||
|
||||
|
||||
IS_LINUX = os.name == 'posix' and os.uname()[0] == 'Linux'
|
||||
if not IS_LINUX:
|
||||
sys.exit(0) # Negative compilation tests are not supported on Windows & Mac.
|
||||
|
||||
|
||||
class GTestNCTest(unittest.TestCase):
|
||||
"""Negative compilation test for Google Test."""
|
||||
|
||||
def testCompilerError(self):
|
||||
"""Verifies that erroneous code leads to expected compiler
|
||||
messages."""
|
||||
|
||||
# Defines a list of test specs, where each element is a tuple
|
||||
# (test name, list of regexes for matching the compiler errors).
|
||||
test_specs = [
|
||||
('CANNOT_IGNORE_RUN_ALL_TESTS_RESULT',
|
||||
[r'ignoring return value']),
|
||||
|
||||
('USER_CANNOT_INCLUDE_GTEST_INTERNAL_INL_H',
|
||||
[r'must not be included except by Google Test itself']),
|
||||
|
||||
('CATCHES_DECLARING_SETUP_IN_TEST_FIXTURE_WITH_TYPO',
|
||||
[r'Setup_should_be_spelled_SetUp']),
|
||||
|
||||
('CATCHES_CALLING_SETUP_IN_TEST_WITH_TYPO',
|
||||
[r'Setup_should_be_spelled_SetUp']),
|
||||
|
||||
('CATCHES_DECLARING_SETUP_IN_ENVIRONMENT_WITH_TYPO',
|
||||
[r'Setup_should_be_spelled_SetUp']),
|
||||
|
||||
('CATCHES_CALLING_SETUP_IN_ENVIRONMENT_WITH_TYPO',
|
||||
[r'Setup_should_be_spelled_SetUp']),
|
||||
|
||||
('CATCHES_WRONG_CASE_IN_TYPED_TEST_P',
|
||||
[r'BarTest.*was not declared']),
|
||||
|
||||
('CATCHES_WRONG_CASE_IN_REGISTER_TYPED_TEST_CASE_P',
|
||||
[r'BarTest.*was not declared']),
|
||||
|
||||
('CATCHES_WRONG_CASE_IN_INSTANTIATE_TYPED_TEST_CASE_P',
|
||||
[r'BarTest.*not declared']),
|
||||
|
||||
('CATCHES_INSTANTIATE_TYPED_TESET_CASE_P_WITH_SAME_NAME_PREFIX',
|
||||
[r'redefinition of.*My.*FooTest']),
|
||||
|
||||
('STATIC_ASSERT_TYPE_EQ_IS_NOT_A_TYPE',
|
||||
[r'StaticAssertTypeEq.* does not name a type']),
|
||||
|
||||
('STATIC_ASSERT_TYPE_EQ_WORKS_IN_NAMESPACE',
|
||||
[r'StaticAssertTypeEq.*int.*const int']),
|
||||
|
||||
('STATIC_ASSERT_TYPE_EQ_WORKS_IN_CLASS',
|
||||
[r'StaticAssertTypeEq.*int.*bool']),
|
||||
|
||||
('STATIC_ASSERT_TYPE_EQ_WORKS_IN_FUNCTION',
|
||||
[r'StaticAssertTypeEq.*const int.*int']),
|
||||
|
||||
('SANITY',
|
||||
None)
|
||||
]
|
||||
|
||||
# TODO(wan@google.com): verify that the test specs are satisfied.
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
|
||||
+307
-307
@@ -1,307 +1,307 @@
|
||||
#!/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.
|
||||
|
||||
"""Tests the text output of Google C++ Testing Framework.
|
||||
|
||||
SYNOPSIS
|
||||
gtest_output_test.py --gtest_build_dir=BUILD/DIR --gengolden
|
||||
# where BUILD/DIR contains the built gtest_output_test_ file.
|
||||
gtest_output_test.py --gengolden
|
||||
gtest_output_test.py
|
||||
"""
|
||||
|
||||
__author__ = 'wan@google.com (Zhanyong Wan)'
|
||||
|
||||
import os
|
||||
import re
|
||||
import sys
|
||||
import gtest_test_utils
|
||||
|
||||
|
||||
# The flag for generating the golden file
|
||||
GENGOLDEN_FLAG = '--gengolden'
|
||||
|
||||
IS_WINDOWS = os.name == 'nt'
|
||||
|
||||
if IS_WINDOWS:
|
||||
GOLDEN_NAME = 'gtest_output_test_golden_win.txt'
|
||||
else:
|
||||
GOLDEN_NAME = 'gtest_output_test_golden_lin.txt'
|
||||
|
||||
PROGRAM_PATH = gtest_test_utils.GetTestExecutablePath('gtest_output_test_')
|
||||
|
||||
# At least one command we exercise must not have the
|
||||
# --gtest_internal_skip_environment_and_ad_hoc_tests flag.
|
||||
COMMAND_LIST_TESTS = ({}, [PROGRAM_PATH, '--gtest_list_tests'])
|
||||
COMMAND_WITH_COLOR = ({}, [PROGRAM_PATH, '--gtest_color=yes'])
|
||||
COMMAND_WITH_TIME = ({}, [PROGRAM_PATH,
|
||||
'--gtest_print_time',
|
||||
'--gtest_internal_skip_environment_and_ad_hoc_tests',
|
||||
'--gtest_filter=FatalFailureTest.*:LoggingTest.*'])
|
||||
COMMAND_WITH_DISABLED = (
|
||||
{}, [PROGRAM_PATH,
|
||||
'--gtest_also_run_disabled_tests',
|
||||
'--gtest_internal_skip_environment_and_ad_hoc_tests',
|
||||
'--gtest_filter=*DISABLED_*'])
|
||||
COMMAND_WITH_SHARDING = (
|
||||
{'GTEST_SHARD_INDEX': '1', 'GTEST_TOTAL_SHARDS': '2'},
|
||||
[PROGRAM_PATH,
|
||||
'--gtest_internal_skip_environment_and_ad_hoc_tests',
|
||||
'--gtest_filter=PassingTest.*'])
|
||||
|
||||
GOLDEN_PATH = os.path.join(gtest_test_utils.GetSourceDir(), GOLDEN_NAME)
|
||||
|
||||
|
||||
def ToUnixLineEnding(s):
|
||||
"""Changes all Windows/Mac line endings in s to UNIX line endings."""
|
||||
|
||||
return s.replace('\r\n', '\n').replace('\r', '\n')
|
||||
|
||||
|
||||
def RemoveLocations(test_output):
|
||||
"""Removes all file location info from a Google Test program's output.
|
||||
|
||||
Args:
|
||||
test_output: the output of a Google Test program.
|
||||
|
||||
Returns:
|
||||
output with all file location info (in the form of
|
||||
'DIRECTORY/FILE_NAME:LINE_NUMBER: 'or
|
||||
'DIRECTORY\\FILE_NAME(LINE_NUMBER): ') replaced by
|
||||
'FILE_NAME:#: '.
|
||||
"""
|
||||
|
||||
return re.sub(r'.*[/\\](.+)(\:\d+|\(\d+\))\: ', r'\1:#: ', test_output)
|
||||
|
||||
|
||||
def RemoveStackTraceDetails(output):
|
||||
"""Removes all stack traces from a Google Test program's output."""
|
||||
|
||||
# *? means "find the shortest string that matches".
|
||||
return re.sub(r'Stack trace:(.|\n)*?\n\n',
|
||||
'Stack trace: (omitted)\n\n', output)
|
||||
|
||||
|
||||
def RemoveStackTraces(output):
|
||||
"""Removes all traces of stack traces from a Google Test program's output."""
|
||||
|
||||
# *? means "find the shortest string that matches".
|
||||
return re.sub(r'Stack trace:(.|\n)*?\n\n', '', output)
|
||||
|
||||
|
||||
def RemoveTime(output):
|
||||
"""Removes all time information from a Google Test program's output."""
|
||||
|
||||
return re.sub(r'\(\d+ ms', '(? ms', output)
|
||||
|
||||
|
||||
def RemoveTestCounts(output):
|
||||
"""Removes test counts from a Google Test program's output."""
|
||||
|
||||
output = re.sub(r'\d+ tests, listed below',
|
||||
'? tests, listed below', output)
|
||||
output = re.sub(r'\d+ FAILED TESTS',
|
||||
'? FAILED TESTS', output)
|
||||
output = re.sub(r'\d+ tests from \d+ test cases',
|
||||
'? tests from ? test cases', output)
|
||||
output = re.sub(r'\d+ tests from ([a-zA-Z_])',
|
||||
r'? tests from \1', output)
|
||||
return re.sub(r'\d+ tests\.', '? tests.', output)
|
||||
|
||||
|
||||
def RemoveMatchingTests(test_output, pattern):
|
||||
"""Removes output of specified tests from a Google Test program's output.
|
||||
|
||||
This function strips not only the beginning and the end of a test but also
|
||||
all output in between.
|
||||
|
||||
Args:
|
||||
test_output: A string containing the test output.
|
||||
pattern: A regex string that matches names of test cases or
|
||||
tests to remove.
|
||||
|
||||
Returns:
|
||||
Contents of test_output with tests whose names match pattern removed.
|
||||
"""
|
||||
|
||||
test_output = re.sub(
|
||||
r'.*\[ RUN \] .*%s(.|\n)*?\[( FAILED | OK )\] .*%s.*\n' % (
|
||||
pattern, pattern),
|
||||
'',
|
||||
test_output)
|
||||
return re.sub(r'.*%s.*\n' % pattern, '', test_output)
|
||||
|
||||
|
||||
def NormalizeOutput(output):
|
||||
"""Normalizes output (the output of gtest_output_test_.exe)."""
|
||||
|
||||
output = ToUnixLineEnding(output)
|
||||
output = RemoveLocations(output)
|
||||
output = RemoveStackTraceDetails(output)
|
||||
output = RemoveTime(output)
|
||||
return output
|
||||
|
||||
|
||||
def GetShellCommandOutput(env_cmd):
|
||||
"""Runs a command in a sub-process, and returns its output in a string.
|
||||
|
||||
Args:
|
||||
env_cmd: The shell command. A 2-tuple where element 0 is a dict of extra
|
||||
environment variables to set, and element 1 is a string with
|
||||
the command and any flags.
|
||||
|
||||
Returns:
|
||||
A string with the command's combined standard and diagnostic output.
|
||||
"""
|
||||
|
||||
# Spawns cmd in a sub-process, and gets its standard I/O file objects.
|
||||
# Set and save the environment properly.
|
||||
old_env_vars = dict(os.environ)
|
||||
os.environ.update(env_cmd[0])
|
||||
p = gtest_test_utils.Subprocess(env_cmd[1])
|
||||
|
||||
# Changes made by os.environ.clear are not inheritable by child processes
|
||||
# until Python 2.6. To produce inheritable changes we have to delete
|
||||
# environment items with the del statement.
|
||||
for key in os.environ.keys():
|
||||
del os.environ[key]
|
||||
os.environ.update(old_env_vars)
|
||||
|
||||
return p.output
|
||||
|
||||
|
||||
def GetCommandOutput(env_cmd):
|
||||
"""Runs a command and returns its output with all file location
|
||||
info stripped off.
|
||||
|
||||
Args:
|
||||
env_cmd: The shell command. A 2-tuple where element 0 is a dict of extra
|
||||
environment variables to set, and element 1 is a string with
|
||||
the command and any flags.
|
||||
"""
|
||||
|
||||
# Disables exception pop-ups on Windows.
|
||||
os.environ['GTEST_CATCH_EXCEPTIONS'] = '1'
|
||||
return NormalizeOutput(GetShellCommandOutput(env_cmd))
|
||||
|
||||
|
||||
def GetOutputOfAllCommands():
|
||||
"""Returns concatenated output from several representative commands."""
|
||||
|
||||
return (GetCommandOutput(COMMAND_WITH_COLOR) +
|
||||
GetCommandOutput(COMMAND_WITH_TIME) +
|
||||
GetCommandOutput(COMMAND_WITH_DISABLED) +
|
||||
GetCommandOutput(COMMAND_WITH_SHARDING))
|
||||
|
||||
|
||||
test_list = GetShellCommandOutput(COMMAND_LIST_TESTS)
|
||||
SUPPORTS_DEATH_TESTS = 'DeathTest' in test_list
|
||||
SUPPORTS_TYPED_TESTS = 'TypedTest' in test_list
|
||||
SUPPORTS_THREADS = 'ExpectFailureWithThreadsTest' in test_list
|
||||
SUPPORTS_STACK_TRACES = False
|
||||
|
||||
CAN_GENERATE_GOLDEN_FILE = SUPPORTS_DEATH_TESTS and SUPPORTS_TYPED_TESTS
|
||||
|
||||
|
||||
class GTestOutputTest(gtest_test_utils.TestCase):
|
||||
def RemoveUnsupportedTests(self, test_output):
|
||||
if not SUPPORTS_DEATH_TESTS:
|
||||
test_output = RemoveMatchingTests(test_output, 'DeathTest')
|
||||
if not SUPPORTS_TYPED_TESTS:
|
||||
test_output = RemoveMatchingTests(test_output, 'TypedTest')
|
||||
if not SUPPORTS_THREADS:
|
||||
test_output = RemoveMatchingTests(test_output,
|
||||
'ExpectFailureWithThreadsTest')
|
||||
test_output = RemoveMatchingTests(test_output,
|
||||
'ScopedFakeTestPartResultReporterTest')
|
||||
test_output = RemoveMatchingTests(test_output,
|
||||
'WorksConcurrently')
|
||||
if not SUPPORTS_STACK_TRACES:
|
||||
test_output = RemoveStackTraces(test_output)
|
||||
|
||||
return test_output
|
||||
|
||||
def testOutput(self):
|
||||
output = GetOutputOfAllCommands()
|
||||
|
||||
golden_file = open(GOLDEN_PATH, 'rb')
|
||||
# A mis-configured source control system can cause \r appear in EOL
|
||||
# sequences when we read the golden file irrespective of an operating
|
||||
# system used. Therefore, we need to strip those \r's from newlines
|
||||
# unconditionally.
|
||||
golden = ToUnixLineEnding(golden_file.read())
|
||||
golden_file.close()
|
||||
|
||||
# We want the test to pass regardless of certain features being
|
||||
# supported or not.
|
||||
if CAN_GENERATE_GOLDEN_FILE:
|
||||
self.assert_(golden == output)
|
||||
else:
|
||||
normalized_actual = RemoveTestCounts(output)
|
||||
normalized_golden = RemoveTestCounts(self.RemoveUnsupportedTests(golden))
|
||||
|
||||
# This code is very handy when debugging test differences so I left it
|
||||
# here, commented.
|
||||
# open(os.path.join(
|
||||
# gtest_test_utils.GetSourceDir(),
|
||||
# '_gtest_output_test_normalized_actual.txt'), 'wb').write(
|
||||
# normalized_actual)
|
||||
# open(os.path.join(
|
||||
# gtest_test_utils.GetSourceDir(),
|
||||
# '_gtest_output_test_normalized_golden.txt'), 'wb').write(
|
||||
# normalized_golden)
|
||||
|
||||
self.assert_(normalized_golden == normalized_actual)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
if sys.argv[1:] == [GENGOLDEN_FLAG]:
|
||||
if CAN_GENERATE_GOLDEN_FILE:
|
||||
output = GetOutputOfAllCommands()
|
||||
golden_file = open(GOLDEN_PATH, 'wb')
|
||||
golden_file.write(output)
|
||||
golden_file.close()
|
||||
else:
|
||||
message = (
|
||||
"""Unable to write a golden file when compiled in an environment
|
||||
that does not support all the required features (death tests""")
|
||||
if IS_WINDOWS:
|
||||
message += (
|
||||
"""\nand typed tests). Please check that you are using VC++ 8.0 SP1
|
||||
or higher as your compiler.""")
|
||||
else:
|
||||
message += """\nand typed tests). Please generate the golden file
|
||||
using a binary built with those features enabled."""
|
||||
|
||||
sys.stderr.write(message)
|
||||
sys.exit(1)
|
||||
else:
|
||||
gtest_test_utils.Main()
|
||||
#!/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.
|
||||
|
||||
"""Tests the text output of Google C++ Testing Framework.
|
||||
|
||||
SYNOPSIS
|
||||
gtest_output_test.py --gtest_build_dir=BUILD/DIR --gengolden
|
||||
# where BUILD/DIR contains the built gtest_output_test_ file.
|
||||
gtest_output_test.py --gengolden
|
||||
gtest_output_test.py
|
||||
"""
|
||||
|
||||
__author__ = 'wan@google.com (Zhanyong Wan)'
|
||||
|
||||
import os
|
||||
import re
|
||||
import sys
|
||||
import gtest_test_utils
|
||||
|
||||
|
||||
# The flag for generating the golden file
|
||||
GENGOLDEN_FLAG = '--gengolden'
|
||||
|
||||
IS_WINDOWS = os.name == 'nt'
|
||||
|
||||
if IS_WINDOWS:
|
||||
GOLDEN_NAME = 'gtest_output_test_golden_win.txt'
|
||||
else:
|
||||
GOLDEN_NAME = 'gtest_output_test_golden_lin.txt'
|
||||
|
||||
PROGRAM_PATH = gtest_test_utils.GetTestExecutablePath('gtest_output_test_')
|
||||
|
||||
# At least one command we exercise must not have the
|
||||
# --gtest_internal_skip_environment_and_ad_hoc_tests flag.
|
||||
COMMAND_LIST_TESTS = ({}, [PROGRAM_PATH, '--gtest_list_tests'])
|
||||
COMMAND_WITH_COLOR = ({}, [PROGRAM_PATH, '--gtest_color=yes'])
|
||||
COMMAND_WITH_TIME = ({}, [PROGRAM_PATH,
|
||||
'--gtest_print_time',
|
||||
'--gtest_internal_skip_environment_and_ad_hoc_tests',
|
||||
'--gtest_filter=FatalFailureTest.*:LoggingTest.*'])
|
||||
COMMAND_WITH_DISABLED = (
|
||||
{}, [PROGRAM_PATH,
|
||||
'--gtest_also_run_disabled_tests',
|
||||
'--gtest_internal_skip_environment_and_ad_hoc_tests',
|
||||
'--gtest_filter=*DISABLED_*'])
|
||||
COMMAND_WITH_SHARDING = (
|
||||
{'GTEST_SHARD_INDEX': '1', 'GTEST_TOTAL_SHARDS': '2'},
|
||||
[PROGRAM_PATH,
|
||||
'--gtest_internal_skip_environment_and_ad_hoc_tests',
|
||||
'--gtest_filter=PassingTest.*'])
|
||||
|
||||
GOLDEN_PATH = os.path.join(gtest_test_utils.GetSourceDir(), GOLDEN_NAME)
|
||||
|
||||
|
||||
def ToUnixLineEnding(s):
|
||||
"""Changes all Windows/Mac line endings in s to UNIX line endings."""
|
||||
|
||||
return s.replace('\r\n', '\n').replace('\r', '\n')
|
||||
|
||||
|
||||
def RemoveLocations(test_output):
|
||||
"""Removes all file location info from a Google Test program's output.
|
||||
|
||||
Args:
|
||||
test_output: the output of a Google Test program.
|
||||
|
||||
Returns:
|
||||
output with all file location info (in the form of
|
||||
'DIRECTORY/FILE_NAME:LINE_NUMBER: 'or
|
||||
'DIRECTORY\\FILE_NAME(LINE_NUMBER): ') replaced by
|
||||
'FILE_NAME:#: '.
|
||||
"""
|
||||
|
||||
return re.sub(r'.*[/\\](.+)(\:\d+|\(\d+\))\: ', r'\1:#: ', test_output)
|
||||
|
||||
|
||||
def RemoveStackTraceDetails(output):
|
||||
"""Removes all stack traces from a Google Test program's output."""
|
||||
|
||||
# *? means "find the shortest string that matches".
|
||||
return re.sub(r'Stack trace:(.|\n)*?\n\n',
|
||||
'Stack trace: (omitted)\n\n', output)
|
||||
|
||||
|
||||
def RemoveStackTraces(output):
|
||||
"""Removes all traces of stack traces from a Google Test program's output."""
|
||||
|
||||
# *? means "find the shortest string that matches".
|
||||
return re.sub(r'Stack trace:(.|\n)*?\n\n', '', output)
|
||||
|
||||
|
||||
def RemoveTime(output):
|
||||
"""Removes all time information from a Google Test program's output."""
|
||||
|
||||
return re.sub(r'\(\d+ ms', '(? ms', output)
|
||||
|
||||
|
||||
def RemoveTestCounts(output):
|
||||
"""Removes test counts from a Google Test program's output."""
|
||||
|
||||
output = re.sub(r'\d+ tests, listed below',
|
||||
'? tests, listed below', output)
|
||||
output = re.sub(r'\d+ FAILED TESTS',
|
||||
'? FAILED TESTS', output)
|
||||
output = re.sub(r'\d+ tests from \d+ test cases',
|
||||
'? tests from ? test cases', output)
|
||||
output = re.sub(r'\d+ tests from ([a-zA-Z_])',
|
||||
r'? tests from \1', output)
|
||||
return re.sub(r'\d+ tests\.', '? tests.', output)
|
||||
|
||||
|
||||
def RemoveMatchingTests(test_output, pattern):
|
||||
"""Removes output of specified tests from a Google Test program's output.
|
||||
|
||||
This function strips not only the beginning and the end of a test but also
|
||||
all output in between.
|
||||
|
||||
Args:
|
||||
test_output: A string containing the test output.
|
||||
pattern: A regex string that matches names of test cases or
|
||||
tests to remove.
|
||||
|
||||
Returns:
|
||||
Contents of test_output with tests whose names match pattern removed.
|
||||
"""
|
||||
|
||||
test_output = re.sub(
|
||||
r'.*\[ RUN \] .*%s(.|\n)*?\[( FAILED | OK )\] .*%s.*\n' % (
|
||||
pattern, pattern),
|
||||
'',
|
||||
test_output)
|
||||
return re.sub(r'.*%s.*\n' % pattern, '', test_output)
|
||||
|
||||
|
||||
def NormalizeOutput(output):
|
||||
"""Normalizes output (the output of gtest_output_test_.exe)."""
|
||||
|
||||
output = ToUnixLineEnding(output)
|
||||
output = RemoveLocations(output)
|
||||
output = RemoveStackTraceDetails(output)
|
||||
output = RemoveTime(output)
|
||||
return output
|
||||
|
||||
|
||||
def GetShellCommandOutput(env_cmd):
|
||||
"""Runs a command in a sub-process, and returns its output in a string.
|
||||
|
||||
Args:
|
||||
env_cmd: The shell command. A 2-tuple where element 0 is a dict of extra
|
||||
environment variables to set, and element 1 is a string with
|
||||
the command and any flags.
|
||||
|
||||
Returns:
|
||||
A string with the command's combined standard and diagnostic output.
|
||||
"""
|
||||
|
||||
# Spawns cmd in a sub-process, and gets its standard I/O file objects.
|
||||
# Set and save the environment properly.
|
||||
old_env_vars = dict(os.environ)
|
||||
os.environ.update(env_cmd[0])
|
||||
p = gtest_test_utils.Subprocess(env_cmd[1])
|
||||
|
||||
# Changes made by os.environ.clear are not inheritable by child processes
|
||||
# until Python 2.6. To produce inheritable changes we have to delete
|
||||
# environment items with the del statement.
|
||||
for key in os.environ.keys():
|
||||
del os.environ[key]
|
||||
os.environ.update(old_env_vars)
|
||||
|
||||
return p.output
|
||||
|
||||
|
||||
def GetCommandOutput(env_cmd):
|
||||
"""Runs a command and returns its output with all file location
|
||||
info stripped off.
|
||||
|
||||
Args:
|
||||
env_cmd: The shell command. A 2-tuple where element 0 is a dict of extra
|
||||
environment variables to set, and element 1 is a string with
|
||||
the command and any flags.
|
||||
"""
|
||||
|
||||
# Disables exception pop-ups on Windows.
|
||||
os.environ['GTEST_CATCH_EXCEPTIONS'] = '1'
|
||||
return NormalizeOutput(GetShellCommandOutput(env_cmd))
|
||||
|
||||
|
||||
def GetOutputOfAllCommands():
|
||||
"""Returns concatenated output from several representative commands."""
|
||||
|
||||
return (GetCommandOutput(COMMAND_WITH_COLOR) +
|
||||
GetCommandOutput(COMMAND_WITH_TIME) +
|
||||
GetCommandOutput(COMMAND_WITH_DISABLED) +
|
||||
GetCommandOutput(COMMAND_WITH_SHARDING))
|
||||
|
||||
|
||||
test_list = GetShellCommandOutput(COMMAND_LIST_TESTS)
|
||||
SUPPORTS_DEATH_TESTS = 'DeathTest' in test_list
|
||||
SUPPORTS_TYPED_TESTS = 'TypedTest' in test_list
|
||||
SUPPORTS_THREADS = 'ExpectFailureWithThreadsTest' in test_list
|
||||
SUPPORTS_STACK_TRACES = False
|
||||
|
||||
CAN_GENERATE_GOLDEN_FILE = SUPPORTS_DEATH_TESTS and SUPPORTS_TYPED_TESTS
|
||||
|
||||
|
||||
class GTestOutputTest(gtest_test_utils.TestCase):
|
||||
def RemoveUnsupportedTests(self, test_output):
|
||||
if not SUPPORTS_DEATH_TESTS:
|
||||
test_output = RemoveMatchingTests(test_output, 'DeathTest')
|
||||
if not SUPPORTS_TYPED_TESTS:
|
||||
test_output = RemoveMatchingTests(test_output, 'TypedTest')
|
||||
if not SUPPORTS_THREADS:
|
||||
test_output = RemoveMatchingTests(test_output,
|
||||
'ExpectFailureWithThreadsTest')
|
||||
test_output = RemoveMatchingTests(test_output,
|
||||
'ScopedFakeTestPartResultReporterTest')
|
||||
test_output = RemoveMatchingTests(test_output,
|
||||
'WorksConcurrently')
|
||||
if not SUPPORTS_STACK_TRACES:
|
||||
test_output = RemoveStackTraces(test_output)
|
||||
|
||||
return test_output
|
||||
|
||||
def testOutput(self):
|
||||
output = GetOutputOfAllCommands()
|
||||
|
||||
golden_file = open(GOLDEN_PATH, 'rb')
|
||||
# A mis-configured source control system can cause \r appear in EOL
|
||||
# sequences when we read the golden file irrespective of an operating
|
||||
# system used. Therefore, we need to strip those \r's from newlines
|
||||
# unconditionally.
|
||||
golden = ToUnixLineEnding(golden_file.read())
|
||||
golden_file.close()
|
||||
|
||||
# We want the test to pass regardless of certain features being
|
||||
# supported or not.
|
||||
if CAN_GENERATE_GOLDEN_FILE:
|
||||
self.assert_(golden == output)
|
||||
else:
|
||||
normalized_actual = RemoveTestCounts(output)
|
||||
normalized_golden = RemoveTestCounts(self.RemoveUnsupportedTests(golden))
|
||||
|
||||
# This code is very handy when debugging test differences so I left it
|
||||
# here, commented.
|
||||
# open(os.path.join(
|
||||
# gtest_test_utils.GetSourceDir(),
|
||||
# '_gtest_output_test_normalized_actual.txt'), 'wb').write(
|
||||
# normalized_actual)
|
||||
# open(os.path.join(
|
||||
# gtest_test_utils.GetSourceDir(),
|
||||
# '_gtest_output_test_normalized_golden.txt'), 'wb').write(
|
||||
# normalized_golden)
|
||||
|
||||
self.assert_(normalized_golden == normalized_actual)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
if sys.argv[1:] == [GENGOLDEN_FLAG]:
|
||||
if CAN_GENERATE_GOLDEN_FILE:
|
||||
output = GetOutputOfAllCommands()
|
||||
golden_file = open(GOLDEN_PATH, 'wb')
|
||||
golden_file.write(output)
|
||||
golden_file.close()
|
||||
else:
|
||||
message = (
|
||||
"""Unable to write a golden file when compiled in an environment
|
||||
that does not support all the required features (death tests""")
|
||||
if IS_WINDOWS:
|
||||
message += (
|
||||
"""\nand typed tests). Please check that you are using VC++ 8.0 SP1
|
||||
or higher as your compiler.""")
|
||||
else:
|
||||
message += """\nand typed tests). Please generate the golden file
|
||||
using a binary built with those features enabled."""
|
||||
|
||||
sys.stderr.write(message)
|
||||
sys.exit(1)
|
||||
else:
|
||||
gtest_test_utils.Main()
|
||||
|
||||
+331
-331
@@ -1,331 +1,331 @@
|
||||
#!/usr/bin/env python
|
||||
#
|
||||
# Copyright 2009 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.
|
||||
|
||||
"""Verifies that test shuffling works."""
|
||||
|
||||
__author__ = 'wan@google.com (Zhanyong Wan)'
|
||||
|
||||
import os
|
||||
import gtest_test_utils
|
||||
|
||||
# Command to run the gtest_shuffle_test_ program.
|
||||
COMMAND = gtest_test_utils.GetTestExecutablePath('gtest_shuffle_test_')
|
||||
|
||||
# The environment variables for test sharding.
|
||||
TOTAL_SHARDS_ENV_VAR = 'GTEST_TOTAL_SHARDS'
|
||||
SHARD_INDEX_ENV_VAR = 'GTEST_SHARD_INDEX'
|
||||
|
||||
TEST_FILTER = 'A*.A:A*.B:C*'
|
||||
|
||||
ALL_TESTS = []
|
||||
ACTIVE_TESTS = []
|
||||
FILTERED_TESTS = []
|
||||
SHARDED_TESTS = []
|
||||
|
||||
SHUFFLED_ALL_TESTS = []
|
||||
SHUFFLED_ACTIVE_TESTS = []
|
||||
SHUFFLED_FILTERED_TESTS = []
|
||||
SHUFFLED_SHARDED_TESTS = []
|
||||
|
||||
|
||||
def AlsoRunDisabledTestsFlag():
|
||||
return '--gtest_also_run_disabled_tests'
|
||||
|
||||
|
||||
def FilterFlag(test_filter):
|
||||
return '--gtest_filter=%s' % (test_filter,)
|
||||
|
||||
|
||||
def RepeatFlag(n):
|
||||
return '--gtest_repeat=%s' % (n,)
|
||||
|
||||
|
||||
def ShuffleFlag():
|
||||
return '--gtest_shuffle'
|
||||
|
||||
|
||||
def RandomSeedFlag(n):
|
||||
return '--gtest_random_seed=%s' % (n,)
|
||||
|
||||
|
||||
def RunAndReturnOutput(extra_env, args):
|
||||
"""Runs the test program and returns its output."""
|
||||
|
||||
try:
|
||||
original_env = os.environ.copy()
|
||||
os.environ.update(extra_env)
|
||||
return gtest_test_utils.Subprocess([COMMAND] + args).output
|
||||
finally:
|
||||
for key in extra_env.iterkeys():
|
||||
if key in original_env:
|
||||
os.environ[key] = original_env[key]
|
||||
else:
|
||||
del os.environ[key]
|
||||
|
||||
|
||||
def GetTestsForAllIterations(extra_env, args):
|
||||
"""Runs the test program and returns a list of test lists.
|
||||
|
||||
Args:
|
||||
extra_env: a map from environment variables to their values
|
||||
args: command line flags to pass to gtest_shuffle_test_
|
||||
|
||||
Returns:
|
||||
A list where the i-th element is the list of tests run in the i-th
|
||||
test iteration.
|
||||
"""
|
||||
|
||||
test_iterations = []
|
||||
for line in RunAndReturnOutput(extra_env, args).split('\n'):
|
||||
if line.startswith('----'):
|
||||
tests = []
|
||||
test_iterations.append(tests)
|
||||
elif line.strip():
|
||||
tests.append(line.strip()) # 'TestCaseName.TestName'
|
||||
|
||||
return test_iterations
|
||||
|
||||
|
||||
def GetTestCases(tests):
|
||||
"""Returns a list of test cases in the given full test names.
|
||||
|
||||
Args:
|
||||
tests: a list of full test names
|
||||
|
||||
Returns:
|
||||
A list of test cases from 'tests', in their original order.
|
||||
Consecutive duplicates are removed.
|
||||
"""
|
||||
|
||||
test_cases = []
|
||||
for test in tests:
|
||||
test_case = test.split('.')[0]
|
||||
if not test_case in test_cases:
|
||||
test_cases.append(test_case)
|
||||
|
||||
return test_cases
|
||||
|
||||
|
||||
def CalculateTestLists():
|
||||
"""Calculates the list of tests run under different flags."""
|
||||
|
||||
if not ALL_TESTS:
|
||||
ALL_TESTS.extend(
|
||||
GetTestsForAllIterations({}, [AlsoRunDisabledTestsFlag()])[0])
|
||||
|
||||
if not ACTIVE_TESTS:
|
||||
ACTIVE_TESTS.extend(GetTestsForAllIterations({}, [])[0])
|
||||
|
||||
if not FILTERED_TESTS:
|
||||
FILTERED_TESTS.extend(
|
||||
GetTestsForAllIterations({}, [FilterFlag(TEST_FILTER)])[0])
|
||||
|
||||
if not SHARDED_TESTS:
|
||||
SHARDED_TESTS.extend(
|
||||
GetTestsForAllIterations({TOTAL_SHARDS_ENV_VAR: '3',
|
||||
SHARD_INDEX_ENV_VAR: '1'},
|
||||
[])[0])
|
||||
|
||||
if not SHUFFLED_ALL_TESTS:
|
||||
SHUFFLED_ALL_TESTS.extend(GetTestsForAllIterations(
|
||||
{}, [AlsoRunDisabledTestsFlag(), ShuffleFlag(), RandomSeedFlag(1)])[0])
|
||||
|
||||
if not SHUFFLED_ACTIVE_TESTS:
|
||||
SHUFFLED_ACTIVE_TESTS.extend(GetTestsForAllIterations(
|
||||
{}, [ShuffleFlag(), RandomSeedFlag(1)])[0])
|
||||
|
||||
if not SHUFFLED_FILTERED_TESTS:
|
||||
SHUFFLED_FILTERED_TESTS.extend(GetTestsForAllIterations(
|
||||
{}, [ShuffleFlag(), RandomSeedFlag(1), FilterFlag(TEST_FILTER)])[0])
|
||||
|
||||
if not SHUFFLED_SHARDED_TESTS:
|
||||
SHUFFLED_SHARDED_TESTS.extend(
|
||||
GetTestsForAllIterations({TOTAL_SHARDS_ENV_VAR: '3',
|
||||
SHARD_INDEX_ENV_VAR: '1'},
|
||||
[ShuffleFlag(), RandomSeedFlag(1)])[0])
|
||||
|
||||
|
||||
class GTestShuffleUnitTest(gtest_test_utils.TestCase):
|
||||
"""Tests test shuffling."""
|
||||
|
||||
def setUp(self):
|
||||
CalculateTestLists()
|
||||
|
||||
def testShufflePreservesNumberOfTests(self):
|
||||
self.assertEqual(len(ALL_TESTS), len(SHUFFLED_ALL_TESTS))
|
||||
self.assertEqual(len(ACTIVE_TESTS), len(SHUFFLED_ACTIVE_TESTS))
|
||||
self.assertEqual(len(FILTERED_TESTS), len(SHUFFLED_FILTERED_TESTS))
|
||||
self.assertEqual(len(SHARDED_TESTS), len(SHUFFLED_SHARDED_TESTS))
|
||||
|
||||
def testShuffleChangesTestOrder(self):
|
||||
self.assert_(SHUFFLED_ALL_TESTS != ALL_TESTS, SHUFFLED_ALL_TESTS)
|
||||
self.assert_(SHUFFLED_ACTIVE_TESTS != ACTIVE_TESTS, SHUFFLED_ACTIVE_TESTS)
|
||||
self.assert_(SHUFFLED_FILTERED_TESTS != FILTERED_TESTS,
|
||||
SHUFFLED_FILTERED_TESTS)
|
||||
self.assert_(SHUFFLED_SHARDED_TESTS != SHARDED_TESTS,
|
||||
SHUFFLED_SHARDED_TESTS)
|
||||
|
||||
def testShuffleChangesTestCaseOrder(self):
|
||||
self.assert_(GetTestCases(SHUFFLED_ALL_TESTS) != GetTestCases(ALL_TESTS),
|
||||
GetTestCases(SHUFFLED_ALL_TESTS))
|
||||
self.assert_(
|
||||
GetTestCases(SHUFFLED_ACTIVE_TESTS) != GetTestCases(ACTIVE_TESTS),
|
||||
GetTestCases(SHUFFLED_ACTIVE_TESTS))
|
||||
self.assert_(
|
||||
GetTestCases(SHUFFLED_FILTERED_TESTS) != GetTestCases(FILTERED_TESTS),
|
||||
GetTestCases(SHUFFLED_FILTERED_TESTS))
|
||||
self.assert_(
|
||||
GetTestCases(SHUFFLED_SHARDED_TESTS) != GetTestCases(SHARDED_TESTS),
|
||||
GetTestCases(SHUFFLED_SHARDED_TESTS))
|
||||
|
||||
def testShuffleDoesNotRepeatTest(self):
|
||||
for test in SHUFFLED_ALL_TESTS:
|
||||
self.assertEqual(1, SHUFFLED_ALL_TESTS.count(test),
|
||||
'%s appears more than once' % (test,))
|
||||
for test in SHUFFLED_ACTIVE_TESTS:
|
||||
self.assertEqual(1, SHUFFLED_ACTIVE_TESTS.count(test),
|
||||
'%s appears more than once' % (test,))
|
||||
for test in SHUFFLED_FILTERED_TESTS:
|
||||
self.assertEqual(1, SHUFFLED_FILTERED_TESTS.count(test),
|
||||
'%s appears more than once' % (test,))
|
||||
for test in SHUFFLED_SHARDED_TESTS:
|
||||
self.assertEqual(1, SHUFFLED_SHARDED_TESTS.count(test),
|
||||
'%s appears more than once' % (test,))
|
||||
|
||||
def testShuffleDoesNotCreateNewTest(self):
|
||||
for test in SHUFFLED_ALL_TESTS:
|
||||
self.assert_(test in ALL_TESTS, '%s is an invalid test' % (test,))
|
||||
for test in SHUFFLED_ACTIVE_TESTS:
|
||||
self.assert_(test in ACTIVE_TESTS, '%s is an invalid test' % (test,))
|
||||
for test in SHUFFLED_FILTERED_TESTS:
|
||||
self.assert_(test in FILTERED_TESTS, '%s is an invalid test' % (test,))
|
||||
for test in SHUFFLED_SHARDED_TESTS:
|
||||
self.assert_(test in SHARDED_TESTS, '%s is an invalid test' % (test,))
|
||||
|
||||
def testShuffleIncludesAllTests(self):
|
||||
for test in ALL_TESTS:
|
||||
self.assert_(test in SHUFFLED_ALL_TESTS, '%s is missing' % (test,))
|
||||
for test in ACTIVE_TESTS:
|
||||
self.assert_(test in SHUFFLED_ACTIVE_TESTS, '%s is missing' % (test,))
|
||||
for test in FILTERED_TESTS:
|
||||
self.assert_(test in SHUFFLED_FILTERED_TESTS, '%s is missing' % (test,))
|
||||
for test in SHARDED_TESTS:
|
||||
self.assert_(test in SHUFFLED_SHARDED_TESTS, '%s is missing' % (test,))
|
||||
|
||||
def testShuffleLeavesDeathTestsAtFront(self):
|
||||
non_death_test_found = False
|
||||
for test in SHUFFLED_ACTIVE_TESTS:
|
||||
if 'DeathTest.' in test:
|
||||
self.assert_(not non_death_test_found,
|
||||
'%s appears after a non-death test' % (test,))
|
||||
else:
|
||||
non_death_test_found = True
|
||||
|
||||
def _VerifyTestCasesDoNotInterleave(self, tests):
|
||||
test_cases = []
|
||||
for test in tests:
|
||||
[test_case, _] = test.split('.')
|
||||
if test_cases and test_cases[-1] != test_case:
|
||||
test_cases.append(test_case)
|
||||
self.assertEqual(1, test_cases.count(test_case),
|
||||
'Test case %s is not grouped together in %s' %
|
||||
(test_case, tests))
|
||||
|
||||
def testShuffleDoesNotInterleaveTestCases(self):
|
||||
self._VerifyTestCasesDoNotInterleave(SHUFFLED_ALL_TESTS)
|
||||
self._VerifyTestCasesDoNotInterleave(SHUFFLED_ACTIVE_TESTS)
|
||||
self._VerifyTestCasesDoNotInterleave(SHUFFLED_FILTERED_TESTS)
|
||||
self._VerifyTestCasesDoNotInterleave(SHUFFLED_SHARDED_TESTS)
|
||||
|
||||
def testShuffleRestoresOrderAfterEachIteration(self):
|
||||
# Get the test lists in all 3 iterations, using random seed 1, 2,
|
||||
# and 3 respectively. Google Test picks a different seed in each
|
||||
# iteration, and this test depends on the current implementation
|
||||
# picking successive numbers. This dependency is not ideal, but
|
||||
# makes the test much easier to write.
|
||||
[tests_in_iteration1, tests_in_iteration2, tests_in_iteration3] = (
|
||||
GetTestsForAllIterations(
|
||||
{}, [ShuffleFlag(), RandomSeedFlag(1), RepeatFlag(3)]))
|
||||
|
||||
# Make sure running the tests with random seed 1 gets the same
|
||||
# order as in iteration 1 above.
|
||||
[tests_with_seed1] = GetTestsForAllIterations(
|
||||
{}, [ShuffleFlag(), RandomSeedFlag(1)])
|
||||
self.assertEqual(tests_in_iteration1, tests_with_seed1)
|
||||
|
||||
# Make sure running the tests with random seed 2 gets the same
|
||||
# order as in iteration 2 above. Success means that Google Test
|
||||
# correctly restores the test order before re-shuffling at the
|
||||
# beginning of iteration 2.
|
||||
[tests_with_seed2] = GetTestsForAllIterations(
|
||||
{}, [ShuffleFlag(), RandomSeedFlag(2)])
|
||||
self.assertEqual(tests_in_iteration2, tests_with_seed2)
|
||||
|
||||
# Make sure running the tests with random seed 3 gets the same
|
||||
# order as in iteration 3 above. Success means that Google Test
|
||||
# correctly restores the test order before re-shuffling at the
|
||||
# beginning of iteration 3.
|
||||
[tests_with_seed3] = GetTestsForAllIterations(
|
||||
{}, [ShuffleFlag(), RandomSeedFlag(3)])
|
||||
self.assertEqual(tests_in_iteration3, tests_with_seed3)
|
||||
|
||||
def testShuffleGeneratesNewOrderInEachIteration(self):
|
||||
[tests_in_iteration1, tests_in_iteration2, tests_in_iteration3] = (
|
||||
GetTestsForAllIterations(
|
||||
{}, [ShuffleFlag(), RandomSeedFlag(1), RepeatFlag(3)]))
|
||||
|
||||
self.assert_(tests_in_iteration1 != tests_in_iteration2,
|
||||
tests_in_iteration1)
|
||||
self.assert_(tests_in_iteration1 != tests_in_iteration3,
|
||||
tests_in_iteration1)
|
||||
self.assert_(tests_in_iteration2 != tests_in_iteration3,
|
||||
tests_in_iteration2)
|
||||
|
||||
def testShuffleShardedTestsPreservesPartition(self):
|
||||
# If we run M tests on N shards, the same M tests should be run in
|
||||
# total, regardless of the random seeds used by the shards.
|
||||
[tests1] = GetTestsForAllIterations({TOTAL_SHARDS_ENV_VAR: '3',
|
||||
SHARD_INDEX_ENV_VAR: '0'},
|
||||
[ShuffleFlag(), RandomSeedFlag(1)])
|
||||
[tests2] = GetTestsForAllIterations({TOTAL_SHARDS_ENV_VAR: '3',
|
||||
SHARD_INDEX_ENV_VAR: '1'},
|
||||
[ShuffleFlag(), RandomSeedFlag(20)])
|
||||
[tests3] = GetTestsForAllIterations({TOTAL_SHARDS_ENV_VAR: '3',
|
||||
SHARD_INDEX_ENV_VAR: '2'},
|
||||
[ShuffleFlag(), RandomSeedFlag(25)])
|
||||
sorted_sharded_tests = tests1 + tests2 + tests3
|
||||
sorted_sharded_tests.sort()
|
||||
sorted_active_tests = []
|
||||
sorted_active_tests.extend(ACTIVE_TESTS)
|
||||
sorted_active_tests.sort()
|
||||
self.assertEqual(sorted_active_tests, sorted_sharded_tests)
|
||||
|
||||
if __name__ == '__main__':
|
||||
gtest_test_utils.Main()
|
||||
#!/usr/bin/env python
|
||||
#
|
||||
# Copyright 2009 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.
|
||||
|
||||
"""Verifies that test shuffling works."""
|
||||
|
||||
__author__ = 'wan@google.com (Zhanyong Wan)'
|
||||
|
||||
import os
|
||||
import gtest_test_utils
|
||||
|
||||
# Command to run the gtest_shuffle_test_ program.
|
||||
COMMAND = gtest_test_utils.GetTestExecutablePath('gtest_shuffle_test_')
|
||||
|
||||
# The environment variables for test sharding.
|
||||
TOTAL_SHARDS_ENV_VAR = 'GTEST_TOTAL_SHARDS'
|
||||
SHARD_INDEX_ENV_VAR = 'GTEST_SHARD_INDEX'
|
||||
|
||||
TEST_FILTER = 'A*.A:A*.B:C*'
|
||||
|
||||
ALL_TESTS = []
|
||||
ACTIVE_TESTS = []
|
||||
FILTERED_TESTS = []
|
||||
SHARDED_TESTS = []
|
||||
|
||||
SHUFFLED_ALL_TESTS = []
|
||||
SHUFFLED_ACTIVE_TESTS = []
|
||||
SHUFFLED_FILTERED_TESTS = []
|
||||
SHUFFLED_SHARDED_TESTS = []
|
||||
|
||||
|
||||
def AlsoRunDisabledTestsFlag():
|
||||
return '--gtest_also_run_disabled_tests'
|
||||
|
||||
|
||||
def FilterFlag(test_filter):
|
||||
return '--gtest_filter=%s' % (test_filter,)
|
||||
|
||||
|
||||
def RepeatFlag(n):
|
||||
return '--gtest_repeat=%s' % (n,)
|
||||
|
||||
|
||||
def ShuffleFlag():
|
||||
return '--gtest_shuffle'
|
||||
|
||||
|
||||
def RandomSeedFlag(n):
|
||||
return '--gtest_random_seed=%s' % (n,)
|
||||
|
||||
|
||||
def RunAndReturnOutput(extra_env, args):
|
||||
"""Runs the test program and returns its output."""
|
||||
|
||||
try:
|
||||
original_env = os.environ.copy()
|
||||
os.environ.update(extra_env)
|
||||
return gtest_test_utils.Subprocess([COMMAND] + args).output
|
||||
finally:
|
||||
for key in extra_env.iterkeys():
|
||||
if key in original_env:
|
||||
os.environ[key] = original_env[key]
|
||||
else:
|
||||
del os.environ[key]
|
||||
|
||||
|
||||
def GetTestsForAllIterations(extra_env, args):
|
||||
"""Runs the test program and returns a list of test lists.
|
||||
|
||||
Args:
|
||||
extra_env: a map from environment variables to their values
|
||||
args: command line flags to pass to gtest_shuffle_test_
|
||||
|
||||
Returns:
|
||||
A list where the i-th element is the list of tests run in the i-th
|
||||
test iteration.
|
||||
"""
|
||||
|
||||
test_iterations = []
|
||||
for line in RunAndReturnOutput(extra_env, args).split('\n'):
|
||||
if line.startswith('----'):
|
||||
tests = []
|
||||
test_iterations.append(tests)
|
||||
elif line.strip():
|
||||
tests.append(line.strip()) # 'TestCaseName.TestName'
|
||||
|
||||
return test_iterations
|
||||
|
||||
|
||||
def GetTestCases(tests):
|
||||
"""Returns a list of test cases in the given full test names.
|
||||
|
||||
Args:
|
||||
tests: a list of full test names
|
||||
|
||||
Returns:
|
||||
A list of test cases from 'tests', in their original order.
|
||||
Consecutive duplicates are removed.
|
||||
"""
|
||||
|
||||
test_cases = []
|
||||
for test in tests:
|
||||
test_case = test.split('.')[0]
|
||||
if not test_case in test_cases:
|
||||
test_cases.append(test_case)
|
||||
|
||||
return test_cases
|
||||
|
||||
|
||||
def CalculateTestLists():
|
||||
"""Calculates the list of tests run under different flags."""
|
||||
|
||||
if not ALL_TESTS:
|
||||
ALL_TESTS.extend(
|
||||
GetTestsForAllIterations({}, [AlsoRunDisabledTestsFlag()])[0])
|
||||
|
||||
if not ACTIVE_TESTS:
|
||||
ACTIVE_TESTS.extend(GetTestsForAllIterations({}, [])[0])
|
||||
|
||||
if not FILTERED_TESTS:
|
||||
FILTERED_TESTS.extend(
|
||||
GetTestsForAllIterations({}, [FilterFlag(TEST_FILTER)])[0])
|
||||
|
||||
if not SHARDED_TESTS:
|
||||
SHARDED_TESTS.extend(
|
||||
GetTestsForAllIterations({TOTAL_SHARDS_ENV_VAR: '3',
|
||||
SHARD_INDEX_ENV_VAR: '1'},
|
||||
[])[0])
|
||||
|
||||
if not SHUFFLED_ALL_TESTS:
|
||||
SHUFFLED_ALL_TESTS.extend(GetTestsForAllIterations(
|
||||
{}, [AlsoRunDisabledTestsFlag(), ShuffleFlag(), RandomSeedFlag(1)])[0])
|
||||
|
||||
if not SHUFFLED_ACTIVE_TESTS:
|
||||
SHUFFLED_ACTIVE_TESTS.extend(GetTestsForAllIterations(
|
||||
{}, [ShuffleFlag(), RandomSeedFlag(1)])[0])
|
||||
|
||||
if not SHUFFLED_FILTERED_TESTS:
|
||||
SHUFFLED_FILTERED_TESTS.extend(GetTestsForAllIterations(
|
||||
{}, [ShuffleFlag(), RandomSeedFlag(1), FilterFlag(TEST_FILTER)])[0])
|
||||
|
||||
if not SHUFFLED_SHARDED_TESTS:
|
||||
SHUFFLED_SHARDED_TESTS.extend(
|
||||
GetTestsForAllIterations({TOTAL_SHARDS_ENV_VAR: '3',
|
||||
SHARD_INDEX_ENV_VAR: '1'},
|
||||
[ShuffleFlag(), RandomSeedFlag(1)])[0])
|
||||
|
||||
|
||||
class GTestShuffleUnitTest(gtest_test_utils.TestCase):
|
||||
"""Tests test shuffling."""
|
||||
|
||||
def setUp(self):
|
||||
CalculateTestLists()
|
||||
|
||||
def testShufflePreservesNumberOfTests(self):
|
||||
self.assertEqual(len(ALL_TESTS), len(SHUFFLED_ALL_TESTS))
|
||||
self.assertEqual(len(ACTIVE_TESTS), len(SHUFFLED_ACTIVE_TESTS))
|
||||
self.assertEqual(len(FILTERED_TESTS), len(SHUFFLED_FILTERED_TESTS))
|
||||
self.assertEqual(len(SHARDED_TESTS), len(SHUFFLED_SHARDED_TESTS))
|
||||
|
||||
def testShuffleChangesTestOrder(self):
|
||||
self.assert_(SHUFFLED_ALL_TESTS != ALL_TESTS, SHUFFLED_ALL_TESTS)
|
||||
self.assert_(SHUFFLED_ACTIVE_TESTS != ACTIVE_TESTS, SHUFFLED_ACTIVE_TESTS)
|
||||
self.assert_(SHUFFLED_FILTERED_TESTS != FILTERED_TESTS,
|
||||
SHUFFLED_FILTERED_TESTS)
|
||||
self.assert_(SHUFFLED_SHARDED_TESTS != SHARDED_TESTS,
|
||||
SHUFFLED_SHARDED_TESTS)
|
||||
|
||||
def testShuffleChangesTestCaseOrder(self):
|
||||
self.assert_(GetTestCases(SHUFFLED_ALL_TESTS) != GetTestCases(ALL_TESTS),
|
||||
GetTestCases(SHUFFLED_ALL_TESTS))
|
||||
self.assert_(
|
||||
GetTestCases(SHUFFLED_ACTIVE_TESTS) != GetTestCases(ACTIVE_TESTS),
|
||||
GetTestCases(SHUFFLED_ACTIVE_TESTS))
|
||||
self.assert_(
|
||||
GetTestCases(SHUFFLED_FILTERED_TESTS) != GetTestCases(FILTERED_TESTS),
|
||||
GetTestCases(SHUFFLED_FILTERED_TESTS))
|
||||
self.assert_(
|
||||
GetTestCases(SHUFFLED_SHARDED_TESTS) != GetTestCases(SHARDED_TESTS),
|
||||
GetTestCases(SHUFFLED_SHARDED_TESTS))
|
||||
|
||||
def testShuffleDoesNotRepeatTest(self):
|
||||
for test in SHUFFLED_ALL_TESTS:
|
||||
self.assertEqual(1, SHUFFLED_ALL_TESTS.count(test),
|
||||
'%s appears more than once' % (test,))
|
||||
for test in SHUFFLED_ACTIVE_TESTS:
|
||||
self.assertEqual(1, SHUFFLED_ACTIVE_TESTS.count(test),
|
||||
'%s appears more than once' % (test,))
|
||||
for test in SHUFFLED_FILTERED_TESTS:
|
||||
self.assertEqual(1, SHUFFLED_FILTERED_TESTS.count(test),
|
||||
'%s appears more than once' % (test,))
|
||||
for test in SHUFFLED_SHARDED_TESTS:
|
||||
self.assertEqual(1, SHUFFLED_SHARDED_TESTS.count(test),
|
||||
'%s appears more than once' % (test,))
|
||||
|
||||
def testShuffleDoesNotCreateNewTest(self):
|
||||
for test in SHUFFLED_ALL_TESTS:
|
||||
self.assert_(test in ALL_TESTS, '%s is an invalid test' % (test,))
|
||||
for test in SHUFFLED_ACTIVE_TESTS:
|
||||
self.assert_(test in ACTIVE_TESTS, '%s is an invalid test' % (test,))
|
||||
for test in SHUFFLED_FILTERED_TESTS:
|
||||
self.assert_(test in FILTERED_TESTS, '%s is an invalid test' % (test,))
|
||||
for test in SHUFFLED_SHARDED_TESTS:
|
||||
self.assert_(test in SHARDED_TESTS, '%s is an invalid test' % (test,))
|
||||
|
||||
def testShuffleIncludesAllTests(self):
|
||||
for test in ALL_TESTS:
|
||||
self.assert_(test in SHUFFLED_ALL_TESTS, '%s is missing' % (test,))
|
||||
for test in ACTIVE_TESTS:
|
||||
self.assert_(test in SHUFFLED_ACTIVE_TESTS, '%s is missing' % (test,))
|
||||
for test in FILTERED_TESTS:
|
||||
self.assert_(test in SHUFFLED_FILTERED_TESTS, '%s is missing' % (test,))
|
||||
for test in SHARDED_TESTS:
|
||||
self.assert_(test in SHUFFLED_SHARDED_TESTS, '%s is missing' % (test,))
|
||||
|
||||
def testShuffleLeavesDeathTestsAtFront(self):
|
||||
non_death_test_found = False
|
||||
for test in SHUFFLED_ACTIVE_TESTS:
|
||||
if 'DeathTest.' in test:
|
||||
self.assert_(not non_death_test_found,
|
||||
'%s appears after a non-death test' % (test,))
|
||||
else:
|
||||
non_death_test_found = True
|
||||
|
||||
def _VerifyTestCasesDoNotInterleave(self, tests):
|
||||
test_cases = []
|
||||
for test in tests:
|
||||
[test_case, _] = test.split('.')
|
||||
if test_cases and test_cases[-1] != test_case:
|
||||
test_cases.append(test_case)
|
||||
self.assertEqual(1, test_cases.count(test_case),
|
||||
'Test case %s is not grouped together in %s' %
|
||||
(test_case, tests))
|
||||
|
||||
def testShuffleDoesNotInterleaveTestCases(self):
|
||||
self._VerifyTestCasesDoNotInterleave(SHUFFLED_ALL_TESTS)
|
||||
self._VerifyTestCasesDoNotInterleave(SHUFFLED_ACTIVE_TESTS)
|
||||
self._VerifyTestCasesDoNotInterleave(SHUFFLED_FILTERED_TESTS)
|
||||
self._VerifyTestCasesDoNotInterleave(SHUFFLED_SHARDED_TESTS)
|
||||
|
||||
def testShuffleRestoresOrderAfterEachIteration(self):
|
||||
# Get the test lists in all 3 iterations, using random seed 1, 2,
|
||||
# and 3 respectively. Google Test picks a different seed in each
|
||||
# iteration, and this test depends on the current implementation
|
||||
# picking successive numbers. This dependency is not ideal, but
|
||||
# makes the test much easier to write.
|
||||
[tests_in_iteration1, tests_in_iteration2, tests_in_iteration3] = (
|
||||
GetTestsForAllIterations(
|
||||
{}, [ShuffleFlag(), RandomSeedFlag(1), RepeatFlag(3)]))
|
||||
|
||||
# Make sure running the tests with random seed 1 gets the same
|
||||
# order as in iteration 1 above.
|
||||
[tests_with_seed1] = GetTestsForAllIterations(
|
||||
{}, [ShuffleFlag(), RandomSeedFlag(1)])
|
||||
self.assertEqual(tests_in_iteration1, tests_with_seed1)
|
||||
|
||||
# Make sure running the tests with random seed 2 gets the same
|
||||
# order as in iteration 2 above. Success means that Google Test
|
||||
# correctly restores the test order before re-shuffling at the
|
||||
# beginning of iteration 2.
|
||||
[tests_with_seed2] = GetTestsForAllIterations(
|
||||
{}, [ShuffleFlag(), RandomSeedFlag(2)])
|
||||
self.assertEqual(tests_in_iteration2, tests_with_seed2)
|
||||
|
||||
# Make sure running the tests with random seed 3 gets the same
|
||||
# order as in iteration 3 above. Success means that Google Test
|
||||
# correctly restores the test order before re-shuffling at the
|
||||
# beginning of iteration 3.
|
||||
[tests_with_seed3] = GetTestsForAllIterations(
|
||||
{}, [ShuffleFlag(), RandomSeedFlag(3)])
|
||||
self.assertEqual(tests_in_iteration3, tests_with_seed3)
|
||||
|
||||
def testShuffleGeneratesNewOrderInEachIteration(self):
|
||||
[tests_in_iteration1, tests_in_iteration2, tests_in_iteration3] = (
|
||||
GetTestsForAllIterations(
|
||||
{}, [ShuffleFlag(), RandomSeedFlag(1), RepeatFlag(3)]))
|
||||
|
||||
self.assert_(tests_in_iteration1 != tests_in_iteration2,
|
||||
tests_in_iteration1)
|
||||
self.assert_(tests_in_iteration1 != tests_in_iteration3,
|
||||
tests_in_iteration1)
|
||||
self.assert_(tests_in_iteration2 != tests_in_iteration3,
|
||||
tests_in_iteration2)
|
||||
|
||||
def testShuffleShardedTestsPreservesPartition(self):
|
||||
# If we run M tests on N shards, the same M tests should be run in
|
||||
# total, regardless of the random seeds used by the shards.
|
||||
[tests1] = GetTestsForAllIterations({TOTAL_SHARDS_ENV_VAR: '3',
|
||||
SHARD_INDEX_ENV_VAR: '0'},
|
||||
[ShuffleFlag(), RandomSeedFlag(1)])
|
||||
[tests2] = GetTestsForAllIterations({TOTAL_SHARDS_ENV_VAR: '3',
|
||||
SHARD_INDEX_ENV_VAR: '1'},
|
||||
[ShuffleFlag(), RandomSeedFlag(20)])
|
||||
[tests3] = GetTestsForAllIterations({TOTAL_SHARDS_ENV_VAR: '3',
|
||||
SHARD_INDEX_ENV_VAR: '2'},
|
||||
[ShuffleFlag(), RandomSeedFlag(25)])
|
||||
sorted_sharded_tests = tests1 + tests2 + tests3
|
||||
sorted_sharded_tests.sort()
|
||||
sorted_active_tests = []
|
||||
sorted_active_tests.extend(ACTIVE_TESTS)
|
||||
sorted_active_tests.sort()
|
||||
self.assertEqual(sorted_active_tests, sorted_sharded_tests)
|
||||
|
||||
if __name__ == '__main__':
|
||||
gtest_test_utils.Main()
|
||||
|
||||
+270
-270
@@ -1,270 +1,270 @@
|
||||
#!/usr/bin/env python
|
||||
#
|
||||
# Copyright 2006, 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.
|
||||
|
||||
"""Unit test utilities for Google C++ Testing Framework."""
|
||||
|
||||
__author__ = 'wan@google.com (Zhanyong Wan)'
|
||||
|
||||
import atexit
|
||||
import os
|
||||
import shutil
|
||||
import sys
|
||||
import tempfile
|
||||
import unittest
|
||||
_test_module = unittest
|
||||
|
||||
# Suppresses the 'Import not at the top of the file' lint complaint.
|
||||
# pylint: disable-msg=C6204
|
||||
try:
|
||||
import subprocess
|
||||
_SUBPROCESS_MODULE_AVAILABLE = True
|
||||
except:
|
||||
import popen2
|
||||
_SUBPROCESS_MODULE_AVAILABLE = False
|
||||
# pylint: enable-msg=C6204
|
||||
|
||||
|
||||
IS_WINDOWS = os.name == 'nt'
|
||||
IS_CYGWIN = os.name == 'posix' and 'CYGWIN' in os.uname()[0]
|
||||
|
||||
# Here we expose a class from a particular module, depending on the
|
||||
# environment. The comment suppresses the 'Invalid variable name' lint
|
||||
# complaint.
|
||||
TestCase = _test_module.TestCase # pylint: disable-msg=C6409
|
||||
|
||||
# Initially maps a flag to its default value. After
|
||||
# _ParseAndStripGTestFlags() is called, maps a flag to its actual value.
|
||||
_flag_map = {'gtest_source_dir': os.path.dirname(sys.argv[0]),
|
||||
'gtest_build_dir': os.path.dirname(sys.argv[0])}
|
||||
_gtest_flags_are_parsed = False
|
||||
|
||||
|
||||
def _ParseAndStripGTestFlags(argv):
|
||||
"""Parses and strips Google Test flags from argv. This is idempotent."""
|
||||
|
||||
# Suppresses the lint complaint about a global variable since we need it
|
||||
# here to maintain module-wide state.
|
||||
global _gtest_flags_are_parsed # pylint: disable-msg=W0603
|
||||
if _gtest_flags_are_parsed:
|
||||
return
|
||||
|
||||
_gtest_flags_are_parsed = True
|
||||
for flag in _flag_map:
|
||||
# The environment variable overrides the default value.
|
||||
if flag.upper() in os.environ:
|
||||
_flag_map[flag] = os.environ[flag.upper()]
|
||||
|
||||
# The command line flag overrides the environment variable.
|
||||
i = 1 # Skips the program name.
|
||||
while i < len(argv):
|
||||
prefix = '--' + flag + '='
|
||||
if argv[i].startswith(prefix):
|
||||
_flag_map[flag] = argv[i][len(prefix):]
|
||||
del argv[i]
|
||||
break
|
||||
else:
|
||||
# We don't increment i in case we just found a --gtest_* flag
|
||||
# and removed it from argv.
|
||||
i += 1
|
||||
|
||||
|
||||
def GetFlag(flag):
|
||||
"""Returns the value of the given flag."""
|
||||
|
||||
# In case GetFlag() is called before Main(), we always call
|
||||
# _ParseAndStripGTestFlags() here to make sure the --gtest_* flags
|
||||
# are parsed.
|
||||
_ParseAndStripGTestFlags(sys.argv)
|
||||
|
||||
return _flag_map[flag]
|
||||
|
||||
|
||||
def GetSourceDir():
|
||||
"""Returns the absolute path of the directory where the .py files are."""
|
||||
|
||||
return os.path.abspath(GetFlag('gtest_source_dir'))
|
||||
|
||||
|
||||
def GetBuildDir():
|
||||
"""Returns the absolute path of the directory where the test binaries are."""
|
||||
|
||||
return os.path.abspath(GetFlag('gtest_build_dir'))
|
||||
|
||||
|
||||
_temp_dir = None
|
||||
|
||||
def _RemoveTempDir():
|
||||
if _temp_dir:
|
||||
shutil.rmtree(_temp_dir, ignore_errors=True)
|
||||
|
||||
atexit.register(_RemoveTempDir)
|
||||
|
||||
|
||||
def GetTempDir():
|
||||
"""Returns a directory for temporary files."""
|
||||
|
||||
global _temp_dir
|
||||
if not _temp_dir:
|
||||
_temp_dir = tempfile.mkdtemp()
|
||||
return _temp_dir
|
||||
|
||||
|
||||
def GetTestExecutablePath(executable_name):
|
||||
"""Returns the absolute path of the test binary given its name.
|
||||
|
||||
The function will print a message and abort the program if the resulting file
|
||||
doesn't exist.
|
||||
|
||||
Args:
|
||||
executable_name: name of the test binary that the test script runs.
|
||||
|
||||
Returns:
|
||||
The absolute path of the test binary.
|
||||
"""
|
||||
|
||||
path = os.path.abspath(os.path.join(GetBuildDir(), executable_name))
|
||||
if (IS_WINDOWS or IS_CYGWIN) and not path.endswith('.exe'):
|
||||
path += '.exe'
|
||||
|
||||
if not os.path.exists(path):
|
||||
message = (
|
||||
'Unable to find the test binary. Please make sure to provide path\n'
|
||||
'to the binary via the --gtest_build_dir flag or the GTEST_BUILD_DIR\n'
|
||||
'environment variable. For convenient use, invoke this script via\n'
|
||||
'mk_test.py.\n'
|
||||
# TODO(vladl@google.com): change mk_test.py to test.py after renaming
|
||||
# the file.
|
||||
'Please run mk_test.py -h for help.')
|
||||
print >> sys.stderr, message
|
||||
sys.exit(1)
|
||||
|
||||
return path
|
||||
|
||||
|
||||
def GetExitStatus(exit_code):
|
||||
"""Returns the argument to exit(), or -1 if exit() wasn't called.
|
||||
|
||||
Args:
|
||||
exit_code: the result value of os.system(command).
|
||||
"""
|
||||
|
||||
if os.name == 'nt':
|
||||
# On Windows, os.WEXITSTATUS() doesn't work and os.system() returns
|
||||
# the argument to exit() directly.
|
||||
return exit_code
|
||||
else:
|
||||
# On Unix, os.WEXITSTATUS() must be used to extract the exit status
|
||||
# from the result of os.system().
|
||||
if os.WIFEXITED(exit_code):
|
||||
return os.WEXITSTATUS(exit_code)
|
||||
else:
|
||||
return -1
|
||||
|
||||
|
||||
class Subprocess:
|
||||
def __init__(self, command, working_dir=None, capture_stderr=True):
|
||||
"""Changes into a specified directory, if provided, and executes a command.
|
||||
Restores the old directory afterwards. Execution results are returned
|
||||
via the following attributes:
|
||||
terminated_by_sygnal True iff the child process has been terminated
|
||||
by a signal.
|
||||
signal Sygnal that terminated the child process.
|
||||
exited True iff the child process exited normally.
|
||||
exit_code The code with which the child proces exited.
|
||||
output Child process's stdout and stderr output
|
||||
combined in a string.
|
||||
|
||||
Args:
|
||||
command: The command to run, in the form of sys.argv.
|
||||
working_dir: The directory to change into.
|
||||
capture_stderr: Determines whether to capture stderr in the output member
|
||||
or to discard it.
|
||||
"""
|
||||
|
||||
# The subprocess module is the preferrable way of running programs
|
||||
# since it is available and behaves consistently on all platforms,
|
||||
# including Windows. But it is only available starting in python 2.4.
|
||||
# In earlier python versions, we revert to the popen2 module, which is
|
||||
# available in python 2.0 and later but doesn't provide required
|
||||
# functionality (Popen4) under Windows. This allows us to support Mac
|
||||
# OS X 10.4 Tiger, which has python 2.3 installed.
|
||||
if _SUBPROCESS_MODULE_AVAILABLE:
|
||||
if capture_stderr:
|
||||
stderr = subprocess.STDOUT
|
||||
else:
|
||||
stderr = subprocess.PIPE
|
||||
|
||||
p = subprocess.Popen(command,
|
||||
stdout=subprocess.PIPE, stderr=stderr,
|
||||
cwd=working_dir, universal_newlines=True)
|
||||
# communicate returns a tuple with the file obect for the child's
|
||||
# output.
|
||||
self.output = p.communicate()[0]
|
||||
self._return_code = p.returncode
|
||||
else:
|
||||
old_dir = os.getcwd()
|
||||
try:
|
||||
if working_dir is not None:
|
||||
os.chdir(working_dir)
|
||||
if capture_stderr:
|
||||
p = popen2.Popen4(command)
|
||||
else:
|
||||
p = popen2.Popen3(command)
|
||||
p.tochild.close()
|
||||
self.output = p.fromchild.read()
|
||||
ret_code = p.wait()
|
||||
finally:
|
||||
os.chdir(old_dir)
|
||||
# Converts ret_code to match the semantics of
|
||||
# subprocess.Popen.returncode.
|
||||
if os.WIFSIGNALED(ret_code):
|
||||
self._return_code = -os.WTERMSIG(ret_code)
|
||||
else: # os.WIFEXITED(ret_code) should return True here.
|
||||
self._return_code = os.WEXITSTATUS(ret_code)
|
||||
|
||||
if self._return_code < 0:
|
||||
self.terminated_by_signal = True
|
||||
self.exited = False
|
||||
self.signal = -self._return_code
|
||||
else:
|
||||
self.terminated_by_signal = False
|
||||
self.exited = True
|
||||
self.exit_code = self._return_code
|
||||
|
||||
|
||||
def Main():
|
||||
"""Runs the unit test."""
|
||||
|
||||
# We must call _ParseAndStripGTestFlags() before calling
|
||||
# unittest.main(). Otherwise the latter will be confused by the
|
||||
# --gtest_* flags.
|
||||
_ParseAndStripGTestFlags(sys.argv)
|
||||
_test_module.main()
|
||||
#!/usr/bin/env python
|
||||
#
|
||||
# Copyright 2006, 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.
|
||||
|
||||
"""Unit test utilities for Google C++ Testing Framework."""
|
||||
|
||||
__author__ = 'wan@google.com (Zhanyong Wan)'
|
||||
|
||||
import atexit
|
||||
import os
|
||||
import shutil
|
||||
import sys
|
||||
import tempfile
|
||||
import unittest
|
||||
_test_module = unittest
|
||||
|
||||
# Suppresses the 'Import not at the top of the file' lint complaint.
|
||||
# pylint: disable-msg=C6204
|
||||
try:
|
||||
import subprocess
|
||||
_SUBPROCESS_MODULE_AVAILABLE = True
|
||||
except:
|
||||
import popen2
|
||||
_SUBPROCESS_MODULE_AVAILABLE = False
|
||||
# pylint: enable-msg=C6204
|
||||
|
||||
|
||||
IS_WINDOWS = os.name == 'nt'
|
||||
IS_CYGWIN = os.name == 'posix' and 'CYGWIN' in os.uname()[0]
|
||||
|
||||
# Here we expose a class from a particular module, depending on the
|
||||
# environment. The comment suppresses the 'Invalid variable name' lint
|
||||
# complaint.
|
||||
TestCase = _test_module.TestCase # pylint: disable-msg=C6409
|
||||
|
||||
# Initially maps a flag to its default value. After
|
||||
# _ParseAndStripGTestFlags() is called, maps a flag to its actual value.
|
||||
_flag_map = {'gtest_source_dir': os.path.dirname(sys.argv[0]),
|
||||
'gtest_build_dir': os.path.dirname(sys.argv[0])}
|
||||
_gtest_flags_are_parsed = False
|
||||
|
||||
|
||||
def _ParseAndStripGTestFlags(argv):
|
||||
"""Parses and strips Google Test flags from argv. This is idempotent."""
|
||||
|
||||
# Suppresses the lint complaint about a global variable since we need it
|
||||
# here to maintain module-wide state.
|
||||
global _gtest_flags_are_parsed # pylint: disable-msg=W0603
|
||||
if _gtest_flags_are_parsed:
|
||||
return
|
||||
|
||||
_gtest_flags_are_parsed = True
|
||||
for flag in _flag_map:
|
||||
# The environment variable overrides the default value.
|
||||
if flag.upper() in os.environ:
|
||||
_flag_map[flag] = os.environ[flag.upper()]
|
||||
|
||||
# The command line flag overrides the environment variable.
|
||||
i = 1 # Skips the program name.
|
||||
while i < len(argv):
|
||||
prefix = '--' + flag + '='
|
||||
if argv[i].startswith(prefix):
|
||||
_flag_map[flag] = argv[i][len(prefix):]
|
||||
del argv[i]
|
||||
break
|
||||
else:
|
||||
# We don't increment i in case we just found a --gtest_* flag
|
||||
# and removed it from argv.
|
||||
i += 1
|
||||
|
||||
|
||||
def GetFlag(flag):
|
||||
"""Returns the value of the given flag."""
|
||||
|
||||
# In case GetFlag() is called before Main(), we always call
|
||||
# _ParseAndStripGTestFlags() here to make sure the --gtest_* flags
|
||||
# are parsed.
|
||||
_ParseAndStripGTestFlags(sys.argv)
|
||||
|
||||
return _flag_map[flag]
|
||||
|
||||
|
||||
def GetSourceDir():
|
||||
"""Returns the absolute path of the directory where the .py files are."""
|
||||
|
||||
return os.path.abspath(GetFlag('gtest_source_dir'))
|
||||
|
||||
|
||||
def GetBuildDir():
|
||||
"""Returns the absolute path of the directory where the test binaries are."""
|
||||
|
||||
return os.path.abspath(GetFlag('gtest_build_dir'))
|
||||
|
||||
|
||||
_temp_dir = None
|
||||
|
||||
def _RemoveTempDir():
|
||||
if _temp_dir:
|
||||
shutil.rmtree(_temp_dir, ignore_errors=True)
|
||||
|
||||
atexit.register(_RemoveTempDir)
|
||||
|
||||
|
||||
def GetTempDir():
|
||||
"""Returns a directory for temporary files."""
|
||||
|
||||
global _temp_dir
|
||||
if not _temp_dir:
|
||||
_temp_dir = tempfile.mkdtemp()
|
||||
return _temp_dir
|
||||
|
||||
|
||||
def GetTestExecutablePath(executable_name):
|
||||
"""Returns the absolute path of the test binary given its name.
|
||||
|
||||
The function will print a message and abort the program if the resulting file
|
||||
doesn't exist.
|
||||
|
||||
Args:
|
||||
executable_name: name of the test binary that the test script runs.
|
||||
|
||||
Returns:
|
||||
The absolute path of the test binary.
|
||||
"""
|
||||
|
||||
path = os.path.abspath(os.path.join(GetBuildDir(), executable_name))
|
||||
if (IS_WINDOWS or IS_CYGWIN) and not path.endswith('.exe'):
|
||||
path += '.exe'
|
||||
|
||||
if not os.path.exists(path):
|
||||
message = (
|
||||
'Unable to find the test binary. Please make sure to provide path\n'
|
||||
'to the binary via the --gtest_build_dir flag or the GTEST_BUILD_DIR\n'
|
||||
'environment variable. For convenient use, invoke this script via\n'
|
||||
'mk_test.py.\n'
|
||||
# TODO(vladl@google.com): change mk_test.py to test.py after renaming
|
||||
# the file.
|
||||
'Please run mk_test.py -h for help.')
|
||||
print >> sys.stderr, message
|
||||
sys.exit(1)
|
||||
|
||||
return path
|
||||
|
||||
|
||||
def GetExitStatus(exit_code):
|
||||
"""Returns the argument to exit(), or -1 if exit() wasn't called.
|
||||
|
||||
Args:
|
||||
exit_code: the result value of os.system(command).
|
||||
"""
|
||||
|
||||
if os.name == 'nt':
|
||||
# On Windows, os.WEXITSTATUS() doesn't work and os.system() returns
|
||||
# the argument to exit() directly.
|
||||
return exit_code
|
||||
else:
|
||||
# On Unix, os.WEXITSTATUS() must be used to extract the exit status
|
||||
# from the result of os.system().
|
||||
if os.WIFEXITED(exit_code):
|
||||
return os.WEXITSTATUS(exit_code)
|
||||
else:
|
||||
return -1
|
||||
|
||||
|
||||
class Subprocess:
|
||||
def __init__(self, command, working_dir=None, capture_stderr=True):
|
||||
"""Changes into a specified directory, if provided, and executes a command.
|
||||
Restores the old directory afterwards. Execution results are returned
|
||||
via the following attributes:
|
||||
terminated_by_sygnal True iff the child process has been terminated
|
||||
by a signal.
|
||||
signal Sygnal that terminated the child process.
|
||||
exited True iff the child process exited normally.
|
||||
exit_code The code with which the child proces exited.
|
||||
output Child process's stdout and stderr output
|
||||
combined in a string.
|
||||
|
||||
Args:
|
||||
command: The command to run, in the form of sys.argv.
|
||||
working_dir: The directory to change into.
|
||||
capture_stderr: Determines whether to capture stderr in the output member
|
||||
or to discard it.
|
||||
"""
|
||||
|
||||
# The subprocess module is the preferrable way of running programs
|
||||
# since it is available and behaves consistently on all platforms,
|
||||
# including Windows. But it is only available starting in python 2.4.
|
||||
# In earlier python versions, we revert to the popen2 module, which is
|
||||
# available in python 2.0 and later but doesn't provide required
|
||||
# functionality (Popen4) under Windows. This allows us to support Mac
|
||||
# OS X 10.4 Tiger, which has python 2.3 installed.
|
||||
if _SUBPROCESS_MODULE_AVAILABLE:
|
||||
if capture_stderr:
|
||||
stderr = subprocess.STDOUT
|
||||
else:
|
||||
stderr = subprocess.PIPE
|
||||
|
||||
p = subprocess.Popen(command,
|
||||
stdout=subprocess.PIPE, stderr=stderr,
|
||||
cwd=working_dir, universal_newlines=True)
|
||||
# communicate returns a tuple with the file obect for the child's
|
||||
# output.
|
||||
self.output = p.communicate()[0]
|
||||
self._return_code = p.returncode
|
||||
else:
|
||||
old_dir = os.getcwd()
|
||||
try:
|
||||
if working_dir is not None:
|
||||
os.chdir(working_dir)
|
||||
if capture_stderr:
|
||||
p = popen2.Popen4(command)
|
||||
else:
|
||||
p = popen2.Popen3(command)
|
||||
p.tochild.close()
|
||||
self.output = p.fromchild.read()
|
||||
ret_code = p.wait()
|
||||
finally:
|
||||
os.chdir(old_dir)
|
||||
# Converts ret_code to match the semantics of
|
||||
# subprocess.Popen.returncode.
|
||||
if os.WIFSIGNALED(ret_code):
|
||||
self._return_code = -os.WTERMSIG(ret_code)
|
||||
else: # os.WIFEXITED(ret_code) should return True here.
|
||||
self._return_code = os.WEXITSTATUS(ret_code)
|
||||
|
||||
if self._return_code < 0:
|
||||
self.terminated_by_signal = True
|
||||
self.exited = False
|
||||
self.signal = -self._return_code
|
||||
else:
|
||||
self.terminated_by_signal = False
|
||||
self.exited = True
|
||||
self.exit_code = self._return_code
|
||||
|
||||
|
||||
def Main():
|
||||
"""Runs the unit test."""
|
||||
|
||||
# We must call _ParseAndStripGTestFlags() before calling
|
||||
# unittest.main(). Otherwise the latter will be confused by the
|
||||
# --gtest_* flags.
|
||||
_ParseAndStripGTestFlags(sys.argv)
|
||||
_test_module.main()
|
||||
|
||||
+171
-171
@@ -1,171 +1,171 @@
|
||||
#!/usr/bin/env python
|
||||
#
|
||||
# Copyright 2009, 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.
|
||||
|
||||
"""Tests Google Test's throw-on-failure mode with exceptions disabled.
|
||||
|
||||
This script invokes gtest_throw_on_failure_test_ (a program written with
|
||||
Google Test) with different environments and command line flags.
|
||||
"""
|
||||
|
||||
__author__ = 'wan@google.com (Zhanyong Wan)'
|
||||
|
||||
import os
|
||||
import gtest_test_utils
|
||||
|
||||
|
||||
# Constants.
|
||||
|
||||
# The command line flag for enabling/disabling the throw-on-failure mode.
|
||||
THROW_ON_FAILURE = 'gtest_throw_on_failure'
|
||||
|
||||
# Path to the gtest_throw_on_failure_test_ program, compiled with
|
||||
# exceptions disabled.
|
||||
EXE_PATH = gtest_test_utils.GetTestExecutablePath(
|
||||
'gtest_throw_on_failure_test_')
|
||||
|
||||
|
||||
# Utilities.
|
||||
|
||||
|
||||
def SetEnvVar(env_var, value):
|
||||
"""Sets an environment variable to a given value; unsets it when the
|
||||
given value is None.
|
||||
"""
|
||||
|
||||
env_var = env_var.upper()
|
||||
if value is not None:
|
||||
os.environ[env_var] = value
|
||||
elif env_var in os.environ:
|
||||
del os.environ[env_var]
|
||||
|
||||
|
||||
def Run(command):
|
||||
"""Runs a command; returns True/False if its exit code is/isn't 0."""
|
||||
|
||||
print 'Running "%s". . .' % ' '.join(command)
|
||||
p = gtest_test_utils.Subprocess(command)
|
||||
return p.exited and p.exit_code == 0
|
||||
|
||||
|
||||
# The tests. TODO(wan@google.com): refactor the class to share common
|
||||
# logic with code in gtest_break_on_failure_unittest.py.
|
||||
class ThrowOnFailureTest(gtest_test_utils.TestCase):
|
||||
"""Tests the throw-on-failure mode."""
|
||||
|
||||
def RunAndVerify(self, env_var_value, flag_value, should_fail):
|
||||
"""Runs gtest_throw_on_failure_test_ and verifies that it does
|
||||
(or does not) exit with a non-zero code.
|
||||
|
||||
Args:
|
||||
env_var_value: value of the GTEST_BREAK_ON_FAILURE environment
|
||||
variable; None if the variable should be unset.
|
||||
flag_value: value of the --gtest_break_on_failure flag;
|
||||
None if the flag should not be present.
|
||||
should_fail: True iff the program is expected to fail.
|
||||
"""
|
||||
|
||||
SetEnvVar(THROW_ON_FAILURE, env_var_value)
|
||||
|
||||
if env_var_value is None:
|
||||
env_var_value_msg = ' is not set'
|
||||
else:
|
||||
env_var_value_msg = '=' + env_var_value
|
||||
|
||||
if flag_value is None:
|
||||
flag = ''
|
||||
elif flag_value == '0':
|
||||
flag = '--%s=0' % THROW_ON_FAILURE
|
||||
else:
|
||||
flag = '--%s' % THROW_ON_FAILURE
|
||||
|
||||
command = [EXE_PATH]
|
||||
if flag:
|
||||
command.append(flag)
|
||||
|
||||
if should_fail:
|
||||
should_or_not = 'should'
|
||||
else:
|
||||
should_or_not = 'should not'
|
||||
|
||||
failed = not Run(command)
|
||||
|
||||
SetEnvVar(THROW_ON_FAILURE, None)
|
||||
|
||||
msg = ('when %s%s, an assertion failure in "%s" %s cause a non-zero '
|
||||
'exit code.' %
|
||||
(THROW_ON_FAILURE, env_var_value_msg, ' '.join(command),
|
||||
should_or_not))
|
||||
self.assert_(failed == should_fail, msg)
|
||||
|
||||
def testDefaultBehavior(self):
|
||||
"""Tests the behavior of the default mode."""
|
||||
|
||||
self.RunAndVerify(env_var_value=None, flag_value=None, should_fail=False)
|
||||
|
||||
def testThrowOnFailureEnvVar(self):
|
||||
"""Tests using the GTEST_THROW_ON_FAILURE environment variable."""
|
||||
|
||||
self.RunAndVerify(env_var_value='0',
|
||||
flag_value=None,
|
||||
should_fail=False)
|
||||
self.RunAndVerify(env_var_value='1',
|
||||
flag_value=None,
|
||||
should_fail=True)
|
||||
|
||||
def testThrowOnFailureFlag(self):
|
||||
"""Tests using the --gtest_throw_on_failure flag."""
|
||||
|
||||
self.RunAndVerify(env_var_value=None,
|
||||
flag_value='0',
|
||||
should_fail=False)
|
||||
self.RunAndVerify(env_var_value=None,
|
||||
flag_value='1',
|
||||
should_fail=True)
|
||||
|
||||
def testThrowOnFailureFlagOverridesEnvVar(self):
|
||||
"""Tests that --gtest_throw_on_failure overrides GTEST_THROW_ON_FAILURE."""
|
||||
|
||||
self.RunAndVerify(env_var_value='0',
|
||||
flag_value='0',
|
||||
should_fail=False)
|
||||
self.RunAndVerify(env_var_value='0',
|
||||
flag_value='1',
|
||||
should_fail=True)
|
||||
self.RunAndVerify(env_var_value='1',
|
||||
flag_value='0',
|
||||
should_fail=False)
|
||||
self.RunAndVerify(env_var_value='1',
|
||||
flag_value='1',
|
||||
should_fail=True)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
gtest_test_utils.Main()
|
||||
#!/usr/bin/env python
|
||||
#
|
||||
# Copyright 2009, 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.
|
||||
|
||||
"""Tests Google Test's throw-on-failure mode with exceptions disabled.
|
||||
|
||||
This script invokes gtest_throw_on_failure_test_ (a program written with
|
||||
Google Test) with different environments and command line flags.
|
||||
"""
|
||||
|
||||
__author__ = 'wan@google.com (Zhanyong Wan)'
|
||||
|
||||
import os
|
||||
import gtest_test_utils
|
||||
|
||||
|
||||
# Constants.
|
||||
|
||||
# The command line flag for enabling/disabling the throw-on-failure mode.
|
||||
THROW_ON_FAILURE = 'gtest_throw_on_failure'
|
||||
|
||||
# Path to the gtest_throw_on_failure_test_ program, compiled with
|
||||
# exceptions disabled.
|
||||
EXE_PATH = gtest_test_utils.GetTestExecutablePath(
|
||||
'gtest_throw_on_failure_test_')
|
||||
|
||||
|
||||
# Utilities.
|
||||
|
||||
|
||||
def SetEnvVar(env_var, value):
|
||||
"""Sets an environment variable to a given value; unsets it when the
|
||||
given value is None.
|
||||
"""
|
||||
|
||||
env_var = env_var.upper()
|
||||
if value is not None:
|
||||
os.environ[env_var] = value
|
||||
elif env_var in os.environ:
|
||||
del os.environ[env_var]
|
||||
|
||||
|
||||
def Run(command):
|
||||
"""Runs a command; returns True/False if its exit code is/isn't 0."""
|
||||
|
||||
print 'Running "%s". . .' % ' '.join(command)
|
||||
p = gtest_test_utils.Subprocess(command)
|
||||
return p.exited and p.exit_code == 0
|
||||
|
||||
|
||||
# The tests. TODO(wan@google.com): refactor the class to share common
|
||||
# logic with code in gtest_break_on_failure_unittest.py.
|
||||
class ThrowOnFailureTest(gtest_test_utils.TestCase):
|
||||
"""Tests the throw-on-failure mode."""
|
||||
|
||||
def RunAndVerify(self, env_var_value, flag_value, should_fail):
|
||||
"""Runs gtest_throw_on_failure_test_ and verifies that it does
|
||||
(or does not) exit with a non-zero code.
|
||||
|
||||
Args:
|
||||
env_var_value: value of the GTEST_BREAK_ON_FAILURE environment
|
||||
variable; None if the variable should be unset.
|
||||
flag_value: value of the --gtest_break_on_failure flag;
|
||||
None if the flag should not be present.
|
||||
should_fail: True iff the program is expected to fail.
|
||||
"""
|
||||
|
||||
SetEnvVar(THROW_ON_FAILURE, env_var_value)
|
||||
|
||||
if env_var_value is None:
|
||||
env_var_value_msg = ' is not set'
|
||||
else:
|
||||
env_var_value_msg = '=' + env_var_value
|
||||
|
||||
if flag_value is None:
|
||||
flag = ''
|
||||
elif flag_value == '0':
|
||||
flag = '--%s=0' % THROW_ON_FAILURE
|
||||
else:
|
||||
flag = '--%s' % THROW_ON_FAILURE
|
||||
|
||||
command = [EXE_PATH]
|
||||
if flag:
|
||||
command.append(flag)
|
||||
|
||||
if should_fail:
|
||||
should_or_not = 'should'
|
||||
else:
|
||||
should_or_not = 'should not'
|
||||
|
||||
failed = not Run(command)
|
||||
|
||||
SetEnvVar(THROW_ON_FAILURE, None)
|
||||
|
||||
msg = ('when %s%s, an assertion failure in "%s" %s cause a non-zero '
|
||||
'exit code.' %
|
||||
(THROW_ON_FAILURE, env_var_value_msg, ' '.join(command),
|
||||
should_or_not))
|
||||
self.assert_(failed == should_fail, msg)
|
||||
|
||||
def testDefaultBehavior(self):
|
||||
"""Tests the behavior of the default mode."""
|
||||
|
||||
self.RunAndVerify(env_var_value=None, flag_value=None, should_fail=False)
|
||||
|
||||
def testThrowOnFailureEnvVar(self):
|
||||
"""Tests using the GTEST_THROW_ON_FAILURE environment variable."""
|
||||
|
||||
self.RunAndVerify(env_var_value='0',
|
||||
flag_value=None,
|
||||
should_fail=False)
|
||||
self.RunAndVerify(env_var_value='1',
|
||||
flag_value=None,
|
||||
should_fail=True)
|
||||
|
||||
def testThrowOnFailureFlag(self):
|
||||
"""Tests using the --gtest_throw_on_failure flag."""
|
||||
|
||||
self.RunAndVerify(env_var_value=None,
|
||||
flag_value='0',
|
||||
should_fail=False)
|
||||
self.RunAndVerify(env_var_value=None,
|
||||
flag_value='1',
|
||||
should_fail=True)
|
||||
|
||||
def testThrowOnFailureFlagOverridesEnvVar(self):
|
||||
"""Tests that --gtest_throw_on_failure overrides GTEST_THROW_ON_FAILURE."""
|
||||
|
||||
self.RunAndVerify(env_var_value='0',
|
||||
flag_value='0',
|
||||
should_fail=False)
|
||||
self.RunAndVerify(env_var_value='0',
|
||||
flag_value='1',
|
||||
should_fail=True)
|
||||
self.RunAndVerify(env_var_value='1',
|
||||
flag_value='0',
|
||||
should_fail=False)
|
||||
self.RunAndVerify(env_var_value='1',
|
||||
flag_value='1',
|
||||
should_fail=True)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
gtest_test_utils.Main()
|
||||
|
||||
@@ -1,70 +1,70 @@
|
||||
#!/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.
|
||||
|
||||
"""Verifies that Google Test warns the user when not initialized properly."""
|
||||
|
||||
__author__ = 'wan@google.com (Zhanyong Wan)'
|
||||
|
||||
import gtest_test_utils
|
||||
|
||||
|
||||
COMMAND = gtest_test_utils.GetTestExecutablePath('gtest_uninitialized_test_')
|
||||
|
||||
|
||||
def Assert(condition):
|
||||
if not condition:
|
||||
raise AssertionError
|
||||
|
||||
|
||||
def AssertEq(expected, actual):
|
||||
if expected != actual:
|
||||
print 'Expected: %s' % (expected,)
|
||||
print ' Actual: %s' % (actual,)
|
||||
raise AssertionError
|
||||
|
||||
|
||||
def TestExitCodeAndOutput(command):
|
||||
"""Runs the given command and verifies its exit code and output."""
|
||||
|
||||
# Verifies that 'command' exits with code 1.
|
||||
p = gtest_test_utils.Subprocess(command)
|
||||
Assert(p.exited)
|
||||
AssertEq(1, p.exit_code)
|
||||
Assert('InitGoogleTest' in p.output)
|
||||
|
||||
|
||||
class GTestUninitializedTest(gtest_test_utils.TestCase):
|
||||
def testExitCodeAndOutput(self):
|
||||
TestExitCodeAndOutput(COMMAND)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
gtest_test_utils.Main()
|
||||
#!/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.
|
||||
|
||||
"""Verifies that Google Test warns the user when not initialized properly."""
|
||||
|
||||
__author__ = 'wan@google.com (Zhanyong Wan)'
|
||||
|
||||
import gtest_test_utils
|
||||
|
||||
|
||||
COMMAND = gtest_test_utils.GetTestExecutablePath('gtest_uninitialized_test_')
|
||||
|
||||
|
||||
def Assert(condition):
|
||||
if not condition:
|
||||
raise AssertionError
|
||||
|
||||
|
||||
def AssertEq(expected, actual):
|
||||
if expected != actual:
|
||||
print 'Expected: %s' % (expected,)
|
||||
print ' Actual: %s' % (actual,)
|
||||
raise AssertionError
|
||||
|
||||
|
||||
def TestExitCodeAndOutput(command):
|
||||
"""Runs the given command and verifies its exit code and output."""
|
||||
|
||||
# Verifies that 'command' exits with code 1.
|
||||
p = gtest_test_utils.Subprocess(command)
|
||||
Assert(p.exited)
|
||||
AssertEq(1, p.exit_code)
|
||||
Assert('InitGoogleTest' in p.output)
|
||||
|
||||
|
||||
class GTestUninitializedTest(gtest_test_utils.TestCase):
|
||||
def testExitCodeAndOutput(self):
|
||||
TestExitCodeAndOutput(COMMAND)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
gtest_test_utils.Main()
|
||||
|
||||
+132
-132
@@ -1,132 +1,132 @@
|
||||
#!/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.
|
||||
|
||||
"""Unit test for the gtest_xml_output module."""
|
||||
|
||||
__author__ = "keith.ray@gmail.com (Keith Ray)"
|
||||
|
||||
import os
|
||||
from xml.dom import minidom, Node
|
||||
|
||||
import gtest_test_utils
|
||||
import gtest_xml_test_utils
|
||||
|
||||
|
||||
GTEST_OUTPUT_SUBDIR = "xml_outfiles"
|
||||
GTEST_OUTPUT_1_TEST = "gtest_xml_outfile1_test_"
|
||||
GTEST_OUTPUT_2_TEST = "gtest_xml_outfile2_test_"
|
||||
|
||||
EXPECTED_XML_1 = """<?xml version="1.0" encoding="UTF-8"?>
|
||||
<testsuites tests="1" failures="0" disabled="0" errors="0" time="*" name="AllTests">
|
||||
<testsuite name="PropertyOne" tests="1" failures="0" disabled="0" errors="0" time="*">
|
||||
<testcase name="TestSomeProperties" status="run" time="*" classname="PropertyOne" SetUpProp="1" TestSomeProperty="1" TearDownProp="1" />
|
||||
</testsuite>
|
||||
</testsuites>
|
||||
"""
|
||||
|
||||
EXPECTED_XML_2 = """<?xml version="1.0" encoding="UTF-8"?>
|
||||
<testsuites tests="1" failures="0" disabled="0" errors="0" time="*" name="AllTests">
|
||||
<testsuite name="PropertyTwo" tests="1" failures="0" disabled="0" errors="0" time="*">
|
||||
<testcase name="TestSomeProperties" status="run" time="*" classname="PropertyTwo" SetUpProp="2" TestSomeProperty="2" TearDownProp="2" />
|
||||
</testsuite>
|
||||
</testsuites>
|
||||
"""
|
||||
|
||||
|
||||
class GTestXMLOutFilesTest(gtest_xml_test_utils.GTestXMLTestCase):
|
||||
"""Unit test for Google Test's XML output functionality."""
|
||||
|
||||
def setUp(self):
|
||||
# We want the trailing '/' that the last "" provides in os.path.join, for
|
||||
# telling Google Test to create an output directory instead of a single file
|
||||
# for xml output.
|
||||
self.output_dir_ = os.path.join(gtest_test_utils.GetTempDir(),
|
||||
GTEST_OUTPUT_SUBDIR, "")
|
||||
self.DeleteFilesAndDir()
|
||||
|
||||
def tearDown(self):
|
||||
self.DeleteFilesAndDir()
|
||||
|
||||
def DeleteFilesAndDir(self):
|
||||
try:
|
||||
os.remove(os.path.join(self.output_dir_, GTEST_OUTPUT_1_TEST + ".xml"))
|
||||
except os.error:
|
||||
pass
|
||||
try:
|
||||
os.remove(os.path.join(self.output_dir_, GTEST_OUTPUT_2_TEST + ".xml"))
|
||||
except os.error:
|
||||
pass
|
||||
try:
|
||||
os.rmdir(self.output_dir_)
|
||||
except os.error:
|
||||
pass
|
||||
|
||||
def testOutfile1(self):
|
||||
self._TestOutFile(GTEST_OUTPUT_1_TEST, EXPECTED_XML_1)
|
||||
|
||||
def testOutfile2(self):
|
||||
self._TestOutFile(GTEST_OUTPUT_2_TEST, EXPECTED_XML_2)
|
||||
|
||||
def _TestOutFile(self, test_name, expected_xml):
|
||||
gtest_prog_path = gtest_test_utils.GetTestExecutablePath(test_name)
|
||||
command = [gtest_prog_path, "--gtest_output=xml:%s" % self.output_dir_]
|
||||
p = gtest_test_utils.Subprocess(command,
|
||||
working_dir=gtest_test_utils.GetTempDir())
|
||||
self.assert_(p.exited)
|
||||
self.assertEquals(0, p.exit_code)
|
||||
|
||||
# TODO(wan@google.com): libtool causes the built test binary to be
|
||||
# named lt-gtest_xml_outfiles_test_ instead of
|
||||
# gtest_xml_outfiles_test_. To account for this possibillity, we
|
||||
# allow both names in the following code. We should remove this
|
||||
# hack when Chandler Carruth's libtool replacement tool is ready.
|
||||
output_file_name1 = test_name + ".xml"
|
||||
output_file1 = os.path.join(self.output_dir_, output_file_name1)
|
||||
output_file_name2 = 'lt-' + output_file_name1
|
||||
output_file2 = os.path.join(self.output_dir_, output_file_name2)
|
||||
self.assert_(os.path.isfile(output_file1) or os.path.isfile(output_file2),
|
||||
output_file1)
|
||||
|
||||
expected = minidom.parseString(expected_xml)
|
||||
if os.path.isfile(output_file1):
|
||||
actual = minidom.parse(output_file1)
|
||||
else:
|
||||
actual = minidom.parse(output_file2)
|
||||
self.NormalizeXml(actual.documentElement)
|
||||
self.AssertEquivalentNodes(expected.documentElement,
|
||||
actual.documentElement)
|
||||
expected.unlink()
|
||||
actual.unlink()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
os.environ["GTEST_STACK_TRACE_DEPTH"] = "0"
|
||||
gtest_test_utils.Main()
|
||||
#!/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.
|
||||
|
||||
"""Unit test for the gtest_xml_output module."""
|
||||
|
||||
__author__ = "keith.ray@gmail.com (Keith Ray)"
|
||||
|
||||
import os
|
||||
from xml.dom import minidom, Node
|
||||
|
||||
import gtest_test_utils
|
||||
import gtest_xml_test_utils
|
||||
|
||||
|
||||
GTEST_OUTPUT_SUBDIR = "xml_outfiles"
|
||||
GTEST_OUTPUT_1_TEST = "gtest_xml_outfile1_test_"
|
||||
GTEST_OUTPUT_2_TEST = "gtest_xml_outfile2_test_"
|
||||
|
||||
EXPECTED_XML_1 = """<?xml version="1.0" encoding="UTF-8"?>
|
||||
<testsuites tests="1" failures="0" disabled="0" errors="0" time="*" name="AllTests">
|
||||
<testsuite name="PropertyOne" tests="1" failures="0" disabled="0" errors="0" time="*">
|
||||
<testcase name="TestSomeProperties" status="run" time="*" classname="PropertyOne" SetUpProp="1" TestSomeProperty="1" TearDownProp="1" />
|
||||
</testsuite>
|
||||
</testsuites>
|
||||
"""
|
||||
|
||||
EXPECTED_XML_2 = """<?xml version="1.0" encoding="UTF-8"?>
|
||||
<testsuites tests="1" failures="0" disabled="0" errors="0" time="*" name="AllTests">
|
||||
<testsuite name="PropertyTwo" tests="1" failures="0" disabled="0" errors="0" time="*">
|
||||
<testcase name="TestSomeProperties" status="run" time="*" classname="PropertyTwo" SetUpProp="2" TestSomeProperty="2" TearDownProp="2" />
|
||||
</testsuite>
|
||||
</testsuites>
|
||||
"""
|
||||
|
||||
|
||||
class GTestXMLOutFilesTest(gtest_xml_test_utils.GTestXMLTestCase):
|
||||
"""Unit test for Google Test's XML output functionality."""
|
||||
|
||||
def setUp(self):
|
||||
# We want the trailing '/' that the last "" provides in os.path.join, for
|
||||
# telling Google Test to create an output directory instead of a single file
|
||||
# for xml output.
|
||||
self.output_dir_ = os.path.join(gtest_test_utils.GetTempDir(),
|
||||
GTEST_OUTPUT_SUBDIR, "")
|
||||
self.DeleteFilesAndDir()
|
||||
|
||||
def tearDown(self):
|
||||
self.DeleteFilesAndDir()
|
||||
|
||||
def DeleteFilesAndDir(self):
|
||||
try:
|
||||
os.remove(os.path.join(self.output_dir_, GTEST_OUTPUT_1_TEST + ".xml"))
|
||||
except os.error:
|
||||
pass
|
||||
try:
|
||||
os.remove(os.path.join(self.output_dir_, GTEST_OUTPUT_2_TEST + ".xml"))
|
||||
except os.error:
|
||||
pass
|
||||
try:
|
||||
os.rmdir(self.output_dir_)
|
||||
except os.error:
|
||||
pass
|
||||
|
||||
def testOutfile1(self):
|
||||
self._TestOutFile(GTEST_OUTPUT_1_TEST, EXPECTED_XML_1)
|
||||
|
||||
def testOutfile2(self):
|
||||
self._TestOutFile(GTEST_OUTPUT_2_TEST, EXPECTED_XML_2)
|
||||
|
||||
def _TestOutFile(self, test_name, expected_xml):
|
||||
gtest_prog_path = gtest_test_utils.GetTestExecutablePath(test_name)
|
||||
command = [gtest_prog_path, "--gtest_output=xml:%s" % self.output_dir_]
|
||||
p = gtest_test_utils.Subprocess(command,
|
||||
working_dir=gtest_test_utils.GetTempDir())
|
||||
self.assert_(p.exited)
|
||||
self.assertEquals(0, p.exit_code)
|
||||
|
||||
# TODO(wan@google.com): libtool causes the built test binary to be
|
||||
# named lt-gtest_xml_outfiles_test_ instead of
|
||||
# gtest_xml_outfiles_test_. To account for this possibillity, we
|
||||
# allow both names in the following code. We should remove this
|
||||
# hack when Chandler Carruth's libtool replacement tool is ready.
|
||||
output_file_name1 = test_name + ".xml"
|
||||
output_file1 = os.path.join(self.output_dir_, output_file_name1)
|
||||
output_file_name2 = 'lt-' + output_file_name1
|
||||
output_file2 = os.path.join(self.output_dir_, output_file_name2)
|
||||
self.assert_(os.path.isfile(output_file1) or os.path.isfile(output_file2),
|
||||
output_file1)
|
||||
|
||||
expected = minidom.parseString(expected_xml)
|
||||
if os.path.isfile(output_file1):
|
||||
actual = minidom.parse(output_file1)
|
||||
else:
|
||||
actual = minidom.parse(output_file2)
|
||||
self.NormalizeXml(actual.documentElement)
|
||||
self.AssertEquivalentNodes(expected.documentElement,
|
||||
actual.documentElement)
|
||||
expected.unlink()
|
||||
actual.unlink()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
os.environ["GTEST_STACK_TRACE_DEPTH"] = "0"
|
||||
gtest_test_utils.Main()
|
||||
|
||||
+224
-224
@@ -1,224 +1,224 @@
|
||||
#!/usr/bin/env python
|
||||
#
|
||||
# Copyright 2006, 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.
|
||||
|
||||
"""Unit test for the gtest_xml_output module"""
|
||||
|
||||
__author__ = 'eefacm@gmail.com (Sean Mcafee)'
|
||||
|
||||
import errno
|
||||
import os
|
||||
import sys
|
||||
from xml.dom import minidom, Node
|
||||
|
||||
import gtest_test_utils
|
||||
import gtest_xml_test_utils
|
||||
|
||||
|
||||
GTEST_OUTPUT_FLAG = "--gtest_output"
|
||||
GTEST_DEFAULT_OUTPUT_FILE = "test_detail.xml"
|
||||
GTEST_PROGRAM_NAME = "gtest_xml_output_unittest_"
|
||||
|
||||
SUPPORTS_STACK_TRACES = False
|
||||
|
||||
if SUPPORTS_STACK_TRACES:
|
||||
STACK_TRACE_TEMPLATE = "\nStack trace:\n*"
|
||||
else:
|
||||
STACK_TRACE_TEMPLATE = ""
|
||||
|
||||
EXPECTED_NON_EMPTY_XML = """<?xml version="1.0" encoding="UTF-8"?>
|
||||
<testsuites tests="15" failures="4" disabled="2" errors="0" time="*" name="AllTests">
|
||||
<testsuite name="SuccessfulTest" tests="1" failures="0" disabled="0" errors="0" time="*">
|
||||
<testcase name="Succeeds" status="run" time="*" classname="SuccessfulTest"/>
|
||||
</testsuite>
|
||||
<testsuite name="FailedTest" tests="1" failures="1" disabled="0" errors="0" time="*">
|
||||
<testcase name="Fails" status="run" time="*" classname="FailedTest">
|
||||
<failure message="Value of: 2
Expected: 1" type=""><![CDATA[gtest_xml_output_unittest_.cc:*
|
||||
Value of: 2
|
||||
Expected: 1%(stack)s]]></failure>
|
||||
</testcase>
|
||||
</testsuite>
|
||||
<testsuite name="MixedResultTest" tests="3" failures="1" disabled="1" errors="0" time="*">
|
||||
<testcase name="Succeeds" status="run" time="*" classname="MixedResultTest"/>
|
||||
<testcase name="Fails" status="run" time="*" classname="MixedResultTest">
|
||||
<failure message="Value of: 2
Expected: 1" type=""><![CDATA[gtest_xml_output_unittest_.cc:*
|
||||
Value of: 2
|
||||
Expected: 1%(stack)s]]></failure>
|
||||
<failure message="Value of: 3
Expected: 2" type=""><![CDATA[gtest_xml_output_unittest_.cc:*
|
||||
Value of: 3
|
||||
Expected: 2%(stack)s]]></failure>
|
||||
</testcase>
|
||||
<testcase name="DISABLED_test" status="notrun" time="*" classname="MixedResultTest"/>
|
||||
</testsuite>
|
||||
<testsuite name="XmlQuotingTest" tests="1" failures="1" disabled="0" errors="0" time="*">
|
||||
<testcase name="OutputsCData" status="run" time="*" classname="XmlQuotingTest">
|
||||
<failure message="Failed
XML output: <?xml encoding="utf-8"><top><![CDATA[cdata text]]></top>" type=""><![CDATA[gtest_xml_output_unittest_.cc:*
|
||||
Failed
|
||||
XML output: <?xml encoding="utf-8"><top><![CDATA[cdata text]]>]]><![CDATA[</top>%(stack)s]]></failure>
|
||||
</testcase>
|
||||
</testsuite>
|
||||
<testsuite name="InvalidCharactersTest" tests="1" failures="1" disabled="0" errors="0" time="*">
|
||||
<testcase name="InvalidCharactersInMessage" status="run" time="*" classname="InvalidCharactersTest">
|
||||
<failure message="Failed
Invalid characters in brackets []" type=""><![CDATA[gtest_xml_output_unittest_.cc:*
|
||||
Failed
|
||||
Invalid characters in brackets []%(stack)s]]></failure>
|
||||
</testcase>
|
||||
</testsuite>
|
||||
<testsuite name="DisabledTest" tests="1" failures="0" disabled="1" errors="0" time="*">
|
||||
<testcase name="DISABLED_test_not_run" status="notrun" time="*" classname="DisabledTest"/>
|
||||
</testsuite>
|
||||
<testsuite name="PropertyRecordingTest" tests="4" failures="0" disabled="0" errors="0" time="*">
|
||||
<testcase name="OneProperty" status="run" time="*" classname="PropertyRecordingTest" key_1="1"/>
|
||||
<testcase name="IntValuedProperty" status="run" time="*" classname="PropertyRecordingTest" key_int="1"/>
|
||||
<testcase name="ThreeProperties" status="run" time="*" classname="PropertyRecordingTest" key_1="1" key_2="2" key_3="3"/>
|
||||
<testcase name="TwoValuesForOneKeyUsesLastValue" status="run" time="*" classname="PropertyRecordingTest" key_1="2"/>
|
||||
</testsuite>
|
||||
<testsuite name="NoFixtureTest" tests="3" failures="0" disabled="0" errors="0" time="*">
|
||||
<testcase name="RecordProperty" status="run" time="*" classname="NoFixtureTest" key="1"/>
|
||||
<testcase name="ExternalUtilityThatCallsRecordIntValuedProperty" status="run" time="*" classname="NoFixtureTest" key_for_utility_int="1"/>
|
||||
<testcase name="ExternalUtilityThatCallsRecordStringValuedProperty" status="run" time="*" classname="NoFixtureTest" key_for_utility_string="1"/>
|
||||
</testsuite>
|
||||
</testsuites>""" % {'stack': STACK_TRACE_TEMPLATE}
|
||||
|
||||
|
||||
EXPECTED_EMPTY_XML = """<?xml version="1.0" encoding="UTF-8"?>
|
||||
<testsuites tests="0" failures="0" disabled="0" errors="0" time="*" name="AllTests">
|
||||
</testsuites>"""
|
||||
|
||||
|
||||
class GTestXMLOutputUnitTest(gtest_xml_test_utils.GTestXMLTestCase):
|
||||
"""
|
||||
Unit test for Google Test's XML output functionality.
|
||||
"""
|
||||
|
||||
def testNonEmptyXmlOutput(self):
|
||||
"""
|
||||
Runs a test program that generates a non-empty XML output, and
|
||||
tests that the XML output is expected.
|
||||
"""
|
||||
self._TestXmlOutput(GTEST_PROGRAM_NAME, EXPECTED_NON_EMPTY_XML, 1)
|
||||
|
||||
def testEmptyXmlOutput(self):
|
||||
"""
|
||||
Runs a test program that generates an empty XML output, and
|
||||
tests that the XML output is expected.
|
||||
"""
|
||||
|
||||
self._TestXmlOutput("gtest_no_test_unittest",
|
||||
EXPECTED_EMPTY_XML, 0)
|
||||
|
||||
def testDefaultOutputFile(self):
|
||||
"""
|
||||
Confirms that Google Test produces an XML output file with the expected
|
||||
default name if no name is explicitly specified.
|
||||
"""
|
||||
output_file = os.path.join(gtest_test_utils.GetTempDir(),
|
||||
GTEST_DEFAULT_OUTPUT_FILE)
|
||||
gtest_prog_path = gtest_test_utils.GetTestExecutablePath(
|
||||
"gtest_no_test_unittest")
|
||||
try:
|
||||
os.remove(output_file)
|
||||
except OSError, e:
|
||||
if e.errno != errno.ENOENT:
|
||||
raise
|
||||
|
||||
p = gtest_test_utils.Subprocess(
|
||||
[gtest_prog_path, "%s=xml" % GTEST_OUTPUT_FLAG],
|
||||
working_dir=gtest_test_utils.GetTempDir())
|
||||
self.assert_(p.exited)
|
||||
self.assertEquals(0, p.exit_code)
|
||||
self.assert_(os.path.isfile(output_file))
|
||||
|
||||
def testSuppressedXmlOutput(self):
|
||||
"""
|
||||
Tests that no XML file is generated if the default XML listener is
|
||||
shut down before RUN_ALL_TESTS is invoked.
|
||||
"""
|
||||
|
||||
xml_path = os.path.join(gtest_test_utils.GetTempDir(),
|
||||
GTEST_PROGRAM_NAME + "out.xml")
|
||||
if os.path.isfile(xml_path):
|
||||
os.remove(xml_path)
|
||||
|
||||
gtest_prog_path = gtest_test_utils.GetTestExecutablePath(GTEST_PROGRAM_NAME)
|
||||
|
||||
command = [gtest_prog_path,
|
||||
"%s=xml:%s" % (GTEST_OUTPUT_FLAG, xml_path),
|
||||
"--shut_down_xml"]
|
||||
p = gtest_test_utils.Subprocess(command)
|
||||
if p.terminated_by_signal:
|
||||
self.assert_(False,
|
||||
"%s was killed by signal %d" % (gtest_prog_name, p.signal))
|
||||
else:
|
||||
self.assert_(p.exited)
|
||||
self.assertEquals(1, p.exit_code,
|
||||
"'%s' exited with code %s, which doesn't match "
|
||||
"the expected exit code %s."
|
||||
% (command, p.exit_code, 1))
|
||||
|
||||
self.assert_(not os.path.isfile(xml_path))
|
||||
|
||||
|
||||
def _TestXmlOutput(self, gtest_prog_name, expected_xml, expected_exit_code):
|
||||
"""
|
||||
Asserts that the XML document generated by running the program
|
||||
gtest_prog_name matches expected_xml, a string containing another
|
||||
XML document. Furthermore, the program's exit code must be
|
||||
expected_exit_code.
|
||||
"""
|
||||
xml_path = os.path.join(gtest_test_utils.GetTempDir(),
|
||||
gtest_prog_name + "out.xml")
|
||||
gtest_prog_path = gtest_test_utils.GetTestExecutablePath(gtest_prog_name)
|
||||
|
||||
command = [gtest_prog_path, "%s=xml:%s" % (GTEST_OUTPUT_FLAG, xml_path)]
|
||||
p = gtest_test_utils.Subprocess(command)
|
||||
if p.terminated_by_signal:
|
||||
self.assert_(False,
|
||||
"%s was killed by signal %d" % (gtest_prog_name, p.signal))
|
||||
else:
|
||||
self.assert_(p.exited)
|
||||
self.assertEquals(expected_exit_code, p.exit_code,
|
||||
"'%s' exited with code %s, which doesn't match "
|
||||
"the expected exit code %s."
|
||||
% (command, p.exit_code, expected_exit_code))
|
||||
|
||||
expected = minidom.parseString(expected_xml)
|
||||
actual = minidom.parse(xml_path)
|
||||
self.NormalizeXml(actual.documentElement)
|
||||
self.AssertEquivalentNodes(expected.documentElement,
|
||||
actual.documentElement)
|
||||
expected.unlink()
|
||||
actual .unlink()
|
||||
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
os.environ['GTEST_STACK_TRACE_DEPTH'] = '1'
|
||||
gtest_test_utils.Main()
|
||||
#!/usr/bin/env python
|
||||
#
|
||||
# Copyright 2006, 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.
|
||||
|
||||
"""Unit test for the gtest_xml_output module"""
|
||||
|
||||
__author__ = 'eefacm@gmail.com (Sean Mcafee)'
|
||||
|
||||
import errno
|
||||
import os
|
||||
import sys
|
||||
from xml.dom import minidom, Node
|
||||
|
||||
import gtest_test_utils
|
||||
import gtest_xml_test_utils
|
||||
|
||||
|
||||
GTEST_OUTPUT_FLAG = "--gtest_output"
|
||||
GTEST_DEFAULT_OUTPUT_FILE = "test_detail.xml"
|
||||
GTEST_PROGRAM_NAME = "gtest_xml_output_unittest_"
|
||||
|
||||
SUPPORTS_STACK_TRACES = False
|
||||
|
||||
if SUPPORTS_STACK_TRACES:
|
||||
STACK_TRACE_TEMPLATE = "\nStack trace:\n*"
|
||||
else:
|
||||
STACK_TRACE_TEMPLATE = ""
|
||||
|
||||
EXPECTED_NON_EMPTY_XML = """<?xml version="1.0" encoding="UTF-8"?>
|
||||
<testsuites tests="15" failures="4" disabled="2" errors="0" time="*" name="AllTests">
|
||||
<testsuite name="SuccessfulTest" tests="1" failures="0" disabled="0" errors="0" time="*">
|
||||
<testcase name="Succeeds" status="run" time="*" classname="SuccessfulTest"/>
|
||||
</testsuite>
|
||||
<testsuite name="FailedTest" tests="1" failures="1" disabled="0" errors="0" time="*">
|
||||
<testcase name="Fails" status="run" time="*" classname="FailedTest">
|
||||
<failure message="Value of: 2
Expected: 1" type=""><![CDATA[gtest_xml_output_unittest_.cc:*
|
||||
Value of: 2
|
||||
Expected: 1%(stack)s]]></failure>
|
||||
</testcase>
|
||||
</testsuite>
|
||||
<testsuite name="MixedResultTest" tests="3" failures="1" disabled="1" errors="0" time="*">
|
||||
<testcase name="Succeeds" status="run" time="*" classname="MixedResultTest"/>
|
||||
<testcase name="Fails" status="run" time="*" classname="MixedResultTest">
|
||||
<failure message="Value of: 2
Expected: 1" type=""><![CDATA[gtest_xml_output_unittest_.cc:*
|
||||
Value of: 2
|
||||
Expected: 1%(stack)s]]></failure>
|
||||
<failure message="Value of: 3
Expected: 2" type=""><![CDATA[gtest_xml_output_unittest_.cc:*
|
||||
Value of: 3
|
||||
Expected: 2%(stack)s]]></failure>
|
||||
</testcase>
|
||||
<testcase name="DISABLED_test" status="notrun" time="*" classname="MixedResultTest"/>
|
||||
</testsuite>
|
||||
<testsuite name="XmlQuotingTest" tests="1" failures="1" disabled="0" errors="0" time="*">
|
||||
<testcase name="OutputsCData" status="run" time="*" classname="XmlQuotingTest">
|
||||
<failure message="Failed
XML output: <?xml encoding="utf-8"><top><![CDATA[cdata text]]></top>" type=""><![CDATA[gtest_xml_output_unittest_.cc:*
|
||||
Failed
|
||||
XML output: <?xml encoding="utf-8"><top><![CDATA[cdata text]]>]]><![CDATA[</top>%(stack)s]]></failure>
|
||||
</testcase>
|
||||
</testsuite>
|
||||
<testsuite name="InvalidCharactersTest" tests="1" failures="1" disabled="0" errors="0" time="*">
|
||||
<testcase name="InvalidCharactersInMessage" status="run" time="*" classname="InvalidCharactersTest">
|
||||
<failure message="Failed
Invalid characters in brackets []" type=""><![CDATA[gtest_xml_output_unittest_.cc:*
|
||||
Failed
|
||||
Invalid characters in brackets []%(stack)s]]></failure>
|
||||
</testcase>
|
||||
</testsuite>
|
||||
<testsuite name="DisabledTest" tests="1" failures="0" disabled="1" errors="0" time="*">
|
||||
<testcase name="DISABLED_test_not_run" status="notrun" time="*" classname="DisabledTest"/>
|
||||
</testsuite>
|
||||
<testsuite name="PropertyRecordingTest" tests="4" failures="0" disabled="0" errors="0" time="*">
|
||||
<testcase name="OneProperty" status="run" time="*" classname="PropertyRecordingTest" key_1="1"/>
|
||||
<testcase name="IntValuedProperty" status="run" time="*" classname="PropertyRecordingTest" key_int="1"/>
|
||||
<testcase name="ThreeProperties" status="run" time="*" classname="PropertyRecordingTest" key_1="1" key_2="2" key_3="3"/>
|
||||
<testcase name="TwoValuesForOneKeyUsesLastValue" status="run" time="*" classname="PropertyRecordingTest" key_1="2"/>
|
||||
</testsuite>
|
||||
<testsuite name="NoFixtureTest" tests="3" failures="0" disabled="0" errors="0" time="*">
|
||||
<testcase name="RecordProperty" status="run" time="*" classname="NoFixtureTest" key="1"/>
|
||||
<testcase name="ExternalUtilityThatCallsRecordIntValuedProperty" status="run" time="*" classname="NoFixtureTest" key_for_utility_int="1"/>
|
||||
<testcase name="ExternalUtilityThatCallsRecordStringValuedProperty" status="run" time="*" classname="NoFixtureTest" key_for_utility_string="1"/>
|
||||
</testsuite>
|
||||
</testsuites>""" % {'stack': STACK_TRACE_TEMPLATE}
|
||||
|
||||
|
||||
EXPECTED_EMPTY_XML = """<?xml version="1.0" encoding="UTF-8"?>
|
||||
<testsuites tests="0" failures="0" disabled="0" errors="0" time="*" name="AllTests">
|
||||
</testsuites>"""
|
||||
|
||||
|
||||
class GTestXMLOutputUnitTest(gtest_xml_test_utils.GTestXMLTestCase):
|
||||
"""
|
||||
Unit test for Google Test's XML output functionality.
|
||||
"""
|
||||
|
||||
def testNonEmptyXmlOutput(self):
|
||||
"""
|
||||
Runs a test program that generates a non-empty XML output, and
|
||||
tests that the XML output is expected.
|
||||
"""
|
||||
self._TestXmlOutput(GTEST_PROGRAM_NAME, EXPECTED_NON_EMPTY_XML, 1)
|
||||
|
||||
def testEmptyXmlOutput(self):
|
||||
"""
|
||||
Runs a test program that generates an empty XML output, and
|
||||
tests that the XML output is expected.
|
||||
"""
|
||||
|
||||
self._TestXmlOutput("gtest_no_test_unittest",
|
||||
EXPECTED_EMPTY_XML, 0)
|
||||
|
||||
def testDefaultOutputFile(self):
|
||||
"""
|
||||
Confirms that Google Test produces an XML output file with the expected
|
||||
default name if no name is explicitly specified.
|
||||
"""
|
||||
output_file = os.path.join(gtest_test_utils.GetTempDir(),
|
||||
GTEST_DEFAULT_OUTPUT_FILE)
|
||||
gtest_prog_path = gtest_test_utils.GetTestExecutablePath(
|
||||
"gtest_no_test_unittest")
|
||||
try:
|
||||
os.remove(output_file)
|
||||
except OSError, e:
|
||||
if e.errno != errno.ENOENT:
|
||||
raise
|
||||
|
||||
p = gtest_test_utils.Subprocess(
|
||||
[gtest_prog_path, "%s=xml" % GTEST_OUTPUT_FLAG],
|
||||
working_dir=gtest_test_utils.GetTempDir())
|
||||
self.assert_(p.exited)
|
||||
self.assertEquals(0, p.exit_code)
|
||||
self.assert_(os.path.isfile(output_file))
|
||||
|
||||
def testSuppressedXmlOutput(self):
|
||||
"""
|
||||
Tests that no XML file is generated if the default XML listener is
|
||||
shut down before RUN_ALL_TESTS is invoked.
|
||||
"""
|
||||
|
||||
xml_path = os.path.join(gtest_test_utils.GetTempDir(),
|
||||
GTEST_PROGRAM_NAME + "out.xml")
|
||||
if os.path.isfile(xml_path):
|
||||
os.remove(xml_path)
|
||||
|
||||
gtest_prog_path = gtest_test_utils.GetTestExecutablePath(GTEST_PROGRAM_NAME)
|
||||
|
||||
command = [gtest_prog_path,
|
||||
"%s=xml:%s" % (GTEST_OUTPUT_FLAG, xml_path),
|
||||
"--shut_down_xml"]
|
||||
p = gtest_test_utils.Subprocess(command)
|
||||
if p.terminated_by_signal:
|
||||
self.assert_(False,
|
||||
"%s was killed by signal %d" % (gtest_prog_name, p.signal))
|
||||
else:
|
||||
self.assert_(p.exited)
|
||||
self.assertEquals(1, p.exit_code,
|
||||
"'%s' exited with code %s, which doesn't match "
|
||||
"the expected exit code %s."
|
||||
% (command, p.exit_code, 1))
|
||||
|
||||
self.assert_(not os.path.isfile(xml_path))
|
||||
|
||||
|
||||
def _TestXmlOutput(self, gtest_prog_name, expected_xml, expected_exit_code):
|
||||
"""
|
||||
Asserts that the XML document generated by running the program
|
||||
gtest_prog_name matches expected_xml, a string containing another
|
||||
XML document. Furthermore, the program's exit code must be
|
||||
expected_exit_code.
|
||||
"""
|
||||
xml_path = os.path.join(gtest_test_utils.GetTempDir(),
|
||||
gtest_prog_name + "out.xml")
|
||||
gtest_prog_path = gtest_test_utils.GetTestExecutablePath(gtest_prog_name)
|
||||
|
||||
command = [gtest_prog_path, "%s=xml:%s" % (GTEST_OUTPUT_FLAG, xml_path)]
|
||||
p = gtest_test_utils.Subprocess(command)
|
||||
if p.terminated_by_signal:
|
||||
self.assert_(False,
|
||||
"%s was killed by signal %d" % (gtest_prog_name, p.signal))
|
||||
else:
|
||||
self.assert_(p.exited)
|
||||
self.assertEquals(expected_exit_code, p.exit_code,
|
||||
"'%s' exited with code %s, which doesn't match "
|
||||
"the expected exit code %s."
|
||||
% (command, p.exit_code, expected_exit_code))
|
||||
|
||||
expected = minidom.parseString(expected_xml)
|
||||
actual = minidom.parse(xml_path)
|
||||
self.NormalizeXml(actual.documentElement)
|
||||
self.AssertEquivalentNodes(expected.documentElement,
|
||||
actual.documentElement)
|
||||
expected.unlink()
|
||||
actual .unlink()
|
||||
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
os.environ['GTEST_STACK_TRACE_DEPTH'] = '1'
|
||||
gtest_test_utils.Main()
|
||||
|
||||
+172
-172
@@ -1,172 +1,172 @@
|
||||
#!/usr/bin/env python
|
||||
#
|
||||
# Copyright 2006, 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.
|
||||
|
||||
"""Unit test utilities for gtest_xml_output"""
|
||||
|
||||
__author__ = 'eefacm@gmail.com (Sean Mcafee)'
|
||||
|
||||
import re
|
||||
from xml.dom import minidom, Node
|
||||
|
||||
import gtest_test_utils
|
||||
|
||||
|
||||
GTEST_OUTPUT_FLAG = "--gtest_output"
|
||||
GTEST_DEFAULT_OUTPUT_FILE = "test_detail.xml"
|
||||
|
||||
class GTestXMLTestCase(gtest_test_utils.TestCase):
|
||||
"""
|
||||
Base class for tests of Google Test's XML output functionality.
|
||||
"""
|
||||
|
||||
|
||||
def AssertEquivalentNodes(self, expected_node, actual_node):
|
||||
"""
|
||||
Asserts that actual_node (a DOM node object) is equivalent to
|
||||
expected_node (another DOM node object), in that either both of
|
||||
them are CDATA nodes and have the same value, or both are DOM
|
||||
elements and actual_node meets all of the following conditions:
|
||||
|
||||
* It has the same tag name as expected_node.
|
||||
* It has the same set of attributes as expected_node, each with
|
||||
the same value as the corresponding attribute of expected_node.
|
||||
An exception is any attribute named "time", which needs only be
|
||||
convertible to a floating-point number.
|
||||
* It has an equivalent set of child nodes (including elements and
|
||||
CDATA sections) as expected_node. Note that we ignore the
|
||||
order of the children as they are not guaranteed to be in any
|
||||
particular order.
|
||||
"""
|
||||
|
||||
if expected_node.nodeType == Node.CDATA_SECTION_NODE:
|
||||
self.assertEquals(Node.CDATA_SECTION_NODE, actual_node.nodeType)
|
||||
self.assertEquals(expected_node.nodeValue, actual_node.nodeValue)
|
||||
return
|
||||
|
||||
self.assertEquals(Node.ELEMENT_NODE, actual_node.nodeType)
|
||||
self.assertEquals(Node.ELEMENT_NODE, expected_node.nodeType)
|
||||
self.assertEquals(expected_node.tagName, actual_node.tagName)
|
||||
|
||||
expected_attributes = expected_node.attributes
|
||||
actual_attributes = actual_node .attributes
|
||||
self.assertEquals(
|
||||
expected_attributes.length, actual_attributes.length,
|
||||
"attribute numbers differ in element " + actual_node.tagName)
|
||||
for i in range(expected_attributes.length):
|
||||
expected_attr = expected_attributes.item(i)
|
||||
actual_attr = actual_attributes.get(expected_attr.name)
|
||||
self.assert_(
|
||||
actual_attr is not None,
|
||||
"expected attribute %s not found in element %s" %
|
||||
(expected_attr.name, actual_node.tagName))
|
||||
self.assertEquals(expected_attr.value, actual_attr.value,
|
||||
" values of attribute %s in element %s differ" %
|
||||
(expected_attr.name, actual_node.tagName))
|
||||
|
||||
expected_children = self._GetChildren(expected_node)
|
||||
actual_children = self._GetChildren(actual_node)
|
||||
self.assertEquals(
|
||||
len(expected_children), len(actual_children),
|
||||
"number of child elements differ in element " + actual_node.tagName)
|
||||
for child_id, child in expected_children.iteritems():
|
||||
self.assert_(child_id in actual_children,
|
||||
'<%s> is not in <%s> (in element %s)' %
|
||||
(child_id, actual_children, actual_node.tagName))
|
||||
self.AssertEquivalentNodes(child, actual_children[child_id])
|
||||
|
||||
identifying_attribute = {
|
||||
"testsuites": "name",
|
||||
"testsuite": "name",
|
||||
"testcase": "name",
|
||||
"failure": "message",
|
||||
}
|
||||
|
||||
def _GetChildren(self, element):
|
||||
"""
|
||||
Fetches all of the child nodes of element, a DOM Element object.
|
||||
Returns them as the values of a dictionary keyed by the IDs of the
|
||||
children. For <testsuites>, <testsuite> and <testcase> elements, the ID
|
||||
is the value of their "name" attribute; for <failure> elements, it is
|
||||
the value of the "message" attribute; CDATA sections and non-whitespace
|
||||
text nodes are concatenated into a single CDATA section with ID
|
||||
"detail". An exception is raised if any element other than the above
|
||||
four is encountered, if two child elements with the same identifying
|
||||
attributes are encountered, or if any other type of node is encountered.
|
||||
"""
|
||||
|
||||
children = {}
|
||||
for child in element.childNodes:
|
||||
if child.nodeType == Node.ELEMENT_NODE:
|
||||
self.assert_(child.tagName in self.identifying_attribute,
|
||||
"Encountered unknown element <%s>" % child.tagName)
|
||||
childID = child.getAttribute(self.identifying_attribute[child.tagName])
|
||||
self.assert_(childID not in children)
|
||||
children[childID] = child
|
||||
elif child.nodeType in [Node.TEXT_NODE, Node.CDATA_SECTION_NODE]:
|
||||
if "detail" not in children:
|
||||
if (child.nodeType == Node.CDATA_SECTION_NODE or
|
||||
not child.nodeValue.isspace()):
|
||||
children["detail"] = child.ownerDocument.createCDATASection(
|
||||
child.nodeValue)
|
||||
else:
|
||||
children["detail"].nodeValue += child.nodeValue
|
||||
else:
|
||||
self.fail("Encountered unexpected node type %d" % child.nodeType)
|
||||
return children
|
||||
|
||||
def NormalizeXml(self, element):
|
||||
"""
|
||||
Normalizes Google Test's XML output to eliminate references to transient
|
||||
information that may change from run to run.
|
||||
|
||||
* The "time" attribute of <testsuites>, <testsuite> and <testcase>
|
||||
elements is replaced with a single asterisk, if it contains
|
||||
only digit characters.
|
||||
* The line number reported in the first line of the "message"
|
||||
attribute of <failure> elements is replaced with a single asterisk.
|
||||
* The directory names in file paths are removed.
|
||||
* The stack traces are removed.
|
||||
"""
|
||||
|
||||
if element.tagName in ("testsuites", "testsuite", "testcase"):
|
||||
time = element.getAttributeNode("time")
|
||||
time.value = re.sub(r"^\d+(\.\d+)?$", "*", time.value)
|
||||
elif element.tagName == "failure":
|
||||
for child in element.childNodes:
|
||||
if child.nodeType == Node.CDATA_SECTION_NODE:
|
||||
# Removes the source line number.
|
||||
cdata = re.sub(r"^.*[/\\](.*:)\d+\n", "\\1*\n", child.nodeValue)
|
||||
# Removes the actual stack trace.
|
||||
child.nodeValue = re.sub(r"\nStack trace:\n(.|\n)*",
|
||||
"", cdata)
|
||||
for child in element.childNodes:
|
||||
if child.nodeType == Node.ELEMENT_NODE:
|
||||
self.NormalizeXml(child)
|
||||
#!/usr/bin/env python
|
||||
#
|
||||
# Copyright 2006, 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.
|
||||
|
||||
"""Unit test utilities for gtest_xml_output"""
|
||||
|
||||
__author__ = 'eefacm@gmail.com (Sean Mcafee)'
|
||||
|
||||
import re
|
||||
from xml.dom import minidom, Node
|
||||
|
||||
import gtest_test_utils
|
||||
|
||||
|
||||
GTEST_OUTPUT_FLAG = "--gtest_output"
|
||||
GTEST_DEFAULT_OUTPUT_FILE = "test_detail.xml"
|
||||
|
||||
class GTestXMLTestCase(gtest_test_utils.TestCase):
|
||||
"""
|
||||
Base class for tests of Google Test's XML output functionality.
|
||||
"""
|
||||
|
||||
|
||||
def AssertEquivalentNodes(self, expected_node, actual_node):
|
||||
"""
|
||||
Asserts that actual_node (a DOM node object) is equivalent to
|
||||
expected_node (another DOM node object), in that either both of
|
||||
them are CDATA nodes and have the same value, or both are DOM
|
||||
elements and actual_node meets all of the following conditions:
|
||||
|
||||
* It has the same tag name as expected_node.
|
||||
* It has the same set of attributes as expected_node, each with
|
||||
the same value as the corresponding attribute of expected_node.
|
||||
An exception is any attribute named "time", which needs only be
|
||||
convertible to a floating-point number.
|
||||
* It has an equivalent set of child nodes (including elements and
|
||||
CDATA sections) as expected_node. Note that we ignore the
|
||||
order of the children as they are not guaranteed to be in any
|
||||
particular order.
|
||||
"""
|
||||
|
||||
if expected_node.nodeType == Node.CDATA_SECTION_NODE:
|
||||
self.assertEquals(Node.CDATA_SECTION_NODE, actual_node.nodeType)
|
||||
self.assertEquals(expected_node.nodeValue, actual_node.nodeValue)
|
||||
return
|
||||
|
||||
self.assertEquals(Node.ELEMENT_NODE, actual_node.nodeType)
|
||||
self.assertEquals(Node.ELEMENT_NODE, expected_node.nodeType)
|
||||
self.assertEquals(expected_node.tagName, actual_node.tagName)
|
||||
|
||||
expected_attributes = expected_node.attributes
|
||||
actual_attributes = actual_node .attributes
|
||||
self.assertEquals(
|
||||
expected_attributes.length, actual_attributes.length,
|
||||
"attribute numbers differ in element " + actual_node.tagName)
|
||||
for i in range(expected_attributes.length):
|
||||
expected_attr = expected_attributes.item(i)
|
||||
actual_attr = actual_attributes.get(expected_attr.name)
|
||||
self.assert_(
|
||||
actual_attr is not None,
|
||||
"expected attribute %s not found in element %s" %
|
||||
(expected_attr.name, actual_node.tagName))
|
||||
self.assertEquals(expected_attr.value, actual_attr.value,
|
||||
" values of attribute %s in element %s differ" %
|
||||
(expected_attr.name, actual_node.tagName))
|
||||
|
||||
expected_children = self._GetChildren(expected_node)
|
||||
actual_children = self._GetChildren(actual_node)
|
||||
self.assertEquals(
|
||||
len(expected_children), len(actual_children),
|
||||
"number of child elements differ in element " + actual_node.tagName)
|
||||
for child_id, child in expected_children.iteritems():
|
||||
self.assert_(child_id in actual_children,
|
||||
'<%s> is not in <%s> (in element %s)' %
|
||||
(child_id, actual_children, actual_node.tagName))
|
||||
self.AssertEquivalentNodes(child, actual_children[child_id])
|
||||
|
||||
identifying_attribute = {
|
||||
"testsuites": "name",
|
||||
"testsuite": "name",
|
||||
"testcase": "name",
|
||||
"failure": "message",
|
||||
}
|
||||
|
||||
def _GetChildren(self, element):
|
||||
"""
|
||||
Fetches all of the child nodes of element, a DOM Element object.
|
||||
Returns them as the values of a dictionary keyed by the IDs of the
|
||||
children. For <testsuites>, <testsuite> and <testcase> elements, the ID
|
||||
is the value of their "name" attribute; for <failure> elements, it is
|
||||
the value of the "message" attribute; CDATA sections and non-whitespace
|
||||
text nodes are concatenated into a single CDATA section with ID
|
||||
"detail". An exception is raised if any element other than the above
|
||||
four is encountered, if two child elements with the same identifying
|
||||
attributes are encountered, or if any other type of node is encountered.
|
||||
"""
|
||||
|
||||
children = {}
|
||||
for child in element.childNodes:
|
||||
if child.nodeType == Node.ELEMENT_NODE:
|
||||
self.assert_(child.tagName in self.identifying_attribute,
|
||||
"Encountered unknown element <%s>" % child.tagName)
|
||||
childID = child.getAttribute(self.identifying_attribute[child.tagName])
|
||||
self.assert_(childID not in children)
|
||||
children[childID] = child
|
||||
elif child.nodeType in [Node.TEXT_NODE, Node.CDATA_SECTION_NODE]:
|
||||
if "detail" not in children:
|
||||
if (child.nodeType == Node.CDATA_SECTION_NODE or
|
||||
not child.nodeValue.isspace()):
|
||||
children["detail"] = child.ownerDocument.createCDATASection(
|
||||
child.nodeValue)
|
||||
else:
|
||||
children["detail"].nodeValue += child.nodeValue
|
||||
else:
|
||||
self.fail("Encountered unexpected node type %d" % child.nodeType)
|
||||
return children
|
||||
|
||||
def NormalizeXml(self, element):
|
||||
"""
|
||||
Normalizes Google Test's XML output to eliminate references to transient
|
||||
information that may change from run to run.
|
||||
|
||||
* The "time" attribute of <testsuites>, <testsuite> and <testcase>
|
||||
elements is replaced with a single asterisk, if it contains
|
||||
only digit characters.
|
||||
* The line number reported in the first line of the "message"
|
||||
attribute of <failure> elements is replaced with a single asterisk.
|
||||
* The directory names in file paths are removed.
|
||||
* The stack traces are removed.
|
||||
"""
|
||||
|
||||
if element.tagName in ("testsuites", "testsuite", "testcase"):
|
||||
time = element.getAttributeNode("time")
|
||||
time.value = re.sub(r"^\d+(\.\d+)?$", "*", time.value)
|
||||
elif element.tagName == "failure":
|
||||
for child in element.childNodes:
|
||||
if child.nodeType == Node.CDATA_SECTION_NODE:
|
||||
# Removes the source line number.
|
||||
cdata = re.sub(r"^.*[/\\](.*:)\d+\n", "\\1*\n", child.nodeValue)
|
||||
# Removes the actual stack trace.
|
||||
child.nodeValue = re.sub(r"\nStack trace:\n(.|\n)*",
|
||||
"", cdata)
|
||||
for child in element.childNodes:
|
||||
if child.nodeType == Node.ELEMENT_NODE:
|
||||
self.NormalizeXml(child)
|
||||
|
||||
+55
-55
@@ -1,55 +1,55 @@
|
||||
// Copyright 2006, 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)
|
||||
//
|
||||
// This is part of the unit test for include/gtest/gtest_prod.h.
|
||||
|
||||
#ifndef GTEST_TEST_PRODUCTION_H_
|
||||
#define GTEST_TEST_PRODUCTION_H_
|
||||
|
||||
#include <gtest/gtest_prod.h>
|
||||
|
||||
class PrivateCode {
|
||||
public:
|
||||
// Declares a friend test that does not use a fixture.
|
||||
FRIEND_TEST(PrivateCodeTest, CanAccessPrivateMembers);
|
||||
|
||||
// Declares a friend test that uses a fixture.
|
||||
FRIEND_TEST(PrivateCodeFixtureTest, CanAccessPrivateMembers);
|
||||
|
||||
PrivateCode();
|
||||
|
||||
int x() const { return x_; }
|
||||
private:
|
||||
void set_x(int x) { x_ = x; }
|
||||
int x_;
|
||||
};
|
||||
|
||||
#endif // GTEST_TEST_PRODUCTION_H_
|
||||
// Copyright 2006, 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)
|
||||
//
|
||||
// This is part of the unit test for include/gtest/gtest_prod.h.
|
||||
|
||||
#ifndef GTEST_TEST_PRODUCTION_H_
|
||||
#define GTEST_TEST_PRODUCTION_H_
|
||||
|
||||
#include <gtest/gtest_prod.h>
|
||||
|
||||
class PrivateCode {
|
||||
public:
|
||||
// Declares a friend test that does not use a fixture.
|
||||
FRIEND_TEST(PrivateCodeTest, CanAccessPrivateMembers);
|
||||
|
||||
// Declares a friend test that uses a fixture.
|
||||
FRIEND_TEST(PrivateCodeFixtureTest, CanAccessPrivateMembers);
|
||||
|
||||
PrivateCode();
|
||||
|
||||
int x() const { return x_; }
|
||||
private:
|
||||
void set_x(int x) { x_ = x; }
|
||||
int x_;
|
||||
};
|
||||
|
||||
#endif // GTEST_TEST_PRODUCTION_H_
|
||||
|
||||
+59
-59
@@ -1,59 +1,59 @@
|
||||
// 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.
|
||||
//
|
||||
// Author: preston.jackson@gmail.com (Preston Jackson)
|
||||
//
|
||||
// Google Test - FrameworkSample
|
||||
// widget.h
|
||||
//
|
||||
|
||||
// Widget is a very simple class used for demonstrating the use of gtest. It
|
||||
// simply stores two values a string and an integer, which are returned via
|
||||
// public accessors in multiple forms.
|
||||
|
||||
#import <string>
|
||||
|
||||
class Widget {
|
||||
public:
|
||||
Widget(int number, const std::string& name);
|
||||
~Widget();
|
||||
|
||||
// Public accessors to number data
|
||||
float GetFloatValue() const;
|
||||
int GetIntValue() const;
|
||||
|
||||
// Public accessors to the string data
|
||||
std::string GetStringValue() const;
|
||||
void GetCharPtrValue(char* buffer, size_t max_size) const;
|
||||
|
||||
private:
|
||||
// Data members
|
||||
float number_;
|
||||
std::string name_;
|
||||
};
|
||||
// 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.
|
||||
//
|
||||
// Author: preston.jackson@gmail.com (Preston Jackson)
|
||||
//
|
||||
// Google Test - FrameworkSample
|
||||
// widget.h
|
||||
//
|
||||
|
||||
// Widget is a very simple class used for demonstrating the use of gtest. It
|
||||
// simply stores two values a string and an integer, which are returned via
|
||||
// public accessors in multiple forms.
|
||||
|
||||
#import <string>
|
||||
|
||||
class Widget {
|
||||
public:
|
||||
Widget(int number, const std::string& name);
|
||||
~Widget();
|
||||
|
||||
// Public accessors to number data
|
||||
float GetFloatValue() const;
|
||||
int GetIntValue() const;
|
||||
|
||||
// Public accessors to the string data
|
||||
std::string GetStringValue() const;
|
||||
void GetCharPtrValue(char* buffer, size_t max_size) const;
|
||||
|
||||
private:
|
||||
// Data members
|
||||
float number_;
|
||||
std::string name_;
|
||||
};
|
||||
|
||||
@@ -1,71 +1,71 @@
|
||||
#/usr/bin/python
|
||||
|
||||
"""A script to prepare version informtion for use the gtest Info.plist file.
|
||||
|
||||
This script extracts the version information from the configure.ac file and
|
||||
uses it to generate a header file containing the same information. The
|
||||
#defines in this header file will be included in during the generation of
|
||||
the Info.plist of the framework, giving the correct value to the version
|
||||
shown in the Finder.
|
||||
|
||||
This script makes the following assumptions (these are faults of the script,
|
||||
not problems with the Autoconf):
|
||||
1. The AC_INIT macro will be contained within the first 1024 characters
|
||||
of configure.ac
|
||||
2. The version string will be 3 integers separated by periods and will be
|
||||
surrounded by squre brackets, "[" and "]" (e.g. [1.0.1]). The first
|
||||
segment represents the major version, the second represents the minor
|
||||
version and the third represents the fix version.
|
||||
3. No ")" character exists between the opening "(" and closing ")" of
|
||||
AC_INIT, including in comments and character strings.
|
||||
"""
|
||||
|
||||
import sys
|
||||
import re
|
||||
|
||||
# Read the command line argument (the output directory for Version.h)
|
||||
if (len(sys.argv) < 3):
|
||||
print "Usage: /usr/bin/python versiongenerate.py input_dir output_dir"
|
||||
sys.exit(1)
|
||||
else:
|
||||
input_dir = sys.argv[1]
|
||||
output_dir = sys.argv[2]
|
||||
|
||||
# Read the first 1024 characters of the configure.ac file
|
||||
config_file = open("%s/configure.ac" % input_dir, 'r')
|
||||
buffer_size = 1024
|
||||
opening_string = config_file.read(buffer_size)
|
||||
config_file.close()
|
||||
|
||||
# Extract the version string from the AC_INIT macro
|
||||
# The following init_expression means:
|
||||
# Extract three integers separated by periods and surrounded by squre
|
||||
# brackets(e.g. "[1.0.1]") between "AC_INIT(" and ")". Do not be greedy
|
||||
# (*? is the non-greedy flag) since that would pull in everything between
|
||||
# the first "(" and the last ")" in the file.
|
||||
version_expression = re.compile(r"AC_INIT\(.*?\[(\d+)\.(\d+)\.(\d+)\].*?\)",
|
||||
re.DOTALL)
|
||||
version_values = version_expression.search(opening_string)
|
||||
major_version = version_values.group(1)
|
||||
minor_version = version_values.group(2)
|
||||
fix_version = version_values.group(3)
|
||||
|
||||
# Write the version information to a header file to be included in the
|
||||
# Info.plist file.
|
||||
file_data = """//
|
||||
// DO NOT MODIFY THIS FILE (but you can delete it)
|
||||
//
|
||||
// This file is autogenerated by the versiongenerate.py script. This script
|
||||
// is executed in a "Run Script" build phase when creating gtest.framework. This
|
||||
// header file is not used during compilation of C-source. Rather, it simply
|
||||
// defines some version strings for substitution in the Info.plist. Because of
|
||||
// this, we are not not restricted to C-syntax nor are we using include guards.
|
||||
//
|
||||
|
||||
#define GTEST_VERSIONINFO_SHORT %s.%s
|
||||
#define GTEST_VERSIONINFO_LONG %s.%s.%s
|
||||
|
||||
""" % (major_version, minor_version, major_version, minor_version, fix_version)
|
||||
version_file = open("%s/Version.h" % output_dir, 'w')
|
||||
version_file.write(file_data)
|
||||
version_file.close()
|
||||
#/usr/bin/python
|
||||
|
||||
"""A script to prepare version informtion for use the gtest Info.plist file.
|
||||
|
||||
This script extracts the version information from the configure.ac file and
|
||||
uses it to generate a header file containing the same information. The
|
||||
#defines in this header file will be included in during the generation of
|
||||
the Info.plist of the framework, giving the correct value to the version
|
||||
shown in the Finder.
|
||||
|
||||
This script makes the following assumptions (these are faults of the script,
|
||||
not problems with the Autoconf):
|
||||
1. The AC_INIT macro will be contained within the first 1024 characters
|
||||
of configure.ac
|
||||
2. The version string will be 3 integers separated by periods and will be
|
||||
surrounded by squre brackets, "[" and "]" (e.g. [1.0.1]). The first
|
||||
segment represents the major version, the second represents the minor
|
||||
version and the third represents the fix version.
|
||||
3. No ")" character exists between the opening "(" and closing ")" of
|
||||
AC_INIT, including in comments and character strings.
|
||||
"""
|
||||
|
||||
import sys
|
||||
import re
|
||||
|
||||
# Read the command line argument (the output directory for Version.h)
|
||||
if (len(sys.argv) < 3):
|
||||
print "Usage: /usr/bin/python versiongenerate.py input_dir output_dir"
|
||||
sys.exit(1)
|
||||
else:
|
||||
input_dir = sys.argv[1]
|
||||
output_dir = sys.argv[2]
|
||||
|
||||
# Read the first 1024 characters of the configure.ac file
|
||||
config_file = open("%s/configure.ac" % input_dir, 'r')
|
||||
buffer_size = 1024
|
||||
opening_string = config_file.read(buffer_size)
|
||||
config_file.close()
|
||||
|
||||
# Extract the version string from the AC_INIT macro
|
||||
# The following init_expression means:
|
||||
# Extract three integers separated by periods and surrounded by squre
|
||||
# brackets(e.g. "[1.0.1]") between "AC_INIT(" and ")". Do not be greedy
|
||||
# (*? is the non-greedy flag) since that would pull in everything between
|
||||
# the first "(" and the last ")" in the file.
|
||||
version_expression = re.compile(r"AC_INIT\(.*?\[(\d+)\.(\d+)\.(\d+)\].*?\)",
|
||||
re.DOTALL)
|
||||
version_values = version_expression.search(opening_string)
|
||||
major_version = version_values.group(1)
|
||||
minor_version = version_values.group(2)
|
||||
fix_version = version_values.group(3)
|
||||
|
||||
# Write the version information to a header file to be included in the
|
||||
# Info.plist file.
|
||||
file_data = """//
|
||||
// DO NOT MODIFY THIS FILE (but you can delete it)
|
||||
//
|
||||
// This file is autogenerated by the versiongenerate.py script. This script
|
||||
// is executed in a "Run Script" build phase when creating gtest.framework. This
|
||||
// header file is not used during compilation of C-source. Rather, it simply
|
||||
// defines some version strings for substitution in the Info.plist. Because of
|
||||
// this, we are not not restricted to C-syntax nor are we using include guards.
|
||||
//
|
||||
|
||||
#define GTEST_VERSIONINFO_SHORT %s.%s
|
||||
#define GTEST_VERSIONINFO_LONG %s.%s.%s
|
||||
|
||||
""" % (major_version, minor_version, major_version, minor_version, fix_version)
|
||||
version_file = open("%s/Version.h" % output_dir, 'w')
|
||||
version_file.write(file_data)
|
||||
version_file.close()
|
||||
|
||||
+9
-9
@@ -1,9 +1,9 @@
|
||||
/* protobuf config.h for SNC compiler on PS3. On other platforms, this is generated
|
||||
* automatically by autoheader / autoconf / configure. */
|
||||
|
||||
/* define if you want to use pthreads */
|
||||
#define HAVE_PTHREAD 1
|
||||
|
||||
/* define if you want to use zlib. See readme.txt for additional
|
||||
* requirements. */
|
||||
// #define HAVE_ZLIB 1
|
||||
/* protobuf config.h for SNC compiler on PS3. On other platforms, this is generated
|
||||
* automatically by autoheader / autoconf / configure. */
|
||||
|
||||
/* define if you want to use pthreads */
|
||||
#define HAVE_PTHREAD 1
|
||||
|
||||
/* define if you want to use zlib. See readme.txt for additional
|
||||
* requirements. */
|
||||
// #define HAVE_ZLIB 1
|
||||
|
||||
+281
-281
@@ -1,281 +1,281 @@
|
||||
#!python
|
||||
|
||||
# This file was obtained from:
|
||||
# http://peak.telecommunity.com/dist/ez_setup.py
|
||||
# on 2009/4/17.
|
||||
|
||||
"""Bootstrap setuptools installation
|
||||
|
||||
If you want to use setuptools in your package's setup.py, just include this
|
||||
file in the same directory with it, and add this to the top of your setup.py::
|
||||
|
||||
from ez_setup import use_setuptools
|
||||
use_setuptools()
|
||||
|
||||
If you want to require a specific version of setuptools, set a download
|
||||
mirror, or use an alternate download directory, you can do so by supplying
|
||||
the appropriate options to ``use_setuptools()``.
|
||||
|
||||
This file can also be run as a script to install or upgrade setuptools.
|
||||
"""
|
||||
import sys
|
||||
DEFAULT_VERSION = "0.6c9"
|
||||
DEFAULT_URL = "http://pypi.python.org/packages/%s/s/setuptools/" % sys.version[:3]
|
||||
|
||||
md5_data = {
|
||||
'setuptools-0.6b1-py2.3.egg': '8822caf901250d848b996b7f25c6e6ca',
|
||||
'setuptools-0.6b1-py2.4.egg': 'b79a8a403e4502fbb85ee3f1941735cb',
|
||||
'setuptools-0.6b2-py2.3.egg': '5657759d8a6d8fc44070a9d07272d99b',
|
||||
'setuptools-0.6b2-py2.4.egg': '4996a8d169d2be661fa32a6e52e4f82a',
|
||||
'setuptools-0.6b3-py2.3.egg': 'bb31c0fc7399a63579975cad9f5a0618',
|
||||
'setuptools-0.6b3-py2.4.egg': '38a8c6b3d6ecd22247f179f7da669fac',
|
||||
'setuptools-0.6b4-py2.3.egg': '62045a24ed4e1ebc77fe039aa4e6f7e5',
|
||||
'setuptools-0.6b4-py2.4.egg': '4cb2a185d228dacffb2d17f103b3b1c4',
|
||||
'setuptools-0.6c1-py2.3.egg': 'b3f2b5539d65cb7f74ad79127f1a908c',
|
||||
'setuptools-0.6c1-py2.4.egg': 'b45adeda0667d2d2ffe14009364f2a4b',
|
||||
'setuptools-0.6c2-py2.3.egg': 'f0064bf6aa2b7d0f3ba0b43f20817c27',
|
||||
'setuptools-0.6c2-py2.4.egg': '616192eec35f47e8ea16cd6a122b7277',
|
||||
'setuptools-0.6c3-py2.3.egg': 'f181fa125dfe85a259c9cd6f1d7b78fa',
|
||||
'setuptools-0.6c3-py2.4.egg': 'e0ed74682c998bfb73bf803a50e7b71e',
|
||||
'setuptools-0.6c3-py2.5.egg': 'abef16fdd61955514841c7c6bd98965e',
|
||||
'setuptools-0.6c4-py2.3.egg': 'b0b9131acab32022bfac7f44c5d7971f',
|
||||
'setuptools-0.6c4-py2.4.egg': '2a1f9656d4fbf3c97bf946c0a124e6e2',
|
||||
'setuptools-0.6c4-py2.5.egg': '8f5a052e32cdb9c72bcf4b5526f28afc',
|
||||
'setuptools-0.6c5-py2.3.egg': 'ee9fd80965da04f2f3e6b3576e9d8167',
|
||||
'setuptools-0.6c5-py2.4.egg': 'afe2adf1c01701ee841761f5bcd8aa64',
|
||||
'setuptools-0.6c5-py2.5.egg': 'a8d3f61494ccaa8714dfed37bccd3d5d',
|
||||
'setuptools-0.6c6-py2.3.egg': '35686b78116a668847237b69d549ec20',
|
||||
'setuptools-0.6c6-py2.4.egg': '3c56af57be3225019260a644430065ab',
|
||||
'setuptools-0.6c6-py2.5.egg': 'b2f8a7520709a5b34f80946de5f02f53',
|
||||
'setuptools-0.6c7-py2.3.egg': '209fdf9adc3a615e5115b725658e13e2',
|
||||
'setuptools-0.6c7-py2.4.egg': '5a8f954807d46a0fb67cf1f26c55a82e',
|
||||
'setuptools-0.6c7-py2.5.egg': '45d2ad28f9750e7434111fde831e8372',
|
||||
'setuptools-0.6c8-py2.3.egg': '50759d29b349db8cfd807ba8303f1902',
|
||||
'setuptools-0.6c8-py2.4.egg': 'cba38d74f7d483c06e9daa6070cce6de',
|
||||
'setuptools-0.6c8-py2.5.egg': '1721747ee329dc150590a58b3e1ac95b',
|
||||
'setuptools-0.6c9-py2.3.egg': 'a83c4020414807b496e4cfbe08507c03',
|
||||
'setuptools-0.6c9-py2.4.egg': '260a2be2e5388d66bdaee06abec6342a',
|
||||
'setuptools-0.6c9-py2.5.egg': 'fe67c3e5a17b12c0e7c541b7ea43a8e6',
|
||||
'setuptools-0.6c9-py2.6.egg': 'ca37b1ff16fa2ede6e19383e7b59245a',
|
||||
}
|
||||
|
||||
import sys, os
|
||||
try: from hashlib import md5
|
||||
except ImportError: from md5 import md5
|
||||
|
||||
def _validate_md5(egg_name, data):
|
||||
if egg_name in md5_data:
|
||||
digest = md5(data).hexdigest()
|
||||
if digest != md5_data[egg_name]:
|
||||
print >>sys.stderr, (
|
||||
"md5 validation of %s failed! (Possible download problem?)"
|
||||
% egg_name
|
||||
)
|
||||
sys.exit(2)
|
||||
return data
|
||||
|
||||
def use_setuptools(
|
||||
version=DEFAULT_VERSION, download_base=DEFAULT_URL, to_dir=os.curdir,
|
||||
download_delay=15
|
||||
):
|
||||
"""Automatically find/download setuptools and make it available on sys.path
|
||||
|
||||
`version` should be a valid setuptools version number that is available
|
||||
as an egg for download under the `download_base` URL (which should end with
|
||||
a '/'). `to_dir` is the directory where setuptools will be downloaded, if
|
||||
it is not already available. If `download_delay` is specified, it should
|
||||
be the number of seconds that will be paused before initiating a download,
|
||||
should one be required. If an older version of setuptools is installed,
|
||||
this routine will print a message to ``sys.stderr`` and raise SystemExit in
|
||||
an attempt to abort the calling script.
|
||||
"""
|
||||
was_imported = 'pkg_resources' in sys.modules or 'setuptools' in sys.modules
|
||||
def do_download():
|
||||
egg = download_setuptools(version, download_base, to_dir, download_delay)
|
||||
sys.path.insert(0, egg)
|
||||
import setuptools; setuptools.bootstrap_install_from = egg
|
||||
try:
|
||||
import pkg_resources
|
||||
except ImportError:
|
||||
return do_download()
|
||||
try:
|
||||
pkg_resources.require("setuptools>="+version); return
|
||||
except pkg_resources.VersionConflict, e:
|
||||
if was_imported:
|
||||
print >>sys.stderr, (
|
||||
"The required version of setuptools (>=%s) is not available, and\n"
|
||||
"can't be installed while this script is running. Please install\n"
|
||||
" a more recent version first, using 'easy_install -U setuptools'."
|
||||
"\n\n(Currently using %r)"
|
||||
) % (version, e.args[0])
|
||||
sys.exit(2)
|
||||
else:
|
||||
del pkg_resources, sys.modules['pkg_resources'] # reload ok
|
||||
return do_download()
|
||||
except pkg_resources.DistributionNotFound:
|
||||
return do_download()
|
||||
|
||||
def download_setuptools(
|
||||
version=DEFAULT_VERSION, download_base=DEFAULT_URL, to_dir=os.curdir,
|
||||
delay = 15
|
||||
):
|
||||
"""Download setuptools from a specified location and return its filename
|
||||
|
||||
`version` should be a valid setuptools version number that is available
|
||||
as an egg for download under the `download_base` URL (which should end
|
||||
with a '/'). `to_dir` is the directory where the egg will be downloaded.
|
||||
`delay` is the number of seconds to pause before an actual download attempt.
|
||||
"""
|
||||
import urllib2, shutil
|
||||
egg_name = "setuptools-%s-py%s.egg" % (version,sys.version[:3])
|
||||
url = download_base + egg_name
|
||||
saveto = os.path.join(to_dir, egg_name)
|
||||
src = dst = None
|
||||
if not os.path.exists(saveto): # Avoid repeated downloads
|
||||
try:
|
||||
from distutils import log
|
||||
if delay:
|
||||
log.warn("""
|
||||
---------------------------------------------------------------------------
|
||||
This script requires setuptools version %s to run (even to display
|
||||
help). I will attempt to download it for you (from
|
||||
%s), but
|
||||
you may need to enable firewall access for this script first.
|
||||
I will start the download in %d seconds.
|
||||
|
||||
(Note: if this machine does not have network access, please obtain the file
|
||||
|
||||
%s
|
||||
|
||||
and place it in this directory before rerunning this script.)
|
||||
---------------------------------------------------------------------------""",
|
||||
version, download_base, delay, url
|
||||
); from time import sleep; sleep(delay)
|
||||
log.warn("Downloading %s", url)
|
||||
src = urllib2.urlopen(url)
|
||||
# Read/write all in one block, so we don't create a corrupt file
|
||||
# if the download is interrupted.
|
||||
data = _validate_md5(egg_name, src.read())
|
||||
dst = open(saveto,"wb"); dst.write(data)
|
||||
finally:
|
||||
if src: src.close()
|
||||
if dst: dst.close()
|
||||
return os.path.realpath(saveto)
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
def main(argv, version=DEFAULT_VERSION):
|
||||
"""Install or upgrade setuptools and EasyInstall"""
|
||||
try:
|
||||
import setuptools
|
||||
except ImportError:
|
||||
egg = None
|
||||
try:
|
||||
egg = download_setuptools(version, delay=0)
|
||||
sys.path.insert(0,egg)
|
||||
from setuptools.command.easy_install import main
|
||||
return main(list(argv)+[egg]) # we're done here
|
||||
finally:
|
||||
if egg and os.path.exists(egg):
|
||||
os.unlink(egg)
|
||||
else:
|
||||
if setuptools.__version__ == '0.0.1':
|
||||
print >>sys.stderr, (
|
||||
"You have an obsolete version of setuptools installed. Please\n"
|
||||
"remove it from your system entirely before rerunning this script."
|
||||
)
|
||||
sys.exit(2)
|
||||
|
||||
req = "setuptools>="+version
|
||||
import pkg_resources
|
||||
try:
|
||||
pkg_resources.require(req)
|
||||
except pkg_resources.VersionConflict:
|
||||
try:
|
||||
from setuptools.command.easy_install import main
|
||||
except ImportError:
|
||||
from easy_install import main
|
||||
main(list(argv)+[download_setuptools(delay=0)])
|
||||
sys.exit(0) # try to force an exit
|
||||
else:
|
||||
if argv:
|
||||
from setuptools.command.easy_install import main
|
||||
main(argv)
|
||||
else:
|
||||
print "Setuptools version",version,"or greater has been installed."
|
||||
print '(Run "ez_setup.py -U setuptools" to reinstall or upgrade.)'
|
||||
|
||||
def update_md5(filenames):
|
||||
"""Update our built-in md5 registry"""
|
||||
|
||||
import re
|
||||
|
||||
for name in filenames:
|
||||
base = os.path.basename(name)
|
||||
f = open(name,'rb')
|
||||
md5_data[base] = md5(f.read()).hexdigest()
|
||||
f.close()
|
||||
|
||||
data = [" %r: %r,\n" % it for it in md5_data.items()]
|
||||
data.sort()
|
||||
repl = "".join(data)
|
||||
|
||||
import inspect
|
||||
srcfile = inspect.getsourcefile(sys.modules[__name__])
|
||||
f = open(srcfile, 'rb'); src = f.read(); f.close()
|
||||
|
||||
match = re.search("\nmd5_data = {\n([^}]+)}", src)
|
||||
if not match:
|
||||
print >>sys.stderr, "Internal error!"
|
||||
sys.exit(2)
|
||||
|
||||
src = src[:match.start(1)] + repl + src[match.end(1):]
|
||||
f = open(srcfile,'w')
|
||||
f.write(src)
|
||||
f.close()
|
||||
|
||||
|
||||
if __name__=='__main__':
|
||||
if len(sys.argv)>2 and sys.argv[1]=='--md5update':
|
||||
update_md5(sys.argv[2:])
|
||||
else:
|
||||
main(sys.argv[1:])
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
#!python
|
||||
|
||||
# This file was obtained from:
|
||||
# http://peak.telecommunity.com/dist/ez_setup.py
|
||||
# on 2009/4/17.
|
||||
|
||||
"""Bootstrap setuptools installation
|
||||
|
||||
If you want to use setuptools in your package's setup.py, just include this
|
||||
file in the same directory with it, and add this to the top of your setup.py::
|
||||
|
||||
from ez_setup import use_setuptools
|
||||
use_setuptools()
|
||||
|
||||
If you want to require a specific version of setuptools, set a download
|
||||
mirror, or use an alternate download directory, you can do so by supplying
|
||||
the appropriate options to ``use_setuptools()``.
|
||||
|
||||
This file can also be run as a script to install or upgrade setuptools.
|
||||
"""
|
||||
import sys
|
||||
DEFAULT_VERSION = "0.6c9"
|
||||
DEFAULT_URL = "http://pypi.python.org/packages/%s/s/setuptools/" % sys.version[:3]
|
||||
|
||||
md5_data = {
|
||||
'setuptools-0.6b1-py2.3.egg': '8822caf901250d848b996b7f25c6e6ca',
|
||||
'setuptools-0.6b1-py2.4.egg': 'b79a8a403e4502fbb85ee3f1941735cb',
|
||||
'setuptools-0.6b2-py2.3.egg': '5657759d8a6d8fc44070a9d07272d99b',
|
||||
'setuptools-0.6b2-py2.4.egg': '4996a8d169d2be661fa32a6e52e4f82a',
|
||||
'setuptools-0.6b3-py2.3.egg': 'bb31c0fc7399a63579975cad9f5a0618',
|
||||
'setuptools-0.6b3-py2.4.egg': '38a8c6b3d6ecd22247f179f7da669fac',
|
||||
'setuptools-0.6b4-py2.3.egg': '62045a24ed4e1ebc77fe039aa4e6f7e5',
|
||||
'setuptools-0.6b4-py2.4.egg': '4cb2a185d228dacffb2d17f103b3b1c4',
|
||||
'setuptools-0.6c1-py2.3.egg': 'b3f2b5539d65cb7f74ad79127f1a908c',
|
||||
'setuptools-0.6c1-py2.4.egg': 'b45adeda0667d2d2ffe14009364f2a4b',
|
||||
'setuptools-0.6c2-py2.3.egg': 'f0064bf6aa2b7d0f3ba0b43f20817c27',
|
||||
'setuptools-0.6c2-py2.4.egg': '616192eec35f47e8ea16cd6a122b7277',
|
||||
'setuptools-0.6c3-py2.3.egg': 'f181fa125dfe85a259c9cd6f1d7b78fa',
|
||||
'setuptools-0.6c3-py2.4.egg': 'e0ed74682c998bfb73bf803a50e7b71e',
|
||||
'setuptools-0.6c3-py2.5.egg': 'abef16fdd61955514841c7c6bd98965e',
|
||||
'setuptools-0.6c4-py2.3.egg': 'b0b9131acab32022bfac7f44c5d7971f',
|
||||
'setuptools-0.6c4-py2.4.egg': '2a1f9656d4fbf3c97bf946c0a124e6e2',
|
||||
'setuptools-0.6c4-py2.5.egg': '8f5a052e32cdb9c72bcf4b5526f28afc',
|
||||
'setuptools-0.6c5-py2.3.egg': 'ee9fd80965da04f2f3e6b3576e9d8167',
|
||||
'setuptools-0.6c5-py2.4.egg': 'afe2adf1c01701ee841761f5bcd8aa64',
|
||||
'setuptools-0.6c5-py2.5.egg': 'a8d3f61494ccaa8714dfed37bccd3d5d',
|
||||
'setuptools-0.6c6-py2.3.egg': '35686b78116a668847237b69d549ec20',
|
||||
'setuptools-0.6c6-py2.4.egg': '3c56af57be3225019260a644430065ab',
|
||||
'setuptools-0.6c6-py2.5.egg': 'b2f8a7520709a5b34f80946de5f02f53',
|
||||
'setuptools-0.6c7-py2.3.egg': '209fdf9adc3a615e5115b725658e13e2',
|
||||
'setuptools-0.6c7-py2.4.egg': '5a8f954807d46a0fb67cf1f26c55a82e',
|
||||
'setuptools-0.6c7-py2.5.egg': '45d2ad28f9750e7434111fde831e8372',
|
||||
'setuptools-0.6c8-py2.3.egg': '50759d29b349db8cfd807ba8303f1902',
|
||||
'setuptools-0.6c8-py2.4.egg': 'cba38d74f7d483c06e9daa6070cce6de',
|
||||
'setuptools-0.6c8-py2.5.egg': '1721747ee329dc150590a58b3e1ac95b',
|
||||
'setuptools-0.6c9-py2.3.egg': 'a83c4020414807b496e4cfbe08507c03',
|
||||
'setuptools-0.6c9-py2.4.egg': '260a2be2e5388d66bdaee06abec6342a',
|
||||
'setuptools-0.6c9-py2.5.egg': 'fe67c3e5a17b12c0e7c541b7ea43a8e6',
|
||||
'setuptools-0.6c9-py2.6.egg': 'ca37b1ff16fa2ede6e19383e7b59245a',
|
||||
}
|
||||
|
||||
import sys, os
|
||||
try: from hashlib import md5
|
||||
except ImportError: from md5 import md5
|
||||
|
||||
def _validate_md5(egg_name, data):
|
||||
if egg_name in md5_data:
|
||||
digest = md5(data).hexdigest()
|
||||
if digest != md5_data[egg_name]:
|
||||
print >>sys.stderr, (
|
||||
"md5 validation of %s failed! (Possible download problem?)"
|
||||
% egg_name
|
||||
)
|
||||
sys.exit(2)
|
||||
return data
|
||||
|
||||
def use_setuptools(
|
||||
version=DEFAULT_VERSION, download_base=DEFAULT_URL, to_dir=os.curdir,
|
||||
download_delay=15
|
||||
):
|
||||
"""Automatically find/download setuptools and make it available on sys.path
|
||||
|
||||
`version` should be a valid setuptools version number that is available
|
||||
as an egg for download under the `download_base` URL (which should end with
|
||||
a '/'). `to_dir` is the directory where setuptools will be downloaded, if
|
||||
it is not already available. If `download_delay` is specified, it should
|
||||
be the number of seconds that will be paused before initiating a download,
|
||||
should one be required. If an older version of setuptools is installed,
|
||||
this routine will print a message to ``sys.stderr`` and raise SystemExit in
|
||||
an attempt to abort the calling script.
|
||||
"""
|
||||
was_imported = 'pkg_resources' in sys.modules or 'setuptools' in sys.modules
|
||||
def do_download():
|
||||
egg = download_setuptools(version, download_base, to_dir, download_delay)
|
||||
sys.path.insert(0, egg)
|
||||
import setuptools; setuptools.bootstrap_install_from = egg
|
||||
try:
|
||||
import pkg_resources
|
||||
except ImportError:
|
||||
return do_download()
|
||||
try:
|
||||
pkg_resources.require("setuptools>="+version); return
|
||||
except pkg_resources.VersionConflict, e:
|
||||
if was_imported:
|
||||
print >>sys.stderr, (
|
||||
"The required version of setuptools (>=%s) is not available, and\n"
|
||||
"can't be installed while this script is running. Please install\n"
|
||||
" a more recent version first, using 'easy_install -U setuptools'."
|
||||
"\n\n(Currently using %r)"
|
||||
) % (version, e.args[0])
|
||||
sys.exit(2)
|
||||
else:
|
||||
del pkg_resources, sys.modules['pkg_resources'] # reload ok
|
||||
return do_download()
|
||||
except pkg_resources.DistributionNotFound:
|
||||
return do_download()
|
||||
|
||||
def download_setuptools(
|
||||
version=DEFAULT_VERSION, download_base=DEFAULT_URL, to_dir=os.curdir,
|
||||
delay = 15
|
||||
):
|
||||
"""Download setuptools from a specified location and return its filename
|
||||
|
||||
`version` should be a valid setuptools version number that is available
|
||||
as an egg for download under the `download_base` URL (which should end
|
||||
with a '/'). `to_dir` is the directory where the egg will be downloaded.
|
||||
`delay` is the number of seconds to pause before an actual download attempt.
|
||||
"""
|
||||
import urllib2, shutil
|
||||
egg_name = "setuptools-%s-py%s.egg" % (version,sys.version[:3])
|
||||
url = download_base + egg_name
|
||||
saveto = os.path.join(to_dir, egg_name)
|
||||
src = dst = None
|
||||
if not os.path.exists(saveto): # Avoid repeated downloads
|
||||
try:
|
||||
from distutils import log
|
||||
if delay:
|
||||
log.warn("""
|
||||
---------------------------------------------------------------------------
|
||||
This script requires setuptools version %s to run (even to display
|
||||
help). I will attempt to download it for you (from
|
||||
%s), but
|
||||
you may need to enable firewall access for this script first.
|
||||
I will start the download in %d seconds.
|
||||
|
||||
(Note: if this machine does not have network access, please obtain the file
|
||||
|
||||
%s
|
||||
|
||||
and place it in this directory before rerunning this script.)
|
||||
---------------------------------------------------------------------------""",
|
||||
version, download_base, delay, url
|
||||
); from time import sleep; sleep(delay)
|
||||
log.warn("Downloading %s", url)
|
||||
src = urllib2.urlopen(url)
|
||||
# Read/write all in one block, so we don't create a corrupt file
|
||||
# if the download is interrupted.
|
||||
data = _validate_md5(egg_name, src.read())
|
||||
dst = open(saveto,"wb"); dst.write(data)
|
||||
finally:
|
||||
if src: src.close()
|
||||
if dst: dst.close()
|
||||
return os.path.realpath(saveto)
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
def main(argv, version=DEFAULT_VERSION):
|
||||
"""Install or upgrade setuptools and EasyInstall"""
|
||||
try:
|
||||
import setuptools
|
||||
except ImportError:
|
||||
egg = None
|
||||
try:
|
||||
egg = download_setuptools(version, delay=0)
|
||||
sys.path.insert(0,egg)
|
||||
from setuptools.command.easy_install import main
|
||||
return main(list(argv)+[egg]) # we're done here
|
||||
finally:
|
||||
if egg and os.path.exists(egg):
|
||||
os.unlink(egg)
|
||||
else:
|
||||
if setuptools.__version__ == '0.0.1':
|
||||
print >>sys.stderr, (
|
||||
"You have an obsolete version of setuptools installed. Please\n"
|
||||
"remove it from your system entirely before rerunning this script."
|
||||
)
|
||||
sys.exit(2)
|
||||
|
||||
req = "setuptools>="+version
|
||||
import pkg_resources
|
||||
try:
|
||||
pkg_resources.require(req)
|
||||
except pkg_resources.VersionConflict:
|
||||
try:
|
||||
from setuptools.command.easy_install import main
|
||||
except ImportError:
|
||||
from easy_install import main
|
||||
main(list(argv)+[download_setuptools(delay=0)])
|
||||
sys.exit(0) # try to force an exit
|
||||
else:
|
||||
if argv:
|
||||
from setuptools.command.easy_install import main
|
||||
main(argv)
|
||||
else:
|
||||
print "Setuptools version",version,"or greater has been installed."
|
||||
print '(Run "ez_setup.py -U setuptools" to reinstall or upgrade.)'
|
||||
|
||||
def update_md5(filenames):
|
||||
"""Update our built-in md5 registry"""
|
||||
|
||||
import re
|
||||
|
||||
for name in filenames:
|
||||
base = os.path.basename(name)
|
||||
f = open(name,'rb')
|
||||
md5_data[base] = md5(f.read()).hexdigest()
|
||||
f.close()
|
||||
|
||||
data = [" %r: %r,\n" % it for it in md5_data.items()]
|
||||
data.sort()
|
||||
repl = "".join(data)
|
||||
|
||||
import inspect
|
||||
srcfile = inspect.getsourcefile(sys.modules[__name__])
|
||||
f = open(srcfile, 'rb'); src = f.read(); f.close()
|
||||
|
||||
match = re.search("\nmd5_data = {\n([^}]+)}", src)
|
||||
if not match:
|
||||
print >>sys.stderr, "Internal error!"
|
||||
sys.exit(2)
|
||||
|
||||
src = src[:match.start(1)] + repl + src[match.end(1):]
|
||||
f = open(srcfile,'w')
|
||||
f.write(src)
|
||||
f.close()
|
||||
|
||||
|
||||
if __name__=='__main__':
|
||||
if len(sys.argv)>2 and sys.argv[1]=='--md5update':
|
||||
update_md5(sys.argv[2:])
|
||||
else:
|
||||
main(sys.argv[1:])
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -1 +1 @@
|
||||
__import__('pkg_resources').declare_namespace(__name__)
|
||||
__import__('pkg_resources').declare_namespace(__name__)
|
||||
|
||||
+590
-590
File diff suppressed because it is too large
Load Diff
+244
-244
@@ -1,244 +1,244 @@
|
||||
# Protocol Buffers - Google's data interchange format
|
||||
# Copyright 2008 Google Inc. All rights reserved.
|
||||
# http://code.google.com/p/protobuf/
|
||||
#
|
||||
# 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.
|
||||
|
||||
"""Contains container classes to represent different protocol buffer types.
|
||||
|
||||
This file defines container classes which represent categories of protocol
|
||||
buffer field types which need extra maintenance. Currently these categories
|
||||
are:
|
||||
- Repeated scalar fields - These are all repeated fields which aren't
|
||||
composite (e.g. they are of simple types like int32, string, etc).
|
||||
- Repeated composite fields - Repeated fields which are composite. This
|
||||
includes groups and nested messages.
|
||||
"""
|
||||
|
||||
__author__ = 'petar@google.com (Petar Petrov)'
|
||||
|
||||
|
||||
class BaseContainer(object):
|
||||
|
||||
"""Base container class."""
|
||||
|
||||
# Minimizes memory usage and disallows assignment to other attributes.
|
||||
__slots__ = ['_message_listener', '_values']
|
||||
|
||||
def __init__(self, message_listener):
|
||||
"""
|
||||
Args:
|
||||
message_listener: A MessageListener implementation.
|
||||
The RepeatedScalarFieldContainer will call this object's
|
||||
Modified() method when it is modified.
|
||||
"""
|
||||
self._message_listener = message_listener
|
||||
self._values = []
|
||||
|
||||
def __getitem__(self, key):
|
||||
"""Retrieves item by the specified key."""
|
||||
return self._values[key]
|
||||
|
||||
def __len__(self):
|
||||
"""Returns the number of elements in the container."""
|
||||
return len(self._values)
|
||||
|
||||
def __ne__(self, other):
|
||||
"""Checks if another instance isn't equal to this one."""
|
||||
# The concrete classes should define __eq__.
|
||||
return not self == other
|
||||
|
||||
def __repr__(self):
|
||||
return repr(self._values)
|
||||
|
||||
|
||||
class RepeatedScalarFieldContainer(BaseContainer):
|
||||
|
||||
"""Simple, type-checked, list-like container for holding repeated scalars."""
|
||||
|
||||
# Disallows assignment to other attributes.
|
||||
__slots__ = ['_type_checker']
|
||||
|
||||
def __init__(self, message_listener, type_checker):
|
||||
"""
|
||||
Args:
|
||||
message_listener: A MessageListener implementation.
|
||||
The RepeatedScalarFieldContainer will call this object's
|
||||
Modified() method when it is modified.
|
||||
type_checker: A type_checkers.ValueChecker instance to run on elements
|
||||
inserted into this container.
|
||||
"""
|
||||
super(RepeatedScalarFieldContainer, self).__init__(message_listener)
|
||||
self._type_checker = type_checker
|
||||
|
||||
def append(self, value):
|
||||
"""Appends an item to the list. Similar to list.append()."""
|
||||
self._type_checker.CheckValue(value)
|
||||
self._values.append(value)
|
||||
if not self._message_listener.dirty:
|
||||
self._message_listener.Modified()
|
||||
|
||||
def insert(self, key, value):
|
||||
"""Inserts the item at the specified position. Similar to list.insert()."""
|
||||
self._type_checker.CheckValue(value)
|
||||
self._values.insert(key, value)
|
||||
if not self._message_listener.dirty:
|
||||
self._message_listener.Modified()
|
||||
|
||||
def extend(self, elem_seq):
|
||||
"""Extends by appending the given sequence. Similar to list.extend()."""
|
||||
if not elem_seq:
|
||||
return
|
||||
|
||||
new_values = []
|
||||
for elem in elem_seq:
|
||||
self._type_checker.CheckValue(elem)
|
||||
new_values.append(elem)
|
||||
self._values.extend(new_values)
|
||||
self._message_listener.Modified()
|
||||
|
||||
def MergeFrom(self, other):
|
||||
"""Appends the contents of another repeated field of the same type to this
|
||||
one. We do not check the types of the individual fields.
|
||||
"""
|
||||
self._values.extend(other._values)
|
||||
self._message_listener.Modified()
|
||||
|
||||
def remove(self, elem):
|
||||
"""Removes an item from the list. Similar to list.remove()."""
|
||||
self._values.remove(elem)
|
||||
self._message_listener.Modified()
|
||||
|
||||
def __setitem__(self, key, value):
|
||||
"""Sets the item on the specified position."""
|
||||
self._type_checker.CheckValue(value)
|
||||
self._values[key] = value
|
||||
self._message_listener.Modified()
|
||||
|
||||
def __getslice__(self, start, stop):
|
||||
"""Retrieves the subset of items from between the specified indices."""
|
||||
return self._values[start:stop]
|
||||
|
||||
def __setslice__(self, start, stop, values):
|
||||
"""Sets the subset of items from between the specified indices."""
|
||||
new_values = []
|
||||
for value in values:
|
||||
self._type_checker.CheckValue(value)
|
||||
new_values.append(value)
|
||||
self._values[start:stop] = new_values
|
||||
self._message_listener.Modified()
|
||||
|
||||
def __delitem__(self, key):
|
||||
"""Deletes the item at the specified position."""
|
||||
del self._values[key]
|
||||
self._message_listener.Modified()
|
||||
|
||||
def __delslice__(self, start, stop):
|
||||
"""Deletes the subset of items from between the specified indices."""
|
||||
del self._values[start:stop]
|
||||
self._message_listener.Modified()
|
||||
|
||||
def __eq__(self, other):
|
||||
"""Compares the current instance with another one."""
|
||||
if self is other:
|
||||
return True
|
||||
# Special case for the same type which should be common and fast.
|
||||
if isinstance(other, self.__class__):
|
||||
return other._values == self._values
|
||||
# We are presumably comparing against some other sequence type.
|
||||
return other == self._values
|
||||
|
||||
|
||||
class RepeatedCompositeFieldContainer(BaseContainer):
|
||||
|
||||
"""Simple, list-like container for holding repeated composite fields."""
|
||||
|
||||
# Disallows assignment to other attributes.
|
||||
__slots__ = ['_message_descriptor']
|
||||
|
||||
def __init__(self, message_listener, message_descriptor):
|
||||
"""
|
||||
Note that we pass in a descriptor instead of the generated directly,
|
||||
since at the time we construct a _RepeatedCompositeFieldContainer we
|
||||
haven't yet necessarily initialized the type that will be contained in the
|
||||
container.
|
||||
|
||||
Args:
|
||||
message_listener: A MessageListener implementation.
|
||||
The RepeatedCompositeFieldContainer will call this object's
|
||||
Modified() method when it is modified.
|
||||
message_descriptor: A Descriptor instance describing the protocol type
|
||||
that should be present in this container. We'll use the
|
||||
_concrete_class field of this descriptor when the client calls add().
|
||||
"""
|
||||
super(RepeatedCompositeFieldContainer, self).__init__(message_listener)
|
||||
self._message_descriptor = message_descriptor
|
||||
|
||||
def add(self):
|
||||
new_element = self._message_descriptor._concrete_class()
|
||||
new_element._SetListener(self._message_listener)
|
||||
self._values.append(new_element)
|
||||
if not self._message_listener.dirty:
|
||||
self._message_listener.Modified()
|
||||
return new_element
|
||||
|
||||
def MergeFrom(self, other):
|
||||
"""Appends the contents of another repeated field of the same type to this
|
||||
one, copying each individual message.
|
||||
"""
|
||||
message_class = self._message_descriptor._concrete_class
|
||||
listener = self._message_listener
|
||||
values = self._values
|
||||
for message in other._values:
|
||||
new_element = message_class()
|
||||
new_element._SetListener(listener)
|
||||
new_element.MergeFrom(message)
|
||||
values.append(new_element)
|
||||
listener.Modified()
|
||||
|
||||
def __getslice__(self, start, stop):
|
||||
"""Retrieves the subset of items from between the specified indices."""
|
||||
return self._values[start:stop]
|
||||
|
||||
def __delitem__(self, key):
|
||||
"""Deletes the item at the specified position."""
|
||||
del self._values[key]
|
||||
self._message_listener.Modified()
|
||||
|
||||
def __delslice__(self, start, stop):
|
||||
"""Deletes the subset of items from between the specified indices."""
|
||||
del self._values[start:stop]
|
||||
self._message_listener.Modified()
|
||||
|
||||
def __eq__(self, other):
|
||||
"""Compares the current instance with another one."""
|
||||
if self is other:
|
||||
return True
|
||||
if not isinstance(other, self.__class__):
|
||||
raise TypeError('Can only compare repeated composite fields against '
|
||||
'other repeated composite fields.')
|
||||
return self._values == other._values
|
||||
# Protocol Buffers - Google's data interchange format
|
||||
# Copyright 2008 Google Inc. All rights reserved.
|
||||
# http://code.google.com/p/protobuf/
|
||||
#
|
||||
# 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.
|
||||
|
||||
"""Contains container classes to represent different protocol buffer types.
|
||||
|
||||
This file defines container classes which represent categories of protocol
|
||||
buffer field types which need extra maintenance. Currently these categories
|
||||
are:
|
||||
- Repeated scalar fields - These are all repeated fields which aren't
|
||||
composite (e.g. they are of simple types like int32, string, etc).
|
||||
- Repeated composite fields - Repeated fields which are composite. This
|
||||
includes groups and nested messages.
|
||||
"""
|
||||
|
||||
__author__ = 'petar@google.com (Petar Petrov)'
|
||||
|
||||
|
||||
class BaseContainer(object):
|
||||
|
||||
"""Base container class."""
|
||||
|
||||
# Minimizes memory usage and disallows assignment to other attributes.
|
||||
__slots__ = ['_message_listener', '_values']
|
||||
|
||||
def __init__(self, message_listener):
|
||||
"""
|
||||
Args:
|
||||
message_listener: A MessageListener implementation.
|
||||
The RepeatedScalarFieldContainer will call this object's
|
||||
Modified() method when it is modified.
|
||||
"""
|
||||
self._message_listener = message_listener
|
||||
self._values = []
|
||||
|
||||
def __getitem__(self, key):
|
||||
"""Retrieves item by the specified key."""
|
||||
return self._values[key]
|
||||
|
||||
def __len__(self):
|
||||
"""Returns the number of elements in the container."""
|
||||
return len(self._values)
|
||||
|
||||
def __ne__(self, other):
|
||||
"""Checks if another instance isn't equal to this one."""
|
||||
# The concrete classes should define __eq__.
|
||||
return not self == other
|
||||
|
||||
def __repr__(self):
|
||||
return repr(self._values)
|
||||
|
||||
|
||||
class RepeatedScalarFieldContainer(BaseContainer):
|
||||
|
||||
"""Simple, type-checked, list-like container for holding repeated scalars."""
|
||||
|
||||
# Disallows assignment to other attributes.
|
||||
__slots__ = ['_type_checker']
|
||||
|
||||
def __init__(self, message_listener, type_checker):
|
||||
"""
|
||||
Args:
|
||||
message_listener: A MessageListener implementation.
|
||||
The RepeatedScalarFieldContainer will call this object's
|
||||
Modified() method when it is modified.
|
||||
type_checker: A type_checkers.ValueChecker instance to run on elements
|
||||
inserted into this container.
|
||||
"""
|
||||
super(RepeatedScalarFieldContainer, self).__init__(message_listener)
|
||||
self._type_checker = type_checker
|
||||
|
||||
def append(self, value):
|
||||
"""Appends an item to the list. Similar to list.append()."""
|
||||
self._type_checker.CheckValue(value)
|
||||
self._values.append(value)
|
||||
if not self._message_listener.dirty:
|
||||
self._message_listener.Modified()
|
||||
|
||||
def insert(self, key, value):
|
||||
"""Inserts the item at the specified position. Similar to list.insert()."""
|
||||
self._type_checker.CheckValue(value)
|
||||
self._values.insert(key, value)
|
||||
if not self._message_listener.dirty:
|
||||
self._message_listener.Modified()
|
||||
|
||||
def extend(self, elem_seq):
|
||||
"""Extends by appending the given sequence. Similar to list.extend()."""
|
||||
if not elem_seq:
|
||||
return
|
||||
|
||||
new_values = []
|
||||
for elem in elem_seq:
|
||||
self._type_checker.CheckValue(elem)
|
||||
new_values.append(elem)
|
||||
self._values.extend(new_values)
|
||||
self._message_listener.Modified()
|
||||
|
||||
def MergeFrom(self, other):
|
||||
"""Appends the contents of another repeated field of the same type to this
|
||||
one. We do not check the types of the individual fields.
|
||||
"""
|
||||
self._values.extend(other._values)
|
||||
self._message_listener.Modified()
|
||||
|
||||
def remove(self, elem):
|
||||
"""Removes an item from the list. Similar to list.remove()."""
|
||||
self._values.remove(elem)
|
||||
self._message_listener.Modified()
|
||||
|
||||
def __setitem__(self, key, value):
|
||||
"""Sets the item on the specified position."""
|
||||
self._type_checker.CheckValue(value)
|
||||
self._values[key] = value
|
||||
self._message_listener.Modified()
|
||||
|
||||
def __getslice__(self, start, stop):
|
||||
"""Retrieves the subset of items from between the specified indices."""
|
||||
return self._values[start:stop]
|
||||
|
||||
def __setslice__(self, start, stop, values):
|
||||
"""Sets the subset of items from between the specified indices."""
|
||||
new_values = []
|
||||
for value in values:
|
||||
self._type_checker.CheckValue(value)
|
||||
new_values.append(value)
|
||||
self._values[start:stop] = new_values
|
||||
self._message_listener.Modified()
|
||||
|
||||
def __delitem__(self, key):
|
||||
"""Deletes the item at the specified position."""
|
||||
del self._values[key]
|
||||
self._message_listener.Modified()
|
||||
|
||||
def __delslice__(self, start, stop):
|
||||
"""Deletes the subset of items from between the specified indices."""
|
||||
del self._values[start:stop]
|
||||
self._message_listener.Modified()
|
||||
|
||||
def __eq__(self, other):
|
||||
"""Compares the current instance with another one."""
|
||||
if self is other:
|
||||
return True
|
||||
# Special case for the same type which should be common and fast.
|
||||
if isinstance(other, self.__class__):
|
||||
return other._values == self._values
|
||||
# We are presumably comparing against some other sequence type.
|
||||
return other == self._values
|
||||
|
||||
|
||||
class RepeatedCompositeFieldContainer(BaseContainer):
|
||||
|
||||
"""Simple, list-like container for holding repeated composite fields."""
|
||||
|
||||
# Disallows assignment to other attributes.
|
||||
__slots__ = ['_message_descriptor']
|
||||
|
||||
def __init__(self, message_listener, message_descriptor):
|
||||
"""
|
||||
Note that we pass in a descriptor instead of the generated directly,
|
||||
since at the time we construct a _RepeatedCompositeFieldContainer we
|
||||
haven't yet necessarily initialized the type that will be contained in the
|
||||
container.
|
||||
|
||||
Args:
|
||||
message_listener: A MessageListener implementation.
|
||||
The RepeatedCompositeFieldContainer will call this object's
|
||||
Modified() method when it is modified.
|
||||
message_descriptor: A Descriptor instance describing the protocol type
|
||||
that should be present in this container. We'll use the
|
||||
_concrete_class field of this descriptor when the client calls add().
|
||||
"""
|
||||
super(RepeatedCompositeFieldContainer, self).__init__(message_listener)
|
||||
self._message_descriptor = message_descriptor
|
||||
|
||||
def add(self):
|
||||
new_element = self._message_descriptor._concrete_class()
|
||||
new_element._SetListener(self._message_listener)
|
||||
self._values.append(new_element)
|
||||
if not self._message_listener.dirty:
|
||||
self._message_listener.Modified()
|
||||
return new_element
|
||||
|
||||
def MergeFrom(self, other):
|
||||
"""Appends the contents of another repeated field of the same type to this
|
||||
one, copying each individual message.
|
||||
"""
|
||||
message_class = self._message_descriptor._concrete_class
|
||||
listener = self._message_listener
|
||||
values = self._values
|
||||
for message in other._values:
|
||||
new_element = message_class()
|
||||
new_element._SetListener(listener)
|
||||
new_element.MergeFrom(message)
|
||||
values.append(new_element)
|
||||
listener.Modified()
|
||||
|
||||
def __getslice__(self, start, stop):
|
||||
"""Retrieves the subset of items from between the specified indices."""
|
||||
return self._values[start:stop]
|
||||
|
||||
def __delitem__(self, key):
|
||||
"""Deletes the item at the specified position."""
|
||||
del self._values[key]
|
||||
self._message_listener.Modified()
|
||||
|
||||
def __delslice__(self, start, stop):
|
||||
"""Deletes the subset of items from between the specified indices."""
|
||||
del self._values[start:stop]
|
||||
self._message_listener.Modified()
|
||||
|
||||
def __eq__(self, other):
|
||||
"""Compares the current instance with another one."""
|
||||
if self is other:
|
||||
return True
|
||||
if not isinstance(other, self.__class__):
|
||||
raise TypeError('Can only compare repeated composite fields against '
|
||||
'other repeated composite fields.')
|
||||
return self._values == other._values
|
||||
|
||||
+641
-641
File diff suppressed because it is too large
Load Diff
+334
-334
@@ -1,334 +1,334 @@
|
||||
#! /usr/bin/python
|
||||
#
|
||||
# Protocol Buffers - Google's data interchange format
|
||||
# Copyright 2008 Google Inc. All rights reserved.
|
||||
# http://code.google.com/p/protobuf/
|
||||
#
|
||||
# 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.
|
||||
|
||||
"""Unittest for google.protobuf.internal.descriptor."""
|
||||
|
||||
__author__ = 'robinson@google.com (Will Robinson)'
|
||||
|
||||
import unittest
|
||||
from google.protobuf import unittest_import_pb2
|
||||
from google.protobuf import unittest_pb2
|
||||
from google.protobuf import descriptor_pb2
|
||||
from google.protobuf import descriptor
|
||||
from google.protobuf import text_format
|
||||
|
||||
|
||||
TEST_EMPTY_MESSAGE_DESCRIPTOR_ASCII = """
|
||||
name: 'TestEmptyMessage'
|
||||
"""
|
||||
|
||||
|
||||
class DescriptorTest(unittest.TestCase):
|
||||
|
||||
def setUp(self):
|
||||
self.my_file = descriptor.FileDescriptor(
|
||||
name='some/filename/some.proto',
|
||||
package='protobuf_unittest'
|
||||
)
|
||||
self.my_enum = descriptor.EnumDescriptor(
|
||||
name='ForeignEnum',
|
||||
full_name='protobuf_unittest.ForeignEnum',
|
||||
filename=None,
|
||||
file=self.my_file,
|
||||
values=[
|
||||
descriptor.EnumValueDescriptor(name='FOREIGN_FOO', index=0, number=4),
|
||||
descriptor.EnumValueDescriptor(name='FOREIGN_BAR', index=1, number=5),
|
||||
descriptor.EnumValueDescriptor(name='FOREIGN_BAZ', index=2, number=6),
|
||||
])
|
||||
self.my_message = descriptor.Descriptor(
|
||||
name='NestedMessage',
|
||||
full_name='protobuf_unittest.TestAllTypes.NestedMessage',
|
||||
filename=None,
|
||||
file=self.my_file,
|
||||
containing_type=None,
|
||||
fields=[
|
||||
descriptor.FieldDescriptor(
|
||||
name='bb',
|
||||
full_name='protobuf_unittest.TestAllTypes.NestedMessage.bb',
|
||||
index=0, number=1,
|
||||
type=5, cpp_type=1, label=1,
|
||||
has_default_value=False, default_value=0,
|
||||
message_type=None, enum_type=None, containing_type=None,
|
||||
is_extension=False, extension_scope=None),
|
||||
],
|
||||
nested_types=[],
|
||||
enum_types=[
|
||||
self.my_enum,
|
||||
],
|
||||
extensions=[])
|
||||
self.my_method = descriptor.MethodDescriptor(
|
||||
name='Bar',
|
||||
full_name='protobuf_unittest.TestService.Bar',
|
||||
index=0,
|
||||
containing_service=None,
|
||||
input_type=None,
|
||||
output_type=None)
|
||||
self.my_service = descriptor.ServiceDescriptor(
|
||||
name='TestServiceWithOptions',
|
||||
full_name='protobuf_unittest.TestServiceWithOptions',
|
||||
file=self.my_file,
|
||||
index=0,
|
||||
methods=[
|
||||
self.my_method
|
||||
])
|
||||
|
||||
def testEnumFixups(self):
|
||||
self.assertEqual(self.my_enum, self.my_enum.values[0].type)
|
||||
|
||||
def testContainingTypeFixups(self):
|
||||
self.assertEqual(self.my_message, self.my_message.fields[0].containing_type)
|
||||
self.assertEqual(self.my_message, self.my_enum.containing_type)
|
||||
|
||||
def testContainingServiceFixups(self):
|
||||
self.assertEqual(self.my_service, self.my_method.containing_service)
|
||||
|
||||
def testGetOptions(self):
|
||||
self.assertEqual(self.my_enum.GetOptions(),
|
||||
descriptor_pb2.EnumOptions())
|
||||
self.assertEqual(self.my_enum.values[0].GetOptions(),
|
||||
descriptor_pb2.EnumValueOptions())
|
||||
self.assertEqual(self.my_message.GetOptions(),
|
||||
descriptor_pb2.MessageOptions())
|
||||
self.assertEqual(self.my_message.fields[0].GetOptions(),
|
||||
descriptor_pb2.FieldOptions())
|
||||
self.assertEqual(self.my_method.GetOptions(),
|
||||
descriptor_pb2.MethodOptions())
|
||||
self.assertEqual(self.my_service.GetOptions(),
|
||||
descriptor_pb2.ServiceOptions())
|
||||
|
||||
def testFileDescriptorReferences(self):
|
||||
self.assertEqual(self.my_enum.file, self.my_file)
|
||||
self.assertEqual(self.my_message.file, self.my_file)
|
||||
|
||||
def testFileDescriptor(self):
|
||||
self.assertEqual(self.my_file.name, 'some/filename/some.proto')
|
||||
self.assertEqual(self.my_file.package, 'protobuf_unittest')
|
||||
|
||||
|
||||
class DescriptorCopyToProtoTest(unittest.TestCase):
|
||||
"""Tests for CopyTo functions of Descriptor."""
|
||||
|
||||
def _AssertProtoEqual(self, actual_proto, expected_class, expected_ascii):
|
||||
expected_proto = expected_class()
|
||||
text_format.Merge(expected_ascii, expected_proto)
|
||||
|
||||
self.assertEqual(
|
||||
actual_proto, expected_proto,
|
||||
'Not equal,\nActual:\n%s\nExpected:\n%s\n'
|
||||
% (str(actual_proto), str(expected_proto)))
|
||||
|
||||
def _InternalTestCopyToProto(self, desc, expected_proto_class,
|
||||
expected_proto_ascii):
|
||||
actual = expected_proto_class()
|
||||
desc.CopyToProto(actual)
|
||||
self._AssertProtoEqual(
|
||||
actual, expected_proto_class, expected_proto_ascii)
|
||||
|
||||
def testCopyToProto_EmptyMessage(self):
|
||||
self._InternalTestCopyToProto(
|
||||
unittest_pb2.TestEmptyMessage.DESCRIPTOR,
|
||||
descriptor_pb2.DescriptorProto,
|
||||
TEST_EMPTY_MESSAGE_DESCRIPTOR_ASCII)
|
||||
|
||||
def testCopyToProto_NestedMessage(self):
|
||||
TEST_NESTED_MESSAGE_ASCII = """
|
||||
name: 'NestedMessage'
|
||||
field: <
|
||||
name: 'bb'
|
||||
number: 1
|
||||
label: 1 # Optional
|
||||
type: 5 # TYPE_INT32
|
||||
>
|
||||
"""
|
||||
|
||||
self._InternalTestCopyToProto(
|
||||
unittest_pb2.TestAllTypes.NestedMessage.DESCRIPTOR,
|
||||
descriptor_pb2.DescriptorProto,
|
||||
TEST_NESTED_MESSAGE_ASCII)
|
||||
|
||||
def testCopyToProto_ForeignNestedMessage(self):
|
||||
TEST_FOREIGN_NESTED_ASCII = """
|
||||
name: 'TestForeignNested'
|
||||
field: <
|
||||
name: 'foreign_nested'
|
||||
number: 1
|
||||
label: 1 # Optional
|
||||
type: 11 # TYPE_MESSAGE
|
||||
type_name: '.protobuf_unittest.TestAllTypes.NestedMessage'
|
||||
>
|
||||
"""
|
||||
|
||||
self._InternalTestCopyToProto(
|
||||
unittest_pb2.TestForeignNested.DESCRIPTOR,
|
||||
descriptor_pb2.DescriptorProto,
|
||||
TEST_FOREIGN_NESTED_ASCII)
|
||||
|
||||
def testCopyToProto_ForeignEnum(self):
|
||||
TEST_FOREIGN_ENUM_ASCII = """
|
||||
name: 'ForeignEnum'
|
||||
value: <
|
||||
name: 'FOREIGN_FOO'
|
||||
number: 4
|
||||
>
|
||||
value: <
|
||||
name: 'FOREIGN_BAR'
|
||||
number: 5
|
||||
>
|
||||
value: <
|
||||
name: 'FOREIGN_BAZ'
|
||||
number: 6
|
||||
>
|
||||
"""
|
||||
|
||||
self._InternalTestCopyToProto(
|
||||
unittest_pb2._FOREIGNENUM,
|
||||
descriptor_pb2.EnumDescriptorProto,
|
||||
TEST_FOREIGN_ENUM_ASCII)
|
||||
|
||||
def testCopyToProto_Options(self):
|
||||
TEST_DEPRECATED_FIELDS_ASCII = """
|
||||
name: 'TestDeprecatedFields'
|
||||
field: <
|
||||
name: 'deprecated_int32'
|
||||
number: 1
|
||||
label: 1 # Optional
|
||||
type: 5 # TYPE_INT32
|
||||
options: <
|
||||
deprecated: true
|
||||
>
|
||||
>
|
||||
"""
|
||||
|
||||
self._InternalTestCopyToProto(
|
||||
unittest_pb2.TestDeprecatedFields.DESCRIPTOR,
|
||||
descriptor_pb2.DescriptorProto,
|
||||
TEST_DEPRECATED_FIELDS_ASCII)
|
||||
|
||||
def testCopyToProto_AllExtensions(self):
|
||||
TEST_EMPTY_MESSAGE_WITH_EXTENSIONS_ASCII = """
|
||||
name: 'TestEmptyMessageWithExtensions'
|
||||
extension_range: <
|
||||
start: 1
|
||||
end: 536870912
|
||||
>
|
||||
"""
|
||||
|
||||
self._InternalTestCopyToProto(
|
||||
unittest_pb2.TestEmptyMessageWithExtensions.DESCRIPTOR,
|
||||
descriptor_pb2.DescriptorProto,
|
||||
TEST_EMPTY_MESSAGE_WITH_EXTENSIONS_ASCII)
|
||||
|
||||
def testCopyToProto_SeveralExtensions(self):
|
||||
TEST_MESSAGE_WITH_SEVERAL_EXTENSIONS_ASCII = """
|
||||
name: 'TestMultipleExtensionRanges'
|
||||
extension_range: <
|
||||
start: 42
|
||||
end: 43
|
||||
>
|
||||
extension_range: <
|
||||
start: 4143
|
||||
end: 4244
|
||||
>
|
||||
extension_range: <
|
||||
start: 65536
|
||||
end: 536870912
|
||||
>
|
||||
"""
|
||||
|
||||
self._InternalTestCopyToProto(
|
||||
unittest_pb2.TestMultipleExtensionRanges.DESCRIPTOR,
|
||||
descriptor_pb2.DescriptorProto,
|
||||
TEST_MESSAGE_WITH_SEVERAL_EXTENSIONS_ASCII)
|
||||
|
||||
def testCopyToProto_FileDescriptor(self):
|
||||
UNITTEST_IMPORT_FILE_DESCRIPTOR_ASCII = ("""
|
||||
name: 'google/protobuf/unittest_import.proto'
|
||||
package: 'protobuf_unittest_import'
|
||||
message_type: <
|
||||
name: 'ImportMessage'
|
||||
field: <
|
||||
name: 'd'
|
||||
number: 1
|
||||
label: 1 # Optional
|
||||
type: 5 # TYPE_INT32
|
||||
>
|
||||
>
|
||||
""" +
|
||||
"""enum_type: <
|
||||
name: 'ImportEnum'
|
||||
value: <
|
||||
name: 'IMPORT_FOO'
|
||||
number: 7
|
||||
>
|
||||
value: <
|
||||
name: 'IMPORT_BAR'
|
||||
number: 8
|
||||
>
|
||||
value: <
|
||||
name: 'IMPORT_BAZ'
|
||||
number: 9
|
||||
>
|
||||
>
|
||||
options: <
|
||||
java_package: 'com.google.protobuf.test'
|
||||
optimize_for: 1 # SPEED
|
||||
>
|
||||
""")
|
||||
|
||||
self._InternalTestCopyToProto(
|
||||
unittest_import_pb2.DESCRIPTOR,
|
||||
descriptor_pb2.FileDescriptorProto,
|
||||
UNITTEST_IMPORT_FILE_DESCRIPTOR_ASCII)
|
||||
|
||||
def testCopyToProto_ServiceDescriptor(self):
|
||||
TEST_SERVICE_ASCII = """
|
||||
name: 'TestService'
|
||||
method: <
|
||||
name: 'Foo'
|
||||
input_type: '.protobuf_unittest.FooRequest'
|
||||
output_type: '.protobuf_unittest.FooResponse'
|
||||
>
|
||||
method: <
|
||||
name: 'Bar'
|
||||
input_type: '.protobuf_unittest.BarRequest'
|
||||
output_type: '.protobuf_unittest.BarResponse'
|
||||
>
|
||||
"""
|
||||
|
||||
self._InternalTestCopyToProto(
|
||||
unittest_pb2.TestService.DESCRIPTOR,
|
||||
descriptor_pb2.ServiceDescriptorProto,
|
||||
TEST_SERVICE_ASCII)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
#! /usr/bin/python
|
||||
#
|
||||
# Protocol Buffers - Google's data interchange format
|
||||
# Copyright 2008 Google Inc. All rights reserved.
|
||||
# http://code.google.com/p/protobuf/
|
||||
#
|
||||
# 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.
|
||||
|
||||
"""Unittest for google.protobuf.internal.descriptor."""
|
||||
|
||||
__author__ = 'robinson@google.com (Will Robinson)'
|
||||
|
||||
import unittest
|
||||
from google.protobuf import unittest_import_pb2
|
||||
from google.protobuf import unittest_pb2
|
||||
from google.protobuf import descriptor_pb2
|
||||
from google.protobuf import descriptor
|
||||
from google.protobuf import text_format
|
||||
|
||||
|
||||
TEST_EMPTY_MESSAGE_DESCRIPTOR_ASCII = """
|
||||
name: 'TestEmptyMessage'
|
||||
"""
|
||||
|
||||
|
||||
class DescriptorTest(unittest.TestCase):
|
||||
|
||||
def setUp(self):
|
||||
self.my_file = descriptor.FileDescriptor(
|
||||
name='some/filename/some.proto',
|
||||
package='protobuf_unittest'
|
||||
)
|
||||
self.my_enum = descriptor.EnumDescriptor(
|
||||
name='ForeignEnum',
|
||||
full_name='protobuf_unittest.ForeignEnum',
|
||||
filename=None,
|
||||
file=self.my_file,
|
||||
values=[
|
||||
descriptor.EnumValueDescriptor(name='FOREIGN_FOO', index=0, number=4),
|
||||
descriptor.EnumValueDescriptor(name='FOREIGN_BAR', index=1, number=5),
|
||||
descriptor.EnumValueDescriptor(name='FOREIGN_BAZ', index=2, number=6),
|
||||
])
|
||||
self.my_message = descriptor.Descriptor(
|
||||
name='NestedMessage',
|
||||
full_name='protobuf_unittest.TestAllTypes.NestedMessage',
|
||||
filename=None,
|
||||
file=self.my_file,
|
||||
containing_type=None,
|
||||
fields=[
|
||||
descriptor.FieldDescriptor(
|
||||
name='bb',
|
||||
full_name='protobuf_unittest.TestAllTypes.NestedMessage.bb',
|
||||
index=0, number=1,
|
||||
type=5, cpp_type=1, label=1,
|
||||
has_default_value=False, default_value=0,
|
||||
message_type=None, enum_type=None, containing_type=None,
|
||||
is_extension=False, extension_scope=None),
|
||||
],
|
||||
nested_types=[],
|
||||
enum_types=[
|
||||
self.my_enum,
|
||||
],
|
||||
extensions=[])
|
||||
self.my_method = descriptor.MethodDescriptor(
|
||||
name='Bar',
|
||||
full_name='protobuf_unittest.TestService.Bar',
|
||||
index=0,
|
||||
containing_service=None,
|
||||
input_type=None,
|
||||
output_type=None)
|
||||
self.my_service = descriptor.ServiceDescriptor(
|
||||
name='TestServiceWithOptions',
|
||||
full_name='protobuf_unittest.TestServiceWithOptions',
|
||||
file=self.my_file,
|
||||
index=0,
|
||||
methods=[
|
||||
self.my_method
|
||||
])
|
||||
|
||||
def testEnumFixups(self):
|
||||
self.assertEqual(self.my_enum, self.my_enum.values[0].type)
|
||||
|
||||
def testContainingTypeFixups(self):
|
||||
self.assertEqual(self.my_message, self.my_message.fields[0].containing_type)
|
||||
self.assertEqual(self.my_message, self.my_enum.containing_type)
|
||||
|
||||
def testContainingServiceFixups(self):
|
||||
self.assertEqual(self.my_service, self.my_method.containing_service)
|
||||
|
||||
def testGetOptions(self):
|
||||
self.assertEqual(self.my_enum.GetOptions(),
|
||||
descriptor_pb2.EnumOptions())
|
||||
self.assertEqual(self.my_enum.values[0].GetOptions(),
|
||||
descriptor_pb2.EnumValueOptions())
|
||||
self.assertEqual(self.my_message.GetOptions(),
|
||||
descriptor_pb2.MessageOptions())
|
||||
self.assertEqual(self.my_message.fields[0].GetOptions(),
|
||||
descriptor_pb2.FieldOptions())
|
||||
self.assertEqual(self.my_method.GetOptions(),
|
||||
descriptor_pb2.MethodOptions())
|
||||
self.assertEqual(self.my_service.GetOptions(),
|
||||
descriptor_pb2.ServiceOptions())
|
||||
|
||||
def testFileDescriptorReferences(self):
|
||||
self.assertEqual(self.my_enum.file, self.my_file)
|
||||
self.assertEqual(self.my_message.file, self.my_file)
|
||||
|
||||
def testFileDescriptor(self):
|
||||
self.assertEqual(self.my_file.name, 'some/filename/some.proto')
|
||||
self.assertEqual(self.my_file.package, 'protobuf_unittest')
|
||||
|
||||
|
||||
class DescriptorCopyToProtoTest(unittest.TestCase):
|
||||
"""Tests for CopyTo functions of Descriptor."""
|
||||
|
||||
def _AssertProtoEqual(self, actual_proto, expected_class, expected_ascii):
|
||||
expected_proto = expected_class()
|
||||
text_format.Merge(expected_ascii, expected_proto)
|
||||
|
||||
self.assertEqual(
|
||||
actual_proto, expected_proto,
|
||||
'Not equal,\nActual:\n%s\nExpected:\n%s\n'
|
||||
% (str(actual_proto), str(expected_proto)))
|
||||
|
||||
def _InternalTestCopyToProto(self, desc, expected_proto_class,
|
||||
expected_proto_ascii):
|
||||
actual = expected_proto_class()
|
||||
desc.CopyToProto(actual)
|
||||
self._AssertProtoEqual(
|
||||
actual, expected_proto_class, expected_proto_ascii)
|
||||
|
||||
def testCopyToProto_EmptyMessage(self):
|
||||
self._InternalTestCopyToProto(
|
||||
unittest_pb2.TestEmptyMessage.DESCRIPTOR,
|
||||
descriptor_pb2.DescriptorProto,
|
||||
TEST_EMPTY_MESSAGE_DESCRIPTOR_ASCII)
|
||||
|
||||
def testCopyToProto_NestedMessage(self):
|
||||
TEST_NESTED_MESSAGE_ASCII = """
|
||||
name: 'NestedMessage'
|
||||
field: <
|
||||
name: 'bb'
|
||||
number: 1
|
||||
label: 1 # Optional
|
||||
type: 5 # TYPE_INT32
|
||||
>
|
||||
"""
|
||||
|
||||
self._InternalTestCopyToProto(
|
||||
unittest_pb2.TestAllTypes.NestedMessage.DESCRIPTOR,
|
||||
descriptor_pb2.DescriptorProto,
|
||||
TEST_NESTED_MESSAGE_ASCII)
|
||||
|
||||
def testCopyToProto_ForeignNestedMessage(self):
|
||||
TEST_FOREIGN_NESTED_ASCII = """
|
||||
name: 'TestForeignNested'
|
||||
field: <
|
||||
name: 'foreign_nested'
|
||||
number: 1
|
||||
label: 1 # Optional
|
||||
type: 11 # TYPE_MESSAGE
|
||||
type_name: '.protobuf_unittest.TestAllTypes.NestedMessage'
|
||||
>
|
||||
"""
|
||||
|
||||
self._InternalTestCopyToProto(
|
||||
unittest_pb2.TestForeignNested.DESCRIPTOR,
|
||||
descriptor_pb2.DescriptorProto,
|
||||
TEST_FOREIGN_NESTED_ASCII)
|
||||
|
||||
def testCopyToProto_ForeignEnum(self):
|
||||
TEST_FOREIGN_ENUM_ASCII = """
|
||||
name: 'ForeignEnum'
|
||||
value: <
|
||||
name: 'FOREIGN_FOO'
|
||||
number: 4
|
||||
>
|
||||
value: <
|
||||
name: 'FOREIGN_BAR'
|
||||
number: 5
|
||||
>
|
||||
value: <
|
||||
name: 'FOREIGN_BAZ'
|
||||
number: 6
|
||||
>
|
||||
"""
|
||||
|
||||
self._InternalTestCopyToProto(
|
||||
unittest_pb2._FOREIGNENUM,
|
||||
descriptor_pb2.EnumDescriptorProto,
|
||||
TEST_FOREIGN_ENUM_ASCII)
|
||||
|
||||
def testCopyToProto_Options(self):
|
||||
TEST_DEPRECATED_FIELDS_ASCII = """
|
||||
name: 'TestDeprecatedFields'
|
||||
field: <
|
||||
name: 'deprecated_int32'
|
||||
number: 1
|
||||
label: 1 # Optional
|
||||
type: 5 # TYPE_INT32
|
||||
options: <
|
||||
deprecated: true
|
||||
>
|
||||
>
|
||||
"""
|
||||
|
||||
self._InternalTestCopyToProto(
|
||||
unittest_pb2.TestDeprecatedFields.DESCRIPTOR,
|
||||
descriptor_pb2.DescriptorProto,
|
||||
TEST_DEPRECATED_FIELDS_ASCII)
|
||||
|
||||
def testCopyToProto_AllExtensions(self):
|
||||
TEST_EMPTY_MESSAGE_WITH_EXTENSIONS_ASCII = """
|
||||
name: 'TestEmptyMessageWithExtensions'
|
||||
extension_range: <
|
||||
start: 1
|
||||
end: 536870912
|
||||
>
|
||||
"""
|
||||
|
||||
self._InternalTestCopyToProto(
|
||||
unittest_pb2.TestEmptyMessageWithExtensions.DESCRIPTOR,
|
||||
descriptor_pb2.DescriptorProto,
|
||||
TEST_EMPTY_MESSAGE_WITH_EXTENSIONS_ASCII)
|
||||
|
||||
def testCopyToProto_SeveralExtensions(self):
|
||||
TEST_MESSAGE_WITH_SEVERAL_EXTENSIONS_ASCII = """
|
||||
name: 'TestMultipleExtensionRanges'
|
||||
extension_range: <
|
||||
start: 42
|
||||
end: 43
|
||||
>
|
||||
extension_range: <
|
||||
start: 4143
|
||||
end: 4244
|
||||
>
|
||||
extension_range: <
|
||||
start: 65536
|
||||
end: 536870912
|
||||
>
|
||||
"""
|
||||
|
||||
self._InternalTestCopyToProto(
|
||||
unittest_pb2.TestMultipleExtensionRanges.DESCRIPTOR,
|
||||
descriptor_pb2.DescriptorProto,
|
||||
TEST_MESSAGE_WITH_SEVERAL_EXTENSIONS_ASCII)
|
||||
|
||||
def testCopyToProto_FileDescriptor(self):
|
||||
UNITTEST_IMPORT_FILE_DESCRIPTOR_ASCII = ("""
|
||||
name: 'google/protobuf/unittest_import.proto'
|
||||
package: 'protobuf_unittest_import'
|
||||
message_type: <
|
||||
name: 'ImportMessage'
|
||||
field: <
|
||||
name: 'd'
|
||||
number: 1
|
||||
label: 1 # Optional
|
||||
type: 5 # TYPE_INT32
|
||||
>
|
||||
>
|
||||
""" +
|
||||
"""enum_type: <
|
||||
name: 'ImportEnum'
|
||||
value: <
|
||||
name: 'IMPORT_FOO'
|
||||
number: 7
|
||||
>
|
||||
value: <
|
||||
name: 'IMPORT_BAR'
|
||||
number: 8
|
||||
>
|
||||
value: <
|
||||
name: 'IMPORT_BAZ'
|
||||
number: 9
|
||||
>
|
||||
>
|
||||
options: <
|
||||
java_package: 'com.google.protobuf.test'
|
||||
optimize_for: 1 # SPEED
|
||||
>
|
||||
""")
|
||||
|
||||
self._InternalTestCopyToProto(
|
||||
unittest_import_pb2.DESCRIPTOR,
|
||||
descriptor_pb2.FileDescriptorProto,
|
||||
UNITTEST_IMPORT_FILE_DESCRIPTOR_ASCII)
|
||||
|
||||
def testCopyToProto_ServiceDescriptor(self):
|
||||
TEST_SERVICE_ASCII = """
|
||||
name: 'TestService'
|
||||
method: <
|
||||
name: 'Foo'
|
||||
input_type: '.protobuf_unittest.FooRequest'
|
||||
output_type: '.protobuf_unittest.FooResponse'
|
||||
>
|
||||
method: <
|
||||
name: 'Bar'
|
||||
input_type: '.protobuf_unittest.BarRequest'
|
||||
output_type: '.protobuf_unittest.BarResponse'
|
||||
>
|
||||
"""
|
||||
|
||||
self._InternalTestCopyToProto(
|
||||
unittest_pb2.TestService.DESCRIPTOR,
|
||||
descriptor_pb2.ServiceDescriptorProto,
|
||||
TEST_SERVICE_ASCII)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
|
||||
+686
-686
File diff suppressed because it is too large
Load Diff
+220
-220
@@ -1,220 +1,220 @@
|
||||
#! /usr/bin/python
|
||||
#
|
||||
# Protocol Buffers - Google's data interchange format
|
||||
# Copyright 2008 Google Inc. All rights reserved.
|
||||
# http://code.google.com/p/protobuf/
|
||||
#
|
||||
# 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.
|
||||
|
||||
# TODO(robinson): Flesh this out considerably. We focused on reflection_test.py
|
||||
# first, since it's testing the subtler code, and since it provides decent
|
||||
# indirect testing of the protocol compiler output.
|
||||
|
||||
"""Unittest that directly tests the output of the pure-Python protocol
|
||||
compiler. See //google/protobuf/reflection_test.py for a test which
|
||||
further ensures that we can use Python protocol message objects as we expect.
|
||||
"""
|
||||
|
||||
__author__ = 'robinson@google.com (Will Robinson)'
|
||||
|
||||
import unittest
|
||||
from google.protobuf import unittest_import_pb2
|
||||
from google.protobuf import unittest_mset_pb2
|
||||
from google.protobuf import unittest_pb2
|
||||
from google.protobuf import unittest_no_generic_services_pb2
|
||||
|
||||
|
||||
MAX_EXTENSION = 536870912
|
||||
|
||||
|
||||
class GeneratorTest(unittest.TestCase):
|
||||
|
||||
def testNestedMessageDescriptor(self):
|
||||
field_name = 'optional_nested_message'
|
||||
proto_type = unittest_pb2.TestAllTypes
|
||||
self.assertEqual(
|
||||
proto_type.NestedMessage.DESCRIPTOR,
|
||||
proto_type.DESCRIPTOR.fields_by_name[field_name].message_type)
|
||||
|
||||
def testEnums(self):
|
||||
# We test only module-level enums here.
|
||||
# TODO(robinson): Examine descriptors directly to check
|
||||
# enum descriptor output.
|
||||
self.assertEqual(4, unittest_pb2.FOREIGN_FOO)
|
||||
self.assertEqual(5, unittest_pb2.FOREIGN_BAR)
|
||||
self.assertEqual(6, unittest_pb2.FOREIGN_BAZ)
|
||||
|
||||
proto = unittest_pb2.TestAllTypes()
|
||||
self.assertEqual(1, proto.FOO)
|
||||
self.assertEqual(1, unittest_pb2.TestAllTypes.FOO)
|
||||
self.assertEqual(2, proto.BAR)
|
||||
self.assertEqual(2, unittest_pb2.TestAllTypes.BAR)
|
||||
self.assertEqual(3, proto.BAZ)
|
||||
self.assertEqual(3, unittest_pb2.TestAllTypes.BAZ)
|
||||
|
||||
def testExtremeDefaultValues(self):
|
||||
message = unittest_pb2.TestExtremeDefaultValues()
|
||||
|
||||
# Python pre-2.6 does not have isinf() or isnan() functions, so we have
|
||||
# to provide our own.
|
||||
def isnan(val):
|
||||
# NaN is never equal to itself.
|
||||
return val != val
|
||||
def isinf(val):
|
||||
# Infinity times zero equals NaN.
|
||||
return not isnan(val) and isnan(val * 0)
|
||||
|
||||
self.assertTrue(isinf(message.inf_double))
|
||||
self.assertTrue(message.inf_double > 0)
|
||||
self.assertTrue(isinf(message.neg_inf_double))
|
||||
self.assertTrue(message.neg_inf_double < 0)
|
||||
self.assertTrue(isnan(message.nan_double))
|
||||
|
||||
self.assertTrue(isinf(message.inf_float))
|
||||
self.assertTrue(message.inf_float > 0)
|
||||
self.assertTrue(isinf(message.neg_inf_float))
|
||||
self.assertTrue(message.neg_inf_float < 0)
|
||||
self.assertTrue(isnan(message.nan_float))
|
||||
|
||||
def testHasDefaultValues(self):
|
||||
desc = unittest_pb2.TestAllTypes.DESCRIPTOR
|
||||
|
||||
expected_has_default_by_name = {
|
||||
'optional_int32': False,
|
||||
'repeated_int32': False,
|
||||
'optional_nested_message': False,
|
||||
'default_int32': True,
|
||||
}
|
||||
|
||||
has_default_by_name = dict(
|
||||
[(f.name, f.has_default_value)
|
||||
for f in desc.fields
|
||||
if f.name in expected_has_default_by_name])
|
||||
self.assertEqual(expected_has_default_by_name, has_default_by_name)
|
||||
|
||||
def testContainingTypeBehaviorForExtensions(self):
|
||||
self.assertEqual(unittest_pb2.optional_int32_extension.containing_type,
|
||||
unittest_pb2.TestAllExtensions.DESCRIPTOR)
|
||||
self.assertEqual(unittest_pb2.TestRequired.single.containing_type,
|
||||
unittest_pb2.TestAllExtensions.DESCRIPTOR)
|
||||
|
||||
def testExtensionScope(self):
|
||||
self.assertEqual(unittest_pb2.optional_int32_extension.extension_scope,
|
||||
None)
|
||||
self.assertEqual(unittest_pb2.TestRequired.single.extension_scope,
|
||||
unittest_pb2.TestRequired.DESCRIPTOR)
|
||||
|
||||
def testIsExtension(self):
|
||||
self.assertTrue(unittest_pb2.optional_int32_extension.is_extension)
|
||||
self.assertTrue(unittest_pb2.TestRequired.single.is_extension)
|
||||
|
||||
message_descriptor = unittest_pb2.TestRequired.DESCRIPTOR
|
||||
non_extension_descriptor = message_descriptor.fields_by_name['a']
|
||||
self.assertTrue(not non_extension_descriptor.is_extension)
|
||||
|
||||
def testOptions(self):
|
||||
proto = unittest_mset_pb2.TestMessageSet()
|
||||
self.assertTrue(proto.DESCRIPTOR.GetOptions().message_set_wire_format)
|
||||
|
||||
def testNestedTypes(self):
|
||||
self.assertEquals(
|
||||
set(unittest_pb2.TestAllTypes.DESCRIPTOR.nested_types),
|
||||
set([
|
||||
unittest_pb2.TestAllTypes.NestedMessage.DESCRIPTOR,
|
||||
unittest_pb2.TestAllTypes.OptionalGroup.DESCRIPTOR,
|
||||
unittest_pb2.TestAllTypes.RepeatedGroup.DESCRIPTOR,
|
||||
]))
|
||||
self.assertEqual(unittest_pb2.TestEmptyMessage.DESCRIPTOR.nested_types, [])
|
||||
self.assertEqual(
|
||||
unittest_pb2.TestAllTypes.NestedMessage.DESCRIPTOR.nested_types, [])
|
||||
|
||||
def testContainingType(self):
|
||||
self.assertTrue(
|
||||
unittest_pb2.TestEmptyMessage.DESCRIPTOR.containing_type is None)
|
||||
self.assertTrue(
|
||||
unittest_pb2.TestAllTypes.DESCRIPTOR.containing_type is None)
|
||||
self.assertEqual(
|
||||
unittest_pb2.TestAllTypes.NestedMessage.DESCRIPTOR.containing_type,
|
||||
unittest_pb2.TestAllTypes.DESCRIPTOR)
|
||||
self.assertEqual(
|
||||
unittest_pb2.TestAllTypes.NestedMessage.DESCRIPTOR.containing_type,
|
||||
unittest_pb2.TestAllTypes.DESCRIPTOR)
|
||||
self.assertEqual(
|
||||
unittest_pb2.TestAllTypes.RepeatedGroup.DESCRIPTOR.containing_type,
|
||||
unittest_pb2.TestAllTypes.DESCRIPTOR)
|
||||
|
||||
def testContainingTypeInEnumDescriptor(self):
|
||||
self.assertTrue(unittest_pb2._FOREIGNENUM.containing_type is None)
|
||||
self.assertEqual(unittest_pb2._TESTALLTYPES_NESTEDENUM.containing_type,
|
||||
unittest_pb2.TestAllTypes.DESCRIPTOR)
|
||||
|
||||
def testPackage(self):
|
||||
self.assertEqual(
|
||||
unittest_pb2.TestAllTypes.DESCRIPTOR.file.package,
|
||||
'protobuf_unittest')
|
||||
desc = unittest_pb2.TestAllTypes.NestedMessage.DESCRIPTOR
|
||||
self.assertEqual(desc.file.package, 'protobuf_unittest')
|
||||
self.assertEqual(
|
||||
unittest_import_pb2.ImportMessage.DESCRIPTOR.file.package,
|
||||
'protobuf_unittest_import')
|
||||
|
||||
self.assertEqual(
|
||||
unittest_pb2._FOREIGNENUM.file.package, 'protobuf_unittest')
|
||||
self.assertEqual(
|
||||
unittest_pb2._TESTALLTYPES_NESTEDENUM.file.package,
|
||||
'protobuf_unittest')
|
||||
self.assertEqual(
|
||||
unittest_import_pb2._IMPORTENUM.file.package,
|
||||
'protobuf_unittest_import')
|
||||
|
||||
def testExtensionRange(self):
|
||||
self.assertEqual(
|
||||
unittest_pb2.TestAllTypes.DESCRIPTOR.extension_ranges, [])
|
||||
self.assertEqual(
|
||||
unittest_pb2.TestAllExtensions.DESCRIPTOR.extension_ranges,
|
||||
[(1, MAX_EXTENSION)])
|
||||
self.assertEqual(
|
||||
unittest_pb2.TestMultipleExtensionRanges.DESCRIPTOR.extension_ranges,
|
||||
[(42, 43), (4143, 4244), (65536, MAX_EXTENSION)])
|
||||
|
||||
def testFileDescriptor(self):
|
||||
self.assertEqual(unittest_pb2.DESCRIPTOR.name,
|
||||
'google/protobuf/unittest.proto')
|
||||
self.assertEqual(unittest_pb2.DESCRIPTOR.package, 'protobuf_unittest')
|
||||
self.assertFalse(unittest_pb2.DESCRIPTOR.serialized_pb is None)
|
||||
|
||||
def testNoGenericServices(self):
|
||||
# unittest_no_generic_services.proto should contain defs for everything
|
||||
# except services.
|
||||
self.assertTrue(hasattr(unittest_no_generic_services_pb2, "TestMessage"))
|
||||
self.assertTrue(hasattr(unittest_no_generic_services_pb2, "FOO"))
|
||||
self.assertTrue(hasattr(unittest_no_generic_services_pb2, "test_extension"))
|
||||
self.assertFalse(hasattr(unittest_no_generic_services_pb2, "TestService"))
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
#! /usr/bin/python
|
||||
#
|
||||
# Protocol Buffers - Google's data interchange format
|
||||
# Copyright 2008 Google Inc. All rights reserved.
|
||||
# http://code.google.com/p/protobuf/
|
||||
#
|
||||
# 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.
|
||||
|
||||
# TODO(robinson): Flesh this out considerably. We focused on reflection_test.py
|
||||
# first, since it's testing the subtler code, and since it provides decent
|
||||
# indirect testing of the protocol compiler output.
|
||||
|
||||
"""Unittest that directly tests the output of the pure-Python protocol
|
||||
compiler. See //google/protobuf/reflection_test.py for a test which
|
||||
further ensures that we can use Python protocol message objects as we expect.
|
||||
"""
|
||||
|
||||
__author__ = 'robinson@google.com (Will Robinson)'
|
||||
|
||||
import unittest
|
||||
from google.protobuf import unittest_import_pb2
|
||||
from google.protobuf import unittest_mset_pb2
|
||||
from google.protobuf import unittest_pb2
|
||||
from google.protobuf import unittest_no_generic_services_pb2
|
||||
|
||||
|
||||
MAX_EXTENSION = 536870912
|
||||
|
||||
|
||||
class GeneratorTest(unittest.TestCase):
|
||||
|
||||
def testNestedMessageDescriptor(self):
|
||||
field_name = 'optional_nested_message'
|
||||
proto_type = unittest_pb2.TestAllTypes
|
||||
self.assertEqual(
|
||||
proto_type.NestedMessage.DESCRIPTOR,
|
||||
proto_type.DESCRIPTOR.fields_by_name[field_name].message_type)
|
||||
|
||||
def testEnums(self):
|
||||
# We test only module-level enums here.
|
||||
# TODO(robinson): Examine descriptors directly to check
|
||||
# enum descriptor output.
|
||||
self.assertEqual(4, unittest_pb2.FOREIGN_FOO)
|
||||
self.assertEqual(5, unittest_pb2.FOREIGN_BAR)
|
||||
self.assertEqual(6, unittest_pb2.FOREIGN_BAZ)
|
||||
|
||||
proto = unittest_pb2.TestAllTypes()
|
||||
self.assertEqual(1, proto.FOO)
|
||||
self.assertEqual(1, unittest_pb2.TestAllTypes.FOO)
|
||||
self.assertEqual(2, proto.BAR)
|
||||
self.assertEqual(2, unittest_pb2.TestAllTypes.BAR)
|
||||
self.assertEqual(3, proto.BAZ)
|
||||
self.assertEqual(3, unittest_pb2.TestAllTypes.BAZ)
|
||||
|
||||
def testExtremeDefaultValues(self):
|
||||
message = unittest_pb2.TestExtremeDefaultValues()
|
||||
|
||||
# Python pre-2.6 does not have isinf() or isnan() functions, so we have
|
||||
# to provide our own.
|
||||
def isnan(val):
|
||||
# NaN is never equal to itself.
|
||||
return val != val
|
||||
def isinf(val):
|
||||
# Infinity times zero equals NaN.
|
||||
return not isnan(val) and isnan(val * 0)
|
||||
|
||||
self.assertTrue(isinf(message.inf_double))
|
||||
self.assertTrue(message.inf_double > 0)
|
||||
self.assertTrue(isinf(message.neg_inf_double))
|
||||
self.assertTrue(message.neg_inf_double < 0)
|
||||
self.assertTrue(isnan(message.nan_double))
|
||||
|
||||
self.assertTrue(isinf(message.inf_float))
|
||||
self.assertTrue(message.inf_float > 0)
|
||||
self.assertTrue(isinf(message.neg_inf_float))
|
||||
self.assertTrue(message.neg_inf_float < 0)
|
||||
self.assertTrue(isnan(message.nan_float))
|
||||
|
||||
def testHasDefaultValues(self):
|
||||
desc = unittest_pb2.TestAllTypes.DESCRIPTOR
|
||||
|
||||
expected_has_default_by_name = {
|
||||
'optional_int32': False,
|
||||
'repeated_int32': False,
|
||||
'optional_nested_message': False,
|
||||
'default_int32': True,
|
||||
}
|
||||
|
||||
has_default_by_name = dict(
|
||||
[(f.name, f.has_default_value)
|
||||
for f in desc.fields
|
||||
if f.name in expected_has_default_by_name])
|
||||
self.assertEqual(expected_has_default_by_name, has_default_by_name)
|
||||
|
||||
def testContainingTypeBehaviorForExtensions(self):
|
||||
self.assertEqual(unittest_pb2.optional_int32_extension.containing_type,
|
||||
unittest_pb2.TestAllExtensions.DESCRIPTOR)
|
||||
self.assertEqual(unittest_pb2.TestRequired.single.containing_type,
|
||||
unittest_pb2.TestAllExtensions.DESCRIPTOR)
|
||||
|
||||
def testExtensionScope(self):
|
||||
self.assertEqual(unittest_pb2.optional_int32_extension.extension_scope,
|
||||
None)
|
||||
self.assertEqual(unittest_pb2.TestRequired.single.extension_scope,
|
||||
unittest_pb2.TestRequired.DESCRIPTOR)
|
||||
|
||||
def testIsExtension(self):
|
||||
self.assertTrue(unittest_pb2.optional_int32_extension.is_extension)
|
||||
self.assertTrue(unittest_pb2.TestRequired.single.is_extension)
|
||||
|
||||
message_descriptor = unittest_pb2.TestRequired.DESCRIPTOR
|
||||
non_extension_descriptor = message_descriptor.fields_by_name['a']
|
||||
self.assertTrue(not non_extension_descriptor.is_extension)
|
||||
|
||||
def testOptions(self):
|
||||
proto = unittest_mset_pb2.TestMessageSet()
|
||||
self.assertTrue(proto.DESCRIPTOR.GetOptions().message_set_wire_format)
|
||||
|
||||
def testNestedTypes(self):
|
||||
self.assertEquals(
|
||||
set(unittest_pb2.TestAllTypes.DESCRIPTOR.nested_types),
|
||||
set([
|
||||
unittest_pb2.TestAllTypes.NestedMessage.DESCRIPTOR,
|
||||
unittest_pb2.TestAllTypes.OptionalGroup.DESCRIPTOR,
|
||||
unittest_pb2.TestAllTypes.RepeatedGroup.DESCRIPTOR,
|
||||
]))
|
||||
self.assertEqual(unittest_pb2.TestEmptyMessage.DESCRIPTOR.nested_types, [])
|
||||
self.assertEqual(
|
||||
unittest_pb2.TestAllTypes.NestedMessage.DESCRIPTOR.nested_types, [])
|
||||
|
||||
def testContainingType(self):
|
||||
self.assertTrue(
|
||||
unittest_pb2.TestEmptyMessage.DESCRIPTOR.containing_type is None)
|
||||
self.assertTrue(
|
||||
unittest_pb2.TestAllTypes.DESCRIPTOR.containing_type is None)
|
||||
self.assertEqual(
|
||||
unittest_pb2.TestAllTypes.NestedMessage.DESCRIPTOR.containing_type,
|
||||
unittest_pb2.TestAllTypes.DESCRIPTOR)
|
||||
self.assertEqual(
|
||||
unittest_pb2.TestAllTypes.NestedMessage.DESCRIPTOR.containing_type,
|
||||
unittest_pb2.TestAllTypes.DESCRIPTOR)
|
||||
self.assertEqual(
|
||||
unittest_pb2.TestAllTypes.RepeatedGroup.DESCRIPTOR.containing_type,
|
||||
unittest_pb2.TestAllTypes.DESCRIPTOR)
|
||||
|
||||
def testContainingTypeInEnumDescriptor(self):
|
||||
self.assertTrue(unittest_pb2._FOREIGNENUM.containing_type is None)
|
||||
self.assertEqual(unittest_pb2._TESTALLTYPES_NESTEDENUM.containing_type,
|
||||
unittest_pb2.TestAllTypes.DESCRIPTOR)
|
||||
|
||||
def testPackage(self):
|
||||
self.assertEqual(
|
||||
unittest_pb2.TestAllTypes.DESCRIPTOR.file.package,
|
||||
'protobuf_unittest')
|
||||
desc = unittest_pb2.TestAllTypes.NestedMessage.DESCRIPTOR
|
||||
self.assertEqual(desc.file.package, 'protobuf_unittest')
|
||||
self.assertEqual(
|
||||
unittest_import_pb2.ImportMessage.DESCRIPTOR.file.package,
|
||||
'protobuf_unittest_import')
|
||||
|
||||
self.assertEqual(
|
||||
unittest_pb2._FOREIGNENUM.file.package, 'protobuf_unittest')
|
||||
self.assertEqual(
|
||||
unittest_pb2._TESTALLTYPES_NESTEDENUM.file.package,
|
||||
'protobuf_unittest')
|
||||
self.assertEqual(
|
||||
unittest_import_pb2._IMPORTENUM.file.package,
|
||||
'protobuf_unittest_import')
|
||||
|
||||
def testExtensionRange(self):
|
||||
self.assertEqual(
|
||||
unittest_pb2.TestAllTypes.DESCRIPTOR.extension_ranges, [])
|
||||
self.assertEqual(
|
||||
unittest_pb2.TestAllExtensions.DESCRIPTOR.extension_ranges,
|
||||
[(1, MAX_EXTENSION)])
|
||||
self.assertEqual(
|
||||
unittest_pb2.TestMultipleExtensionRanges.DESCRIPTOR.extension_ranges,
|
||||
[(42, 43), (4143, 4244), (65536, MAX_EXTENSION)])
|
||||
|
||||
def testFileDescriptor(self):
|
||||
self.assertEqual(unittest_pb2.DESCRIPTOR.name,
|
||||
'google/protobuf/unittest.proto')
|
||||
self.assertEqual(unittest_pb2.DESCRIPTOR.package, 'protobuf_unittest')
|
||||
self.assertFalse(unittest_pb2.DESCRIPTOR.serialized_pb is None)
|
||||
|
||||
def testNoGenericServices(self):
|
||||
# unittest_no_generic_services.proto should contain defs for everything
|
||||
# except services.
|
||||
self.assertTrue(hasattr(unittest_no_generic_services_pb2, "TestMessage"))
|
||||
self.assertTrue(hasattr(unittest_no_generic_services_pb2, "FOO"))
|
||||
self.assertTrue(hasattr(unittest_no_generic_services_pb2, "test_extension"))
|
||||
self.assertFalse(hasattr(unittest_no_generic_services_pb2, "TestService"))
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
|
||||
+78
-78
@@ -1,78 +1,78 @@
|
||||
# Protocol Buffers - Google's data interchange format
|
||||
# Copyright 2008 Google Inc. All rights reserved.
|
||||
# http://code.google.com/p/protobuf/
|
||||
#
|
||||
# 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.
|
||||
|
||||
"""Defines a listener interface for observing certain
|
||||
state transitions on Message objects.
|
||||
|
||||
Also defines a null implementation of this interface.
|
||||
"""
|
||||
|
||||
__author__ = 'robinson@google.com (Will Robinson)'
|
||||
|
||||
|
||||
class MessageListener(object):
|
||||
|
||||
"""Listens for modifications made to a message. Meant to be registered via
|
||||
Message._SetListener().
|
||||
|
||||
Attributes:
|
||||
dirty: If True, then calling Modified() would be a no-op. This can be
|
||||
used to avoid these calls entirely in the common case.
|
||||
"""
|
||||
|
||||
def Modified(self):
|
||||
"""Called every time the message is modified in such a way that the parent
|
||||
message may need to be updated. This currently means either:
|
||||
(a) The message was modified for the first time, so the parent message
|
||||
should henceforth mark the message as present.
|
||||
(b) The message's cached byte size became dirty -- i.e. the message was
|
||||
modified for the first time after a previous call to ByteSize().
|
||||
Therefore the parent should also mark its byte size as dirty.
|
||||
Note that (a) implies (b), since new objects start out with a client cached
|
||||
size (zero). However, we document (a) explicitly because it is important.
|
||||
|
||||
Modified() will *only* be called in response to one of these two events --
|
||||
not every time the sub-message is modified.
|
||||
|
||||
Note that if the listener's |dirty| attribute is true, then calling
|
||||
Modified at the moment would be a no-op, so it can be skipped. Performance-
|
||||
sensitive callers should check this attribute directly before calling since
|
||||
it will be true most of the time.
|
||||
"""
|
||||
|
||||
raise NotImplementedError
|
||||
|
||||
|
||||
class NullMessageListener(object):
|
||||
|
||||
"""No-op MessageListener implementation."""
|
||||
|
||||
def Modified(self):
|
||||
pass
|
||||
# Protocol Buffers - Google's data interchange format
|
||||
# Copyright 2008 Google Inc. All rights reserved.
|
||||
# http://code.google.com/p/protobuf/
|
||||
#
|
||||
# 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.
|
||||
|
||||
"""Defines a listener interface for observing certain
|
||||
state transitions on Message objects.
|
||||
|
||||
Also defines a null implementation of this interface.
|
||||
"""
|
||||
|
||||
__author__ = 'robinson@google.com (Will Robinson)'
|
||||
|
||||
|
||||
class MessageListener(object):
|
||||
|
||||
"""Listens for modifications made to a message. Meant to be registered via
|
||||
Message._SetListener().
|
||||
|
||||
Attributes:
|
||||
dirty: If True, then calling Modified() would be a no-op. This can be
|
||||
used to avoid these calls entirely in the common case.
|
||||
"""
|
||||
|
||||
def Modified(self):
|
||||
"""Called every time the message is modified in such a way that the parent
|
||||
message may need to be updated. This currently means either:
|
||||
(a) The message was modified for the first time, so the parent message
|
||||
should henceforth mark the message as present.
|
||||
(b) The message's cached byte size became dirty -- i.e. the message was
|
||||
modified for the first time after a previous call to ByteSize().
|
||||
Therefore the parent should also mark its byte size as dirty.
|
||||
Note that (a) implies (b), since new objects start out with a client cached
|
||||
size (zero). However, we document (a) explicitly because it is important.
|
||||
|
||||
Modified() will *only* be called in response to one of these two events --
|
||||
not every time the sub-message is modified.
|
||||
|
||||
Note that if the listener's |dirty| attribute is true, then calling
|
||||
Modified at the moment would be a no-op, so it can be skipped. Performance-
|
||||
sensitive callers should check this attribute directly before calling since
|
||||
it will be true most of the time.
|
||||
"""
|
||||
|
||||
raise NotImplementedError
|
||||
|
||||
|
||||
class NullMessageListener(object):
|
||||
|
||||
"""No-op MessageListener implementation."""
|
||||
|
||||
def Modified(self):
|
||||
pass
|
||||
|
||||
+89
-89
@@ -1,89 +1,89 @@
|
||||
#! /usr/bin/python
|
||||
#
|
||||
# Protocol Buffers - Google's data interchange format
|
||||
# Copyright 2008 Google Inc. All rights reserved.
|
||||
# http://code.google.com/p/protobuf/
|
||||
#
|
||||
# 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.
|
||||
|
||||
"""Tests python protocol buffers against the golden message.
|
||||
|
||||
Note that the golden messages exercise every known field type, thus this
|
||||
test ends up exercising and verifying nearly all of the parsing and
|
||||
serialization code in the whole library.
|
||||
|
||||
TODO(kenton): Merge with wire_format_test? It doesn't make a whole lot of
|
||||
sense to call this a test of the "message" module, which only declares an
|
||||
abstract interface.
|
||||
"""
|
||||
|
||||
__author__ = 'gps@google.com (Gregory P. Smith)'
|
||||
|
||||
import unittest
|
||||
from google.protobuf import unittest_import_pb2
|
||||
from google.protobuf import unittest_pb2
|
||||
from google.protobuf.internal import test_util
|
||||
|
||||
|
||||
class MessageTest(unittest.TestCase):
|
||||
|
||||
def testGoldenMessage(self):
|
||||
golden_data = test_util.GoldenFile('golden_message').read()
|
||||
golden_message = unittest_pb2.TestAllTypes()
|
||||
golden_message.ParseFromString(golden_data)
|
||||
test_util.ExpectAllFieldsSet(self, golden_message)
|
||||
self.assertTrue(golden_message.SerializeToString() == golden_data)
|
||||
|
||||
def testGoldenExtensions(self):
|
||||
golden_data = test_util.GoldenFile('golden_message').read()
|
||||
golden_message = unittest_pb2.TestAllExtensions()
|
||||
golden_message.ParseFromString(golden_data)
|
||||
all_set = unittest_pb2.TestAllExtensions()
|
||||
test_util.SetAllExtensions(all_set)
|
||||
self.assertEquals(all_set, golden_message)
|
||||
self.assertTrue(golden_message.SerializeToString() == golden_data)
|
||||
|
||||
def testGoldenPackedMessage(self):
|
||||
golden_data = test_util.GoldenFile('golden_packed_fields_message').read()
|
||||
golden_message = unittest_pb2.TestPackedTypes()
|
||||
golden_message.ParseFromString(golden_data)
|
||||
all_set = unittest_pb2.TestPackedTypes()
|
||||
test_util.SetAllPackedFields(all_set)
|
||||
self.assertEquals(all_set, golden_message)
|
||||
self.assertTrue(all_set.SerializeToString() == golden_data)
|
||||
|
||||
def testGoldenPackedExtensions(self):
|
||||
golden_data = test_util.GoldenFile('golden_packed_fields_message').read()
|
||||
golden_message = unittest_pb2.TestPackedExtensions()
|
||||
golden_message.ParseFromString(golden_data)
|
||||
all_set = unittest_pb2.TestPackedExtensions()
|
||||
test_util.SetAllPackedExtensions(all_set)
|
||||
self.assertEquals(all_set, golden_message)
|
||||
self.assertTrue(all_set.SerializeToString() == golden_data)
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
#! /usr/bin/python
|
||||
#
|
||||
# Protocol Buffers - Google's data interchange format
|
||||
# Copyright 2008 Google Inc. All rights reserved.
|
||||
# http://code.google.com/p/protobuf/
|
||||
#
|
||||
# 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.
|
||||
|
||||
"""Tests python protocol buffers against the golden message.
|
||||
|
||||
Note that the golden messages exercise every known field type, thus this
|
||||
test ends up exercising and verifying nearly all of the parsing and
|
||||
serialization code in the whole library.
|
||||
|
||||
TODO(kenton): Merge with wire_format_test? It doesn't make a whole lot of
|
||||
sense to call this a test of the "message" module, which only declares an
|
||||
abstract interface.
|
||||
"""
|
||||
|
||||
__author__ = 'gps@google.com (Gregory P. Smith)'
|
||||
|
||||
import unittest
|
||||
from google.protobuf import unittest_import_pb2
|
||||
from google.protobuf import unittest_pb2
|
||||
from google.protobuf.internal import test_util
|
||||
|
||||
|
||||
class MessageTest(unittest.TestCase):
|
||||
|
||||
def testGoldenMessage(self):
|
||||
golden_data = test_util.GoldenFile('golden_message').read()
|
||||
golden_message = unittest_pb2.TestAllTypes()
|
||||
golden_message.ParseFromString(golden_data)
|
||||
test_util.ExpectAllFieldsSet(self, golden_message)
|
||||
self.assertTrue(golden_message.SerializeToString() == golden_data)
|
||||
|
||||
def testGoldenExtensions(self):
|
||||
golden_data = test_util.GoldenFile('golden_message').read()
|
||||
golden_message = unittest_pb2.TestAllExtensions()
|
||||
golden_message.ParseFromString(golden_data)
|
||||
all_set = unittest_pb2.TestAllExtensions()
|
||||
test_util.SetAllExtensions(all_set)
|
||||
self.assertEquals(all_set, golden_message)
|
||||
self.assertTrue(golden_message.SerializeToString() == golden_data)
|
||||
|
||||
def testGoldenPackedMessage(self):
|
||||
golden_data = test_util.GoldenFile('golden_packed_fields_message').read()
|
||||
golden_message = unittest_pb2.TestPackedTypes()
|
||||
golden_message.ParseFromString(golden_data)
|
||||
all_set = unittest_pb2.TestPackedTypes()
|
||||
test_util.SetAllPackedFields(all_set)
|
||||
self.assertEquals(all_set, golden_message)
|
||||
self.assertTrue(all_set.SerializeToString() == golden_data)
|
||||
|
||||
def testGoldenPackedExtensions(self):
|
||||
golden_data = test_util.GoldenFile('golden_packed_fields_message').read()
|
||||
golden_message = unittest_pb2.TestPackedExtensions()
|
||||
golden_message.ParseFromString(golden_data)
|
||||
all_set = unittest_pb2.TestPackedExtensions()
|
||||
test_util.SetAllPackedExtensions(all_set)
|
||||
self.assertEquals(all_set, golden_message)
|
||||
self.assertTrue(all_set.SerializeToString() == golden_data)
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
|
||||
+2236
-2236
File diff suppressed because it is too large
Load Diff
Vendored
+136
-136
@@ -1,136 +1,136 @@
|
||||
#! /usr/bin/python
|
||||
#
|
||||
# Protocol Buffers - Google's data interchange format
|
||||
# Copyright 2008 Google Inc. All rights reserved.
|
||||
# http://code.google.com/p/protobuf/
|
||||
#
|
||||
# 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.
|
||||
|
||||
"""Tests for google.protobuf.internal.service_reflection."""
|
||||
|
||||
__author__ = 'petar@google.com (Petar Petrov)'
|
||||
|
||||
import unittest
|
||||
from google.protobuf import unittest_pb2
|
||||
from google.protobuf import service_reflection
|
||||
from google.protobuf import service
|
||||
|
||||
|
||||
class FooUnitTest(unittest.TestCase):
|
||||
|
||||
def testService(self):
|
||||
class MockRpcChannel(service.RpcChannel):
|
||||
def CallMethod(self, method, controller, request, response, callback):
|
||||
self.method = method
|
||||
self.controller = controller
|
||||
self.request = request
|
||||
callback(response)
|
||||
|
||||
class MockRpcController(service.RpcController):
|
||||
def SetFailed(self, msg):
|
||||
self.failure_message = msg
|
||||
|
||||
self.callback_response = None
|
||||
|
||||
class MyService(unittest_pb2.TestService):
|
||||
pass
|
||||
|
||||
self.callback_response = None
|
||||
|
||||
def MyCallback(response):
|
||||
self.callback_response = response
|
||||
|
||||
rpc_controller = MockRpcController()
|
||||
channel = MockRpcChannel()
|
||||
srvc = MyService()
|
||||
srvc.Foo(rpc_controller, unittest_pb2.FooRequest(), MyCallback)
|
||||
self.assertEqual('Method Foo not implemented.',
|
||||
rpc_controller.failure_message)
|
||||
self.assertEqual(None, self.callback_response)
|
||||
|
||||
rpc_controller.failure_message = None
|
||||
|
||||
service_descriptor = unittest_pb2.TestService.GetDescriptor()
|
||||
srvc.CallMethod(service_descriptor.methods[1], rpc_controller,
|
||||
unittest_pb2.BarRequest(), MyCallback)
|
||||
self.assertEqual('Method Bar not implemented.',
|
||||
rpc_controller.failure_message)
|
||||
self.assertEqual(None, self.callback_response)
|
||||
|
||||
class MyServiceImpl(unittest_pb2.TestService):
|
||||
def Foo(self, rpc_controller, request, done):
|
||||
self.foo_called = True
|
||||
def Bar(self, rpc_controller, request, done):
|
||||
self.bar_called = True
|
||||
|
||||
srvc = MyServiceImpl()
|
||||
rpc_controller.failure_message = None
|
||||
srvc.Foo(rpc_controller, unittest_pb2.FooRequest(), MyCallback)
|
||||
self.assertEqual(None, rpc_controller.failure_message)
|
||||
self.assertEqual(True, srvc.foo_called)
|
||||
|
||||
rpc_controller.failure_message = None
|
||||
srvc.CallMethod(service_descriptor.methods[1], rpc_controller,
|
||||
unittest_pb2.BarRequest(), MyCallback)
|
||||
self.assertEqual(None, rpc_controller.failure_message)
|
||||
self.assertEqual(True, srvc.bar_called)
|
||||
|
||||
def testServiceStub(self):
|
||||
class MockRpcChannel(service.RpcChannel):
|
||||
def CallMethod(self, method, controller, request,
|
||||
response_class, callback):
|
||||
self.method = method
|
||||
self.controller = controller
|
||||
self.request = request
|
||||
callback(response_class())
|
||||
|
||||
self.callback_response = None
|
||||
|
||||
def MyCallback(response):
|
||||
self.callback_response = response
|
||||
|
||||
channel = MockRpcChannel()
|
||||
stub = unittest_pb2.TestService_Stub(channel)
|
||||
rpc_controller = 'controller'
|
||||
request = 'request'
|
||||
|
||||
# GetDescriptor now static, still works as instance method for compatability
|
||||
self.assertEqual(unittest_pb2.TestService_Stub.GetDescriptor(),
|
||||
stub.GetDescriptor())
|
||||
|
||||
# Invoke method.
|
||||
stub.Foo(rpc_controller, request, MyCallback)
|
||||
|
||||
self.assertTrue(isinstance(self.callback_response,
|
||||
unittest_pb2.FooResponse))
|
||||
self.assertEqual(request, channel.request)
|
||||
self.assertEqual(rpc_controller, channel.controller)
|
||||
self.assertEqual(stub.GetDescriptor().methods[0], channel.method)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
#! /usr/bin/python
|
||||
#
|
||||
# Protocol Buffers - Google's data interchange format
|
||||
# Copyright 2008 Google Inc. All rights reserved.
|
||||
# http://code.google.com/p/protobuf/
|
||||
#
|
||||
# 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.
|
||||
|
||||
"""Tests for google.protobuf.internal.service_reflection."""
|
||||
|
||||
__author__ = 'petar@google.com (Petar Petrov)'
|
||||
|
||||
import unittest
|
||||
from google.protobuf import unittest_pb2
|
||||
from google.protobuf import service_reflection
|
||||
from google.protobuf import service
|
||||
|
||||
|
||||
class FooUnitTest(unittest.TestCase):
|
||||
|
||||
def testService(self):
|
||||
class MockRpcChannel(service.RpcChannel):
|
||||
def CallMethod(self, method, controller, request, response, callback):
|
||||
self.method = method
|
||||
self.controller = controller
|
||||
self.request = request
|
||||
callback(response)
|
||||
|
||||
class MockRpcController(service.RpcController):
|
||||
def SetFailed(self, msg):
|
||||
self.failure_message = msg
|
||||
|
||||
self.callback_response = None
|
||||
|
||||
class MyService(unittest_pb2.TestService):
|
||||
pass
|
||||
|
||||
self.callback_response = None
|
||||
|
||||
def MyCallback(response):
|
||||
self.callback_response = response
|
||||
|
||||
rpc_controller = MockRpcController()
|
||||
channel = MockRpcChannel()
|
||||
srvc = MyService()
|
||||
srvc.Foo(rpc_controller, unittest_pb2.FooRequest(), MyCallback)
|
||||
self.assertEqual('Method Foo not implemented.',
|
||||
rpc_controller.failure_message)
|
||||
self.assertEqual(None, self.callback_response)
|
||||
|
||||
rpc_controller.failure_message = None
|
||||
|
||||
service_descriptor = unittest_pb2.TestService.GetDescriptor()
|
||||
srvc.CallMethod(service_descriptor.methods[1], rpc_controller,
|
||||
unittest_pb2.BarRequest(), MyCallback)
|
||||
self.assertEqual('Method Bar not implemented.',
|
||||
rpc_controller.failure_message)
|
||||
self.assertEqual(None, self.callback_response)
|
||||
|
||||
class MyServiceImpl(unittest_pb2.TestService):
|
||||
def Foo(self, rpc_controller, request, done):
|
||||
self.foo_called = True
|
||||
def Bar(self, rpc_controller, request, done):
|
||||
self.bar_called = True
|
||||
|
||||
srvc = MyServiceImpl()
|
||||
rpc_controller.failure_message = None
|
||||
srvc.Foo(rpc_controller, unittest_pb2.FooRequest(), MyCallback)
|
||||
self.assertEqual(None, rpc_controller.failure_message)
|
||||
self.assertEqual(True, srvc.foo_called)
|
||||
|
||||
rpc_controller.failure_message = None
|
||||
srvc.CallMethod(service_descriptor.methods[1], rpc_controller,
|
||||
unittest_pb2.BarRequest(), MyCallback)
|
||||
self.assertEqual(None, rpc_controller.failure_message)
|
||||
self.assertEqual(True, srvc.bar_called)
|
||||
|
||||
def testServiceStub(self):
|
||||
class MockRpcChannel(service.RpcChannel):
|
||||
def CallMethod(self, method, controller, request,
|
||||
response_class, callback):
|
||||
self.method = method
|
||||
self.controller = controller
|
||||
self.request = request
|
||||
callback(response_class())
|
||||
|
||||
self.callback_response = None
|
||||
|
||||
def MyCallback(response):
|
||||
self.callback_response = response
|
||||
|
||||
channel = MockRpcChannel()
|
||||
stub = unittest_pb2.TestService_Stub(channel)
|
||||
rpc_controller = 'controller'
|
||||
request = 'request'
|
||||
|
||||
# GetDescriptor now static, still works as instance method for compatability
|
||||
self.assertEqual(unittest_pb2.TestService_Stub.GetDescriptor(),
|
||||
stub.GetDescriptor())
|
||||
|
||||
# Invoke method.
|
||||
stub.Foo(rpc_controller, request, MyCallback)
|
||||
|
||||
self.assertTrue(isinstance(self.callback_response,
|
||||
unittest_pb2.FooResponse))
|
||||
self.assertEqual(request, channel.request)
|
||||
self.assertEqual(rpc_controller, channel.controller)
|
||||
self.assertEqual(stub.GetDescriptor().methods[0], channel.method)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
|
||||
+635
-635
File diff suppressed because it is too large
Load Diff
+428
-428
@@ -1,428 +1,428 @@
|
||||
#! /usr/bin/python
|
||||
#
|
||||
# Protocol Buffers - Google's data interchange format
|
||||
# Copyright 2008 Google Inc. All rights reserved.
|
||||
# http://code.google.com/p/protobuf/
|
||||
#
|
||||
# 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.
|
||||
|
||||
"""Test for google.protobuf.text_format."""
|
||||
|
||||
__author__ = 'kenton@google.com (Kenton Varda)'
|
||||
|
||||
import difflib
|
||||
|
||||
import unittest
|
||||
from google.protobuf import text_format
|
||||
from google.protobuf.internal import test_util
|
||||
from google.protobuf import unittest_pb2
|
||||
from google.protobuf import unittest_mset_pb2
|
||||
|
||||
|
||||
class TextFormatTest(unittest.TestCase):
|
||||
def ReadGolden(self, golden_filename):
|
||||
f = test_util.GoldenFile(golden_filename)
|
||||
golden_lines = f.readlines()
|
||||
f.close()
|
||||
return golden_lines
|
||||
|
||||
def CompareToGoldenFile(self, text, golden_filename):
|
||||
golden_lines = self.ReadGolden(golden_filename)
|
||||
self.CompareToGoldenLines(text, golden_lines)
|
||||
|
||||
def CompareToGoldenText(self, text, golden_text):
|
||||
self.CompareToGoldenLines(text, golden_text.splitlines(1))
|
||||
|
||||
def CompareToGoldenLines(self, text, golden_lines):
|
||||
actual_lines = text.splitlines(1)
|
||||
self.assertEqual(golden_lines, actual_lines,
|
||||
"Text doesn't match golden. Diff:\n" +
|
||||
''.join(difflib.ndiff(golden_lines, actual_lines)))
|
||||
|
||||
def testPrintAllFields(self):
|
||||
message = unittest_pb2.TestAllTypes()
|
||||
test_util.SetAllFields(message)
|
||||
self.CompareToGoldenFile(
|
||||
self.RemoveRedundantZeros(text_format.MessageToString(message)),
|
||||
'text_format_unittest_data.txt')
|
||||
|
||||
def testPrintAllExtensions(self):
|
||||
message = unittest_pb2.TestAllExtensions()
|
||||
test_util.SetAllExtensions(message)
|
||||
self.CompareToGoldenFile(
|
||||
self.RemoveRedundantZeros(text_format.MessageToString(message)),
|
||||
'text_format_unittest_extensions_data.txt')
|
||||
|
||||
def testPrintMessageSet(self):
|
||||
message = unittest_mset_pb2.TestMessageSetContainer()
|
||||
ext1 = unittest_mset_pb2.TestMessageSetExtension1.message_set_extension
|
||||
ext2 = unittest_mset_pb2.TestMessageSetExtension2.message_set_extension
|
||||
message.message_set.Extensions[ext1].i = 23
|
||||
message.message_set.Extensions[ext2].str = 'foo'
|
||||
self.CompareToGoldenText(text_format.MessageToString(message),
|
||||
'message_set {\n'
|
||||
' [protobuf_unittest.TestMessageSetExtension1] {\n'
|
||||
' i: 23\n'
|
||||
' }\n'
|
||||
' [protobuf_unittest.TestMessageSetExtension2] {\n'
|
||||
' str: \"foo\"\n'
|
||||
' }\n'
|
||||
'}\n')
|
||||
|
||||
def testPrintExotic(self):
|
||||
message = unittest_pb2.TestAllTypes()
|
||||
message.repeated_int64.append(-9223372036854775808);
|
||||
message.repeated_uint64.append(18446744073709551615);
|
||||
message.repeated_double.append(123.456);
|
||||
message.repeated_double.append(1.23e22);
|
||||
message.repeated_double.append(1.23e-18);
|
||||
message.repeated_string.append('\000\001\a\b\f\n\r\t\v\\\'\"');
|
||||
self.CompareToGoldenText(
|
||||
self.RemoveRedundantZeros(text_format.MessageToString(message)),
|
||||
'repeated_int64: -9223372036854775808\n'
|
||||
'repeated_uint64: 18446744073709551615\n'
|
||||
'repeated_double: 123.456\n'
|
||||
'repeated_double: 1.23e+22\n'
|
||||
'repeated_double: 1.23e-18\n'
|
||||
'repeated_string: '
|
||||
'\"\\000\\001\\007\\010\\014\\n\\r\\t\\013\\\\\\\'\\\"\"\n')
|
||||
|
||||
def testMessageToString(self):
|
||||
message = unittest_pb2.ForeignMessage()
|
||||
message.c = 123
|
||||
self.assertEqual('c: 123\n', str(message))
|
||||
|
||||
def RemoveRedundantZeros(self, text):
|
||||
# Some platforms print 1e+5 as 1e+005. This is fine, but we need to remove
|
||||
# these zeros in order to match the golden file.
|
||||
return text.replace('e+0','e+').replace('e+0','e+') \
|
||||
.replace('e-0','e-').replace('e-0','e-')
|
||||
|
||||
def testMergeGolden(self):
|
||||
golden_text = '\n'.join(self.ReadGolden('text_format_unittest_data.txt'))
|
||||
parsed_message = unittest_pb2.TestAllTypes()
|
||||
text_format.Merge(golden_text, parsed_message)
|
||||
|
||||
message = unittest_pb2.TestAllTypes()
|
||||
test_util.SetAllFields(message)
|
||||
self.assertEquals(message, parsed_message)
|
||||
|
||||
def testMergeGoldenExtensions(self):
|
||||
golden_text = '\n'.join(self.ReadGolden(
|
||||
'text_format_unittest_extensions_data.txt'))
|
||||
parsed_message = unittest_pb2.TestAllExtensions()
|
||||
text_format.Merge(golden_text, parsed_message)
|
||||
|
||||
message = unittest_pb2.TestAllExtensions()
|
||||
test_util.SetAllExtensions(message)
|
||||
self.assertEquals(message, parsed_message)
|
||||
|
||||
def testMergeAllFields(self):
|
||||
message = unittest_pb2.TestAllTypes()
|
||||
test_util.SetAllFields(message)
|
||||
ascii_text = text_format.MessageToString(message)
|
||||
|
||||
parsed_message = unittest_pb2.TestAllTypes()
|
||||
text_format.Merge(ascii_text, parsed_message)
|
||||
self.assertEqual(message, parsed_message)
|
||||
test_util.ExpectAllFieldsSet(self, message)
|
||||
|
||||
def testMergeAllExtensions(self):
|
||||
message = unittest_pb2.TestAllExtensions()
|
||||
test_util.SetAllExtensions(message)
|
||||
ascii_text = text_format.MessageToString(message)
|
||||
|
||||
parsed_message = unittest_pb2.TestAllExtensions()
|
||||
text_format.Merge(ascii_text, parsed_message)
|
||||
self.assertEqual(message, parsed_message)
|
||||
|
||||
def testMergeMessageSet(self):
|
||||
message = unittest_pb2.TestAllTypes()
|
||||
text = ('repeated_uint64: 1\n'
|
||||
'repeated_uint64: 2\n')
|
||||
text_format.Merge(text, message)
|
||||
self.assertEqual(1, message.repeated_uint64[0])
|
||||
self.assertEqual(2, message.repeated_uint64[1])
|
||||
|
||||
message = unittest_mset_pb2.TestMessageSetContainer()
|
||||
text = ('message_set {\n'
|
||||
' [protobuf_unittest.TestMessageSetExtension1] {\n'
|
||||
' i: 23\n'
|
||||
' }\n'
|
||||
' [protobuf_unittest.TestMessageSetExtension2] {\n'
|
||||
' str: \"foo\"\n'
|
||||
' }\n'
|
||||
'}\n')
|
||||
text_format.Merge(text, message)
|
||||
ext1 = unittest_mset_pb2.TestMessageSetExtension1.message_set_extension
|
||||
ext2 = unittest_mset_pb2.TestMessageSetExtension2.message_set_extension
|
||||
self.assertEquals(23, message.message_set.Extensions[ext1].i)
|
||||
self.assertEquals('foo', message.message_set.Extensions[ext2].str)
|
||||
|
||||
def testMergeExotic(self):
|
||||
message = unittest_pb2.TestAllTypes()
|
||||
text = ('repeated_int64: -9223372036854775808\n'
|
||||
'repeated_uint64: 18446744073709551615\n'
|
||||
'repeated_double: 123.456\n'
|
||||
'repeated_double: 1.23e+22\n'
|
||||
'repeated_double: 1.23e-18\n'
|
||||
'repeated_string: \n'
|
||||
'\"\\000\\001\\007\\010\\014\\n\\r\\t\\013\\\\\\\'\\\"\"\n'
|
||||
'repeated_string: "foo" \'corge\' "grault"')
|
||||
text_format.Merge(text, message)
|
||||
|
||||
self.assertEqual(-9223372036854775808, message.repeated_int64[0])
|
||||
self.assertEqual(18446744073709551615, message.repeated_uint64[0])
|
||||
self.assertEqual(123.456, message.repeated_double[0])
|
||||
self.assertEqual(1.23e22, message.repeated_double[1])
|
||||
self.assertEqual(1.23e-18, message.repeated_double[2])
|
||||
self.assertEqual(
|
||||
'\000\001\a\b\f\n\r\t\v\\\'\"', message.repeated_string[0])
|
||||
self.assertEqual('foocorgegrault', message.repeated_string[1])
|
||||
|
||||
def testMergeUnknownField(self):
|
||||
message = unittest_pb2.TestAllTypes()
|
||||
text = 'unknown_field: 8\n'
|
||||
self.assertRaisesWithMessage(
|
||||
text_format.ParseError,
|
||||
('1:1 : Message type "protobuf_unittest.TestAllTypes" has no field named '
|
||||
'"unknown_field".'),
|
||||
text_format.Merge, text, message)
|
||||
|
||||
def testMergeBadExtension(self):
|
||||
message = unittest_pb2.TestAllExtensions()
|
||||
text = '[unknown_extension]: 8\n'
|
||||
self.assertRaisesWithMessage(
|
||||
text_format.ParseError,
|
||||
'1:2 : Extension "unknown_extension" not registered.',
|
||||
text_format.Merge, text, message)
|
||||
message = unittest_pb2.TestAllTypes()
|
||||
self.assertRaisesWithMessage(
|
||||
text_format.ParseError,
|
||||
('1:2 : Message type "protobuf_unittest.TestAllTypes" does not have '
|
||||
'extensions.'),
|
||||
text_format.Merge, text, message)
|
||||
|
||||
def testMergeGroupNotClosed(self):
|
||||
message = unittest_pb2.TestAllTypes()
|
||||
text = 'RepeatedGroup: <'
|
||||
self.assertRaisesWithMessage(
|
||||
text_format.ParseError, '1:16 : Expected ">".',
|
||||
text_format.Merge, text, message)
|
||||
|
||||
text = 'RepeatedGroup: {'
|
||||
self.assertRaisesWithMessage(
|
||||
text_format.ParseError, '1:16 : Expected "}".',
|
||||
text_format.Merge, text, message)
|
||||
|
||||
def testMergeEmptyGroup(self):
|
||||
message = unittest_pb2.TestAllTypes()
|
||||
text = 'OptionalGroup: {}'
|
||||
text_format.Merge(text, message)
|
||||
self.assertTrue(message.HasField('optionalgroup'))
|
||||
|
||||
message.Clear()
|
||||
|
||||
message = unittest_pb2.TestAllTypes()
|
||||
text = 'OptionalGroup: <>'
|
||||
text_format.Merge(text, message)
|
||||
self.assertTrue(message.HasField('optionalgroup'))
|
||||
|
||||
def testMergeBadEnumValue(self):
|
||||
message = unittest_pb2.TestAllTypes()
|
||||
text = 'optional_nested_enum: BARR'
|
||||
self.assertRaisesWithMessage(
|
||||
text_format.ParseError,
|
||||
('1:23 : Enum type "protobuf_unittest.TestAllTypes.NestedEnum" '
|
||||
'has no value named BARR.'),
|
||||
text_format.Merge, text, message)
|
||||
|
||||
message = unittest_pb2.TestAllTypes()
|
||||
text = 'optional_nested_enum: 100'
|
||||
self.assertRaisesWithMessage(
|
||||
text_format.ParseError,
|
||||
('1:23 : Enum type "protobuf_unittest.TestAllTypes.NestedEnum" '
|
||||
'has no value with number 100.'),
|
||||
text_format.Merge, text, message)
|
||||
|
||||
def assertRaisesWithMessage(self, e_class, e, func, *args, **kwargs):
|
||||
"""Same as assertRaises, but also compares the exception message."""
|
||||
if hasattr(e_class, '__name__'):
|
||||
exc_name = e_class.__name__
|
||||
else:
|
||||
exc_name = str(e_class)
|
||||
|
||||
try:
|
||||
func(*args, **kwargs)
|
||||
except e_class, expr:
|
||||
if str(expr) != e:
|
||||
msg = '%s raised, but with wrong message: "%s" instead of "%s"'
|
||||
raise self.failureException(msg % (exc_name,
|
||||
str(expr).encode('string_escape'),
|
||||
e.encode('string_escape')))
|
||||
return
|
||||
else:
|
||||
raise self.failureException('%s not raised' % exc_name)
|
||||
|
||||
|
||||
class TokenizerTest(unittest.TestCase):
|
||||
|
||||
def testSimpleTokenCases(self):
|
||||
text = ('identifier1:"string1"\n \n\n'
|
||||
'identifier2 : \n \n123 \n identifier3 :\'string\'\n'
|
||||
'identifiER_4 : 1.1e+2 ID5:-0.23 ID6:\'aaaa\\\'bbbb\'\n'
|
||||
'ID7 : "aa\\"bb"\n\n\n\n ID8: {A:inf B:-inf C:true D:false}\n'
|
||||
'ID9: 22 ID10: -111111111111111111 ID11: -22\n'
|
||||
'ID12: 2222222222222222222')
|
||||
tokenizer = text_format._Tokenizer(text)
|
||||
methods = [(tokenizer.ConsumeIdentifier, 'identifier1'),
|
||||
':',
|
||||
(tokenizer.ConsumeString, 'string1'),
|
||||
(tokenizer.ConsumeIdentifier, 'identifier2'),
|
||||
':',
|
||||
(tokenizer.ConsumeInt32, 123),
|
||||
(tokenizer.ConsumeIdentifier, 'identifier3'),
|
||||
':',
|
||||
(tokenizer.ConsumeString, 'string'),
|
||||
(tokenizer.ConsumeIdentifier, 'identifiER_4'),
|
||||
':',
|
||||
(tokenizer.ConsumeFloat, 1.1e+2),
|
||||
(tokenizer.ConsumeIdentifier, 'ID5'),
|
||||
':',
|
||||
(tokenizer.ConsumeFloat, -0.23),
|
||||
(tokenizer.ConsumeIdentifier, 'ID6'),
|
||||
':',
|
||||
(tokenizer.ConsumeString, 'aaaa\'bbbb'),
|
||||
(tokenizer.ConsumeIdentifier, 'ID7'),
|
||||
':',
|
||||
(tokenizer.ConsumeString, 'aa\"bb'),
|
||||
(tokenizer.ConsumeIdentifier, 'ID8'),
|
||||
':',
|
||||
'{',
|
||||
(tokenizer.ConsumeIdentifier, 'A'),
|
||||
':',
|
||||
(tokenizer.ConsumeFloat, text_format._INFINITY),
|
||||
(tokenizer.ConsumeIdentifier, 'B'),
|
||||
':',
|
||||
(tokenizer.ConsumeFloat, -text_format._INFINITY),
|
||||
(tokenizer.ConsumeIdentifier, 'C'),
|
||||
':',
|
||||
(tokenizer.ConsumeBool, True),
|
||||
(tokenizer.ConsumeIdentifier, 'D'),
|
||||
':',
|
||||
(tokenizer.ConsumeBool, False),
|
||||
'}',
|
||||
(tokenizer.ConsumeIdentifier, 'ID9'),
|
||||
':',
|
||||
(tokenizer.ConsumeUint32, 22),
|
||||
(tokenizer.ConsumeIdentifier, 'ID10'),
|
||||
':',
|
||||
(tokenizer.ConsumeInt64, -111111111111111111),
|
||||
(tokenizer.ConsumeIdentifier, 'ID11'),
|
||||
':',
|
||||
(tokenizer.ConsumeInt32, -22),
|
||||
(tokenizer.ConsumeIdentifier, 'ID12'),
|
||||
':',
|
||||
(tokenizer.ConsumeUint64, 2222222222222222222)]
|
||||
|
||||
i = 0
|
||||
while not tokenizer.AtEnd():
|
||||
m = methods[i]
|
||||
if type(m) == str:
|
||||
token = tokenizer.token
|
||||
self.assertEqual(token, m)
|
||||
tokenizer.NextToken()
|
||||
else:
|
||||
self.assertEqual(m[1], m[0]())
|
||||
i += 1
|
||||
|
||||
def testConsumeIntegers(self):
|
||||
# This test only tests the failures in the integer parsing methods as well
|
||||
# as the '0' special cases.
|
||||
int64_max = (1 << 63) - 1
|
||||
uint32_max = (1 << 32) - 1
|
||||
text = '-1 %d %d' % (uint32_max + 1, int64_max + 1)
|
||||
tokenizer = text_format._Tokenizer(text)
|
||||
self.assertRaises(text_format.ParseError, tokenizer.ConsumeUint32)
|
||||
self.assertRaises(text_format.ParseError, tokenizer.ConsumeUint64)
|
||||
self.assertEqual(-1, tokenizer.ConsumeInt32())
|
||||
|
||||
self.assertRaises(text_format.ParseError, tokenizer.ConsumeUint32)
|
||||
self.assertRaises(text_format.ParseError, tokenizer.ConsumeInt32)
|
||||
self.assertEqual(uint32_max + 1, tokenizer.ConsumeInt64())
|
||||
|
||||
self.assertRaises(text_format.ParseError, tokenizer.ConsumeInt64)
|
||||
self.assertEqual(int64_max + 1, tokenizer.ConsumeUint64())
|
||||
self.assertTrue(tokenizer.AtEnd())
|
||||
|
||||
text = '-0 -0 0 0'
|
||||
tokenizer = text_format._Tokenizer(text)
|
||||
self.assertEqual(0, tokenizer.ConsumeUint32())
|
||||
self.assertEqual(0, tokenizer.ConsumeUint64())
|
||||
self.assertEqual(0, tokenizer.ConsumeUint32())
|
||||
self.assertEqual(0, tokenizer.ConsumeUint64())
|
||||
self.assertTrue(tokenizer.AtEnd())
|
||||
|
||||
def testConsumeByteString(self):
|
||||
text = '"string1\''
|
||||
tokenizer = text_format._Tokenizer(text)
|
||||
self.assertRaises(text_format.ParseError, tokenizer.ConsumeByteString)
|
||||
|
||||
text = 'string1"'
|
||||
tokenizer = text_format._Tokenizer(text)
|
||||
self.assertRaises(text_format.ParseError, tokenizer.ConsumeByteString)
|
||||
|
||||
text = '\n"\\xt"'
|
||||
tokenizer = text_format._Tokenizer(text)
|
||||
self.assertRaises(text_format.ParseError, tokenizer.ConsumeByteString)
|
||||
|
||||
text = '\n"\\"'
|
||||
tokenizer = text_format._Tokenizer(text)
|
||||
self.assertRaises(text_format.ParseError, tokenizer.ConsumeByteString)
|
||||
|
||||
text = '\n"\\x"'
|
||||
tokenizer = text_format._Tokenizer(text)
|
||||
self.assertRaises(text_format.ParseError, tokenizer.ConsumeByteString)
|
||||
|
||||
def testConsumeBool(self):
|
||||
text = 'not-a-bool'
|
||||
tokenizer = text_format._Tokenizer(text)
|
||||
self.assertRaises(text_format.ParseError, tokenizer.ConsumeBool)
|
||||
|
||||
def testInfNan(self):
|
||||
# Make sure our infinity and NaN definitions are sound.
|
||||
self.assertEquals(float, type(text_format._INFINITY))
|
||||
self.assertEquals(float, type(text_format._NAN))
|
||||
self.assertTrue(text_format._NAN != text_format._NAN)
|
||||
|
||||
inf_times_zero = text_format._INFINITY * 0
|
||||
self.assertTrue(inf_times_zero != inf_times_zero)
|
||||
self.assertTrue(text_format._INFINITY > 0)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
#! /usr/bin/python
|
||||
#
|
||||
# Protocol Buffers - Google's data interchange format
|
||||
# Copyright 2008 Google Inc. All rights reserved.
|
||||
# http://code.google.com/p/protobuf/
|
||||
#
|
||||
# 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.
|
||||
|
||||
"""Test for google.protobuf.text_format."""
|
||||
|
||||
__author__ = 'kenton@google.com (Kenton Varda)'
|
||||
|
||||
import difflib
|
||||
|
||||
import unittest
|
||||
from google.protobuf import text_format
|
||||
from google.protobuf.internal import test_util
|
||||
from google.protobuf import unittest_pb2
|
||||
from google.protobuf import unittest_mset_pb2
|
||||
|
||||
|
||||
class TextFormatTest(unittest.TestCase):
|
||||
def ReadGolden(self, golden_filename):
|
||||
f = test_util.GoldenFile(golden_filename)
|
||||
golden_lines = f.readlines()
|
||||
f.close()
|
||||
return golden_lines
|
||||
|
||||
def CompareToGoldenFile(self, text, golden_filename):
|
||||
golden_lines = self.ReadGolden(golden_filename)
|
||||
self.CompareToGoldenLines(text, golden_lines)
|
||||
|
||||
def CompareToGoldenText(self, text, golden_text):
|
||||
self.CompareToGoldenLines(text, golden_text.splitlines(1))
|
||||
|
||||
def CompareToGoldenLines(self, text, golden_lines):
|
||||
actual_lines = text.splitlines(1)
|
||||
self.assertEqual(golden_lines, actual_lines,
|
||||
"Text doesn't match golden. Diff:\n" +
|
||||
''.join(difflib.ndiff(golden_lines, actual_lines)))
|
||||
|
||||
def testPrintAllFields(self):
|
||||
message = unittest_pb2.TestAllTypes()
|
||||
test_util.SetAllFields(message)
|
||||
self.CompareToGoldenFile(
|
||||
self.RemoveRedundantZeros(text_format.MessageToString(message)),
|
||||
'text_format_unittest_data.txt')
|
||||
|
||||
def testPrintAllExtensions(self):
|
||||
message = unittest_pb2.TestAllExtensions()
|
||||
test_util.SetAllExtensions(message)
|
||||
self.CompareToGoldenFile(
|
||||
self.RemoveRedundantZeros(text_format.MessageToString(message)),
|
||||
'text_format_unittest_extensions_data.txt')
|
||||
|
||||
def testPrintMessageSet(self):
|
||||
message = unittest_mset_pb2.TestMessageSetContainer()
|
||||
ext1 = unittest_mset_pb2.TestMessageSetExtension1.message_set_extension
|
||||
ext2 = unittest_mset_pb2.TestMessageSetExtension2.message_set_extension
|
||||
message.message_set.Extensions[ext1].i = 23
|
||||
message.message_set.Extensions[ext2].str = 'foo'
|
||||
self.CompareToGoldenText(text_format.MessageToString(message),
|
||||
'message_set {\n'
|
||||
' [protobuf_unittest.TestMessageSetExtension1] {\n'
|
||||
' i: 23\n'
|
||||
' }\n'
|
||||
' [protobuf_unittest.TestMessageSetExtension2] {\n'
|
||||
' str: \"foo\"\n'
|
||||
' }\n'
|
||||
'}\n')
|
||||
|
||||
def testPrintExotic(self):
|
||||
message = unittest_pb2.TestAllTypes()
|
||||
message.repeated_int64.append(-9223372036854775808);
|
||||
message.repeated_uint64.append(18446744073709551615);
|
||||
message.repeated_double.append(123.456);
|
||||
message.repeated_double.append(1.23e22);
|
||||
message.repeated_double.append(1.23e-18);
|
||||
message.repeated_string.append('\000\001\a\b\f\n\r\t\v\\\'\"');
|
||||
self.CompareToGoldenText(
|
||||
self.RemoveRedundantZeros(text_format.MessageToString(message)),
|
||||
'repeated_int64: -9223372036854775808\n'
|
||||
'repeated_uint64: 18446744073709551615\n'
|
||||
'repeated_double: 123.456\n'
|
||||
'repeated_double: 1.23e+22\n'
|
||||
'repeated_double: 1.23e-18\n'
|
||||
'repeated_string: '
|
||||
'\"\\000\\001\\007\\010\\014\\n\\r\\t\\013\\\\\\\'\\\"\"\n')
|
||||
|
||||
def testMessageToString(self):
|
||||
message = unittest_pb2.ForeignMessage()
|
||||
message.c = 123
|
||||
self.assertEqual('c: 123\n', str(message))
|
||||
|
||||
def RemoveRedundantZeros(self, text):
|
||||
# Some platforms print 1e+5 as 1e+005. This is fine, but we need to remove
|
||||
# these zeros in order to match the golden file.
|
||||
return text.replace('e+0','e+').replace('e+0','e+') \
|
||||
.replace('e-0','e-').replace('e-0','e-')
|
||||
|
||||
def testMergeGolden(self):
|
||||
golden_text = '\n'.join(self.ReadGolden('text_format_unittest_data.txt'))
|
||||
parsed_message = unittest_pb2.TestAllTypes()
|
||||
text_format.Merge(golden_text, parsed_message)
|
||||
|
||||
message = unittest_pb2.TestAllTypes()
|
||||
test_util.SetAllFields(message)
|
||||
self.assertEquals(message, parsed_message)
|
||||
|
||||
def testMergeGoldenExtensions(self):
|
||||
golden_text = '\n'.join(self.ReadGolden(
|
||||
'text_format_unittest_extensions_data.txt'))
|
||||
parsed_message = unittest_pb2.TestAllExtensions()
|
||||
text_format.Merge(golden_text, parsed_message)
|
||||
|
||||
message = unittest_pb2.TestAllExtensions()
|
||||
test_util.SetAllExtensions(message)
|
||||
self.assertEquals(message, parsed_message)
|
||||
|
||||
def testMergeAllFields(self):
|
||||
message = unittest_pb2.TestAllTypes()
|
||||
test_util.SetAllFields(message)
|
||||
ascii_text = text_format.MessageToString(message)
|
||||
|
||||
parsed_message = unittest_pb2.TestAllTypes()
|
||||
text_format.Merge(ascii_text, parsed_message)
|
||||
self.assertEqual(message, parsed_message)
|
||||
test_util.ExpectAllFieldsSet(self, message)
|
||||
|
||||
def testMergeAllExtensions(self):
|
||||
message = unittest_pb2.TestAllExtensions()
|
||||
test_util.SetAllExtensions(message)
|
||||
ascii_text = text_format.MessageToString(message)
|
||||
|
||||
parsed_message = unittest_pb2.TestAllExtensions()
|
||||
text_format.Merge(ascii_text, parsed_message)
|
||||
self.assertEqual(message, parsed_message)
|
||||
|
||||
def testMergeMessageSet(self):
|
||||
message = unittest_pb2.TestAllTypes()
|
||||
text = ('repeated_uint64: 1\n'
|
||||
'repeated_uint64: 2\n')
|
||||
text_format.Merge(text, message)
|
||||
self.assertEqual(1, message.repeated_uint64[0])
|
||||
self.assertEqual(2, message.repeated_uint64[1])
|
||||
|
||||
message = unittest_mset_pb2.TestMessageSetContainer()
|
||||
text = ('message_set {\n'
|
||||
' [protobuf_unittest.TestMessageSetExtension1] {\n'
|
||||
' i: 23\n'
|
||||
' }\n'
|
||||
' [protobuf_unittest.TestMessageSetExtension2] {\n'
|
||||
' str: \"foo\"\n'
|
||||
' }\n'
|
||||
'}\n')
|
||||
text_format.Merge(text, message)
|
||||
ext1 = unittest_mset_pb2.TestMessageSetExtension1.message_set_extension
|
||||
ext2 = unittest_mset_pb2.TestMessageSetExtension2.message_set_extension
|
||||
self.assertEquals(23, message.message_set.Extensions[ext1].i)
|
||||
self.assertEquals('foo', message.message_set.Extensions[ext2].str)
|
||||
|
||||
def testMergeExotic(self):
|
||||
message = unittest_pb2.TestAllTypes()
|
||||
text = ('repeated_int64: -9223372036854775808\n'
|
||||
'repeated_uint64: 18446744073709551615\n'
|
||||
'repeated_double: 123.456\n'
|
||||
'repeated_double: 1.23e+22\n'
|
||||
'repeated_double: 1.23e-18\n'
|
||||
'repeated_string: \n'
|
||||
'\"\\000\\001\\007\\010\\014\\n\\r\\t\\013\\\\\\\'\\\"\"\n'
|
||||
'repeated_string: "foo" \'corge\' "grault"')
|
||||
text_format.Merge(text, message)
|
||||
|
||||
self.assertEqual(-9223372036854775808, message.repeated_int64[0])
|
||||
self.assertEqual(18446744073709551615, message.repeated_uint64[0])
|
||||
self.assertEqual(123.456, message.repeated_double[0])
|
||||
self.assertEqual(1.23e22, message.repeated_double[1])
|
||||
self.assertEqual(1.23e-18, message.repeated_double[2])
|
||||
self.assertEqual(
|
||||
'\000\001\a\b\f\n\r\t\v\\\'\"', message.repeated_string[0])
|
||||
self.assertEqual('foocorgegrault', message.repeated_string[1])
|
||||
|
||||
def testMergeUnknownField(self):
|
||||
message = unittest_pb2.TestAllTypes()
|
||||
text = 'unknown_field: 8\n'
|
||||
self.assertRaisesWithMessage(
|
||||
text_format.ParseError,
|
||||
('1:1 : Message type "protobuf_unittest.TestAllTypes" has no field named '
|
||||
'"unknown_field".'),
|
||||
text_format.Merge, text, message)
|
||||
|
||||
def testMergeBadExtension(self):
|
||||
message = unittest_pb2.TestAllExtensions()
|
||||
text = '[unknown_extension]: 8\n'
|
||||
self.assertRaisesWithMessage(
|
||||
text_format.ParseError,
|
||||
'1:2 : Extension "unknown_extension" not registered.',
|
||||
text_format.Merge, text, message)
|
||||
message = unittest_pb2.TestAllTypes()
|
||||
self.assertRaisesWithMessage(
|
||||
text_format.ParseError,
|
||||
('1:2 : Message type "protobuf_unittest.TestAllTypes" does not have '
|
||||
'extensions.'),
|
||||
text_format.Merge, text, message)
|
||||
|
||||
def testMergeGroupNotClosed(self):
|
||||
message = unittest_pb2.TestAllTypes()
|
||||
text = 'RepeatedGroup: <'
|
||||
self.assertRaisesWithMessage(
|
||||
text_format.ParseError, '1:16 : Expected ">".',
|
||||
text_format.Merge, text, message)
|
||||
|
||||
text = 'RepeatedGroup: {'
|
||||
self.assertRaisesWithMessage(
|
||||
text_format.ParseError, '1:16 : Expected "}".',
|
||||
text_format.Merge, text, message)
|
||||
|
||||
def testMergeEmptyGroup(self):
|
||||
message = unittest_pb2.TestAllTypes()
|
||||
text = 'OptionalGroup: {}'
|
||||
text_format.Merge(text, message)
|
||||
self.assertTrue(message.HasField('optionalgroup'))
|
||||
|
||||
message.Clear()
|
||||
|
||||
message = unittest_pb2.TestAllTypes()
|
||||
text = 'OptionalGroup: <>'
|
||||
text_format.Merge(text, message)
|
||||
self.assertTrue(message.HasField('optionalgroup'))
|
||||
|
||||
def testMergeBadEnumValue(self):
|
||||
message = unittest_pb2.TestAllTypes()
|
||||
text = 'optional_nested_enum: BARR'
|
||||
self.assertRaisesWithMessage(
|
||||
text_format.ParseError,
|
||||
('1:23 : Enum type "protobuf_unittest.TestAllTypes.NestedEnum" '
|
||||
'has no value named BARR.'),
|
||||
text_format.Merge, text, message)
|
||||
|
||||
message = unittest_pb2.TestAllTypes()
|
||||
text = 'optional_nested_enum: 100'
|
||||
self.assertRaisesWithMessage(
|
||||
text_format.ParseError,
|
||||
('1:23 : Enum type "protobuf_unittest.TestAllTypes.NestedEnum" '
|
||||
'has no value with number 100.'),
|
||||
text_format.Merge, text, message)
|
||||
|
||||
def assertRaisesWithMessage(self, e_class, e, func, *args, **kwargs):
|
||||
"""Same as assertRaises, but also compares the exception message."""
|
||||
if hasattr(e_class, '__name__'):
|
||||
exc_name = e_class.__name__
|
||||
else:
|
||||
exc_name = str(e_class)
|
||||
|
||||
try:
|
||||
func(*args, **kwargs)
|
||||
except e_class, expr:
|
||||
if str(expr) != e:
|
||||
msg = '%s raised, but with wrong message: "%s" instead of "%s"'
|
||||
raise self.failureException(msg % (exc_name,
|
||||
str(expr).encode('string_escape'),
|
||||
e.encode('string_escape')))
|
||||
return
|
||||
else:
|
||||
raise self.failureException('%s not raised' % exc_name)
|
||||
|
||||
|
||||
class TokenizerTest(unittest.TestCase):
|
||||
|
||||
def testSimpleTokenCases(self):
|
||||
text = ('identifier1:"string1"\n \n\n'
|
||||
'identifier2 : \n \n123 \n identifier3 :\'string\'\n'
|
||||
'identifiER_4 : 1.1e+2 ID5:-0.23 ID6:\'aaaa\\\'bbbb\'\n'
|
||||
'ID7 : "aa\\"bb"\n\n\n\n ID8: {A:inf B:-inf C:true D:false}\n'
|
||||
'ID9: 22 ID10: -111111111111111111 ID11: -22\n'
|
||||
'ID12: 2222222222222222222')
|
||||
tokenizer = text_format._Tokenizer(text)
|
||||
methods = [(tokenizer.ConsumeIdentifier, 'identifier1'),
|
||||
':',
|
||||
(tokenizer.ConsumeString, 'string1'),
|
||||
(tokenizer.ConsumeIdentifier, 'identifier2'),
|
||||
':',
|
||||
(tokenizer.ConsumeInt32, 123),
|
||||
(tokenizer.ConsumeIdentifier, 'identifier3'),
|
||||
':',
|
||||
(tokenizer.ConsumeString, 'string'),
|
||||
(tokenizer.ConsumeIdentifier, 'identifiER_4'),
|
||||
':',
|
||||
(tokenizer.ConsumeFloat, 1.1e+2),
|
||||
(tokenizer.ConsumeIdentifier, 'ID5'),
|
||||
':',
|
||||
(tokenizer.ConsumeFloat, -0.23),
|
||||
(tokenizer.ConsumeIdentifier, 'ID6'),
|
||||
':',
|
||||
(tokenizer.ConsumeString, 'aaaa\'bbbb'),
|
||||
(tokenizer.ConsumeIdentifier, 'ID7'),
|
||||
':',
|
||||
(tokenizer.ConsumeString, 'aa\"bb'),
|
||||
(tokenizer.ConsumeIdentifier, 'ID8'),
|
||||
':',
|
||||
'{',
|
||||
(tokenizer.ConsumeIdentifier, 'A'),
|
||||
':',
|
||||
(tokenizer.ConsumeFloat, text_format._INFINITY),
|
||||
(tokenizer.ConsumeIdentifier, 'B'),
|
||||
':',
|
||||
(tokenizer.ConsumeFloat, -text_format._INFINITY),
|
||||
(tokenizer.ConsumeIdentifier, 'C'),
|
||||
':',
|
||||
(tokenizer.ConsumeBool, True),
|
||||
(tokenizer.ConsumeIdentifier, 'D'),
|
||||
':',
|
||||
(tokenizer.ConsumeBool, False),
|
||||
'}',
|
||||
(tokenizer.ConsumeIdentifier, 'ID9'),
|
||||
':',
|
||||
(tokenizer.ConsumeUint32, 22),
|
||||
(tokenizer.ConsumeIdentifier, 'ID10'),
|
||||
':',
|
||||
(tokenizer.ConsumeInt64, -111111111111111111),
|
||||
(tokenizer.ConsumeIdentifier, 'ID11'),
|
||||
':',
|
||||
(tokenizer.ConsumeInt32, -22),
|
||||
(tokenizer.ConsumeIdentifier, 'ID12'),
|
||||
':',
|
||||
(tokenizer.ConsumeUint64, 2222222222222222222)]
|
||||
|
||||
i = 0
|
||||
while not tokenizer.AtEnd():
|
||||
m = methods[i]
|
||||
if type(m) == str:
|
||||
token = tokenizer.token
|
||||
self.assertEqual(token, m)
|
||||
tokenizer.NextToken()
|
||||
else:
|
||||
self.assertEqual(m[1], m[0]())
|
||||
i += 1
|
||||
|
||||
def testConsumeIntegers(self):
|
||||
# This test only tests the failures in the integer parsing methods as well
|
||||
# as the '0' special cases.
|
||||
int64_max = (1 << 63) - 1
|
||||
uint32_max = (1 << 32) - 1
|
||||
text = '-1 %d %d' % (uint32_max + 1, int64_max + 1)
|
||||
tokenizer = text_format._Tokenizer(text)
|
||||
self.assertRaises(text_format.ParseError, tokenizer.ConsumeUint32)
|
||||
self.assertRaises(text_format.ParseError, tokenizer.ConsumeUint64)
|
||||
self.assertEqual(-1, tokenizer.ConsumeInt32())
|
||||
|
||||
self.assertRaises(text_format.ParseError, tokenizer.ConsumeUint32)
|
||||
self.assertRaises(text_format.ParseError, tokenizer.ConsumeInt32)
|
||||
self.assertEqual(uint32_max + 1, tokenizer.ConsumeInt64())
|
||||
|
||||
self.assertRaises(text_format.ParseError, tokenizer.ConsumeInt64)
|
||||
self.assertEqual(int64_max + 1, tokenizer.ConsumeUint64())
|
||||
self.assertTrue(tokenizer.AtEnd())
|
||||
|
||||
text = '-0 -0 0 0'
|
||||
tokenizer = text_format._Tokenizer(text)
|
||||
self.assertEqual(0, tokenizer.ConsumeUint32())
|
||||
self.assertEqual(0, tokenizer.ConsumeUint64())
|
||||
self.assertEqual(0, tokenizer.ConsumeUint32())
|
||||
self.assertEqual(0, tokenizer.ConsumeUint64())
|
||||
self.assertTrue(tokenizer.AtEnd())
|
||||
|
||||
def testConsumeByteString(self):
|
||||
text = '"string1\''
|
||||
tokenizer = text_format._Tokenizer(text)
|
||||
self.assertRaises(text_format.ParseError, tokenizer.ConsumeByteString)
|
||||
|
||||
text = 'string1"'
|
||||
tokenizer = text_format._Tokenizer(text)
|
||||
self.assertRaises(text_format.ParseError, tokenizer.ConsumeByteString)
|
||||
|
||||
text = '\n"\\xt"'
|
||||
tokenizer = text_format._Tokenizer(text)
|
||||
self.assertRaises(text_format.ParseError, tokenizer.ConsumeByteString)
|
||||
|
||||
text = '\n"\\"'
|
||||
tokenizer = text_format._Tokenizer(text)
|
||||
self.assertRaises(text_format.ParseError, tokenizer.ConsumeByteString)
|
||||
|
||||
text = '\n"\\x"'
|
||||
tokenizer = text_format._Tokenizer(text)
|
||||
self.assertRaises(text_format.ParseError, tokenizer.ConsumeByteString)
|
||||
|
||||
def testConsumeBool(self):
|
||||
text = 'not-a-bool'
|
||||
tokenizer = text_format._Tokenizer(text)
|
||||
self.assertRaises(text_format.ParseError, tokenizer.ConsumeBool)
|
||||
|
||||
def testInfNan(self):
|
||||
# Make sure our infinity and NaN definitions are sound.
|
||||
self.assertEquals(float, type(text_format._INFINITY))
|
||||
self.assertEquals(float, type(text_format._NAN))
|
||||
self.assertTrue(text_format._NAN != text_format._NAN)
|
||||
|
||||
inf_times_zero = text_format._INFINITY * 0
|
||||
self.assertTrue(inf_times_zero != inf_times_zero)
|
||||
self.assertTrue(text_format._INFINITY > 0)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
|
||||
+286
-286
@@ -1,286 +1,286 @@
|
||||
# Protocol Buffers - Google's data interchange format
|
||||
# Copyright 2008 Google Inc. All rights reserved.
|
||||
# http://code.google.com/p/protobuf/
|
||||
#
|
||||
# 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.
|
||||
|
||||
"""Provides type checking routines.
|
||||
|
||||
This module defines type checking utilities in the forms of dictionaries:
|
||||
|
||||
VALUE_CHECKERS: A dictionary of field types and a value validation object.
|
||||
TYPE_TO_BYTE_SIZE_FN: A dictionary with field types and a size computing
|
||||
function.
|
||||
TYPE_TO_SERIALIZE_METHOD: A dictionary with field types and serialization
|
||||
function.
|
||||
FIELD_TYPE_TO_WIRE_TYPE: A dictionary with field typed and their
|
||||
coresponding wire types.
|
||||
TYPE_TO_DESERIALIZE_METHOD: A dictionary with field types and deserialization
|
||||
function.
|
||||
"""
|
||||
|
||||
__author__ = 'robinson@google.com (Will Robinson)'
|
||||
|
||||
from google.protobuf.internal import decoder
|
||||
from google.protobuf.internal import encoder
|
||||
from google.protobuf.internal import wire_format
|
||||
from google.protobuf import descriptor
|
||||
|
||||
_FieldDescriptor = descriptor.FieldDescriptor
|
||||
|
||||
|
||||
def GetTypeChecker(cpp_type, field_type):
|
||||
"""Returns a type checker for a message field of the specified types.
|
||||
|
||||
Args:
|
||||
cpp_type: C++ type of the field (see descriptor.py).
|
||||
field_type: Protocol message field type (see descriptor.py).
|
||||
|
||||
Returns:
|
||||
An instance of TypeChecker which can be used to verify the types
|
||||
of values assigned to a field of the specified type.
|
||||
"""
|
||||
if (cpp_type == _FieldDescriptor.CPPTYPE_STRING and
|
||||
field_type == _FieldDescriptor.TYPE_STRING):
|
||||
return UnicodeValueChecker()
|
||||
return _VALUE_CHECKERS[cpp_type]
|
||||
|
||||
|
||||
# None of the typecheckers below make any attempt to guard against people
|
||||
# subclassing builtin types and doing weird things. We're not trying to
|
||||
# protect against malicious clients here, just people accidentally shooting
|
||||
# themselves in the foot in obvious ways.
|
||||
|
||||
class TypeChecker(object):
|
||||
|
||||
"""Type checker used to catch type errors as early as possible
|
||||
when the client is setting scalar fields in protocol messages.
|
||||
"""
|
||||
|
||||
def __init__(self, *acceptable_types):
|
||||
self._acceptable_types = acceptable_types
|
||||
|
||||
def CheckValue(self, proposed_value):
|
||||
if not isinstance(proposed_value, self._acceptable_types):
|
||||
message = ('%.1024r has type %s, but expected one of: %s' %
|
||||
(proposed_value, type(proposed_value), self._acceptable_types))
|
||||
raise TypeError(message)
|
||||
|
||||
|
||||
# IntValueChecker and its subclasses perform integer type-checks
|
||||
# and bounds-checks.
|
||||
class IntValueChecker(object):
|
||||
|
||||
"""Checker used for integer fields. Performs type-check and range check."""
|
||||
|
||||
def CheckValue(self, proposed_value):
|
||||
if not isinstance(proposed_value, (int, long)):
|
||||
message = ('%.1024r has type %s, but expected one of: %s' %
|
||||
(proposed_value, type(proposed_value), (int, long)))
|
||||
raise TypeError(message)
|
||||
if not self._MIN <= proposed_value <= self._MAX:
|
||||
raise ValueError('Value out of range: %d' % proposed_value)
|
||||
|
||||
|
||||
class UnicodeValueChecker(object):
|
||||
|
||||
"""Checker used for string fields."""
|
||||
|
||||
def CheckValue(self, proposed_value):
|
||||
if not isinstance(proposed_value, (str, unicode)):
|
||||
message = ('%.1024r has type %s, but expected one of: %s' %
|
||||
(proposed_value, type(proposed_value), (str, unicode)))
|
||||
raise TypeError(message)
|
||||
|
||||
# If the value is of type 'str' make sure that it is in 7-bit ASCII
|
||||
# encoding.
|
||||
if isinstance(proposed_value, str):
|
||||
try:
|
||||
unicode(proposed_value, 'ascii')
|
||||
except UnicodeDecodeError:
|
||||
raise ValueError('%.1024r has type str, but isn\'t in 7-bit ASCII '
|
||||
'encoding. Non-ASCII strings must be converted to '
|
||||
'unicode objects before being added.' %
|
||||
(proposed_value))
|
||||
|
||||
|
||||
class Int32ValueChecker(IntValueChecker):
|
||||
# We're sure to use ints instead of longs here since comparison may be more
|
||||
# efficient.
|
||||
_MIN = -2147483648
|
||||
_MAX = 2147483647
|
||||
|
||||
|
||||
class Uint32ValueChecker(IntValueChecker):
|
||||
_MIN = 0
|
||||
_MAX = (1 << 32) - 1
|
||||
|
||||
|
||||
class Int64ValueChecker(IntValueChecker):
|
||||
_MIN = -(1 << 63)
|
||||
_MAX = (1 << 63) - 1
|
||||
|
||||
|
||||
class Uint64ValueChecker(IntValueChecker):
|
||||
_MIN = 0
|
||||
_MAX = (1 << 64) - 1
|
||||
|
||||
|
||||
# Type-checkers for all scalar CPPTYPEs.
|
||||
_VALUE_CHECKERS = {
|
||||
_FieldDescriptor.CPPTYPE_INT32: Int32ValueChecker(),
|
||||
_FieldDescriptor.CPPTYPE_INT64: Int64ValueChecker(),
|
||||
_FieldDescriptor.CPPTYPE_UINT32: Uint32ValueChecker(),
|
||||
_FieldDescriptor.CPPTYPE_UINT64: Uint64ValueChecker(),
|
||||
_FieldDescriptor.CPPTYPE_DOUBLE: TypeChecker(
|
||||
float, int, long),
|
||||
_FieldDescriptor.CPPTYPE_FLOAT: TypeChecker(
|
||||
float, int, long),
|
||||
_FieldDescriptor.CPPTYPE_BOOL: TypeChecker(bool, int),
|
||||
_FieldDescriptor.CPPTYPE_ENUM: Int32ValueChecker(),
|
||||
_FieldDescriptor.CPPTYPE_STRING: TypeChecker(str),
|
||||
}
|
||||
|
||||
|
||||
# Map from field type to a function F, such that F(field_num, value)
|
||||
# gives the total byte size for a value of the given type. This
|
||||
# byte size includes tag information and any other additional space
|
||||
# associated with serializing "value".
|
||||
TYPE_TO_BYTE_SIZE_FN = {
|
||||
_FieldDescriptor.TYPE_DOUBLE: wire_format.DoubleByteSize,
|
||||
_FieldDescriptor.TYPE_FLOAT: wire_format.FloatByteSize,
|
||||
_FieldDescriptor.TYPE_INT64: wire_format.Int64ByteSize,
|
||||
_FieldDescriptor.TYPE_UINT64: wire_format.UInt64ByteSize,
|
||||
_FieldDescriptor.TYPE_INT32: wire_format.Int32ByteSize,
|
||||
_FieldDescriptor.TYPE_FIXED64: wire_format.Fixed64ByteSize,
|
||||
_FieldDescriptor.TYPE_FIXED32: wire_format.Fixed32ByteSize,
|
||||
_FieldDescriptor.TYPE_BOOL: wire_format.BoolByteSize,
|
||||
_FieldDescriptor.TYPE_STRING: wire_format.StringByteSize,
|
||||
_FieldDescriptor.TYPE_GROUP: wire_format.GroupByteSize,
|
||||
_FieldDescriptor.TYPE_MESSAGE: wire_format.MessageByteSize,
|
||||
_FieldDescriptor.TYPE_BYTES: wire_format.BytesByteSize,
|
||||
_FieldDescriptor.TYPE_UINT32: wire_format.UInt32ByteSize,
|
||||
_FieldDescriptor.TYPE_ENUM: wire_format.EnumByteSize,
|
||||
_FieldDescriptor.TYPE_SFIXED32: wire_format.SFixed32ByteSize,
|
||||
_FieldDescriptor.TYPE_SFIXED64: wire_format.SFixed64ByteSize,
|
||||
_FieldDescriptor.TYPE_SINT32: wire_format.SInt32ByteSize,
|
||||
_FieldDescriptor.TYPE_SINT64: wire_format.SInt64ByteSize
|
||||
}
|
||||
|
||||
|
||||
# Maps from field types to encoder constructors.
|
||||
TYPE_TO_ENCODER = {
|
||||
_FieldDescriptor.TYPE_DOUBLE: encoder.DoubleEncoder,
|
||||
_FieldDescriptor.TYPE_FLOAT: encoder.FloatEncoder,
|
||||
_FieldDescriptor.TYPE_INT64: encoder.Int64Encoder,
|
||||
_FieldDescriptor.TYPE_UINT64: encoder.UInt64Encoder,
|
||||
_FieldDescriptor.TYPE_INT32: encoder.Int32Encoder,
|
||||
_FieldDescriptor.TYPE_FIXED64: encoder.Fixed64Encoder,
|
||||
_FieldDescriptor.TYPE_FIXED32: encoder.Fixed32Encoder,
|
||||
_FieldDescriptor.TYPE_BOOL: encoder.BoolEncoder,
|
||||
_FieldDescriptor.TYPE_STRING: encoder.StringEncoder,
|
||||
_FieldDescriptor.TYPE_GROUP: encoder.GroupEncoder,
|
||||
_FieldDescriptor.TYPE_MESSAGE: encoder.MessageEncoder,
|
||||
_FieldDescriptor.TYPE_BYTES: encoder.BytesEncoder,
|
||||
_FieldDescriptor.TYPE_UINT32: encoder.UInt32Encoder,
|
||||
_FieldDescriptor.TYPE_ENUM: encoder.EnumEncoder,
|
||||
_FieldDescriptor.TYPE_SFIXED32: encoder.SFixed32Encoder,
|
||||
_FieldDescriptor.TYPE_SFIXED64: encoder.SFixed64Encoder,
|
||||
_FieldDescriptor.TYPE_SINT32: encoder.SInt32Encoder,
|
||||
_FieldDescriptor.TYPE_SINT64: encoder.SInt64Encoder,
|
||||
}
|
||||
|
||||
|
||||
# Maps from field types to sizer constructors.
|
||||
TYPE_TO_SIZER = {
|
||||
_FieldDescriptor.TYPE_DOUBLE: encoder.DoubleSizer,
|
||||
_FieldDescriptor.TYPE_FLOAT: encoder.FloatSizer,
|
||||
_FieldDescriptor.TYPE_INT64: encoder.Int64Sizer,
|
||||
_FieldDescriptor.TYPE_UINT64: encoder.UInt64Sizer,
|
||||
_FieldDescriptor.TYPE_INT32: encoder.Int32Sizer,
|
||||
_FieldDescriptor.TYPE_FIXED64: encoder.Fixed64Sizer,
|
||||
_FieldDescriptor.TYPE_FIXED32: encoder.Fixed32Sizer,
|
||||
_FieldDescriptor.TYPE_BOOL: encoder.BoolSizer,
|
||||
_FieldDescriptor.TYPE_STRING: encoder.StringSizer,
|
||||
_FieldDescriptor.TYPE_GROUP: encoder.GroupSizer,
|
||||
_FieldDescriptor.TYPE_MESSAGE: encoder.MessageSizer,
|
||||
_FieldDescriptor.TYPE_BYTES: encoder.BytesSizer,
|
||||
_FieldDescriptor.TYPE_UINT32: encoder.UInt32Sizer,
|
||||
_FieldDescriptor.TYPE_ENUM: encoder.EnumSizer,
|
||||
_FieldDescriptor.TYPE_SFIXED32: encoder.SFixed32Sizer,
|
||||
_FieldDescriptor.TYPE_SFIXED64: encoder.SFixed64Sizer,
|
||||
_FieldDescriptor.TYPE_SINT32: encoder.SInt32Sizer,
|
||||
_FieldDescriptor.TYPE_SINT64: encoder.SInt64Sizer,
|
||||
}
|
||||
|
||||
|
||||
# Maps from field type to a decoder constructor.
|
||||
TYPE_TO_DECODER = {
|
||||
_FieldDescriptor.TYPE_DOUBLE: decoder.DoubleDecoder,
|
||||
_FieldDescriptor.TYPE_FLOAT: decoder.FloatDecoder,
|
||||
_FieldDescriptor.TYPE_INT64: decoder.Int64Decoder,
|
||||
_FieldDescriptor.TYPE_UINT64: decoder.UInt64Decoder,
|
||||
_FieldDescriptor.TYPE_INT32: decoder.Int32Decoder,
|
||||
_FieldDescriptor.TYPE_FIXED64: decoder.Fixed64Decoder,
|
||||
_FieldDescriptor.TYPE_FIXED32: decoder.Fixed32Decoder,
|
||||
_FieldDescriptor.TYPE_BOOL: decoder.BoolDecoder,
|
||||
_FieldDescriptor.TYPE_STRING: decoder.StringDecoder,
|
||||
_FieldDescriptor.TYPE_GROUP: decoder.GroupDecoder,
|
||||
_FieldDescriptor.TYPE_MESSAGE: decoder.MessageDecoder,
|
||||
_FieldDescriptor.TYPE_BYTES: decoder.BytesDecoder,
|
||||
_FieldDescriptor.TYPE_UINT32: decoder.UInt32Decoder,
|
||||
_FieldDescriptor.TYPE_ENUM: decoder.EnumDecoder,
|
||||
_FieldDescriptor.TYPE_SFIXED32: decoder.SFixed32Decoder,
|
||||
_FieldDescriptor.TYPE_SFIXED64: decoder.SFixed64Decoder,
|
||||
_FieldDescriptor.TYPE_SINT32: decoder.SInt32Decoder,
|
||||
_FieldDescriptor.TYPE_SINT64: decoder.SInt64Decoder,
|
||||
}
|
||||
|
||||
# Maps from field type to expected wiretype.
|
||||
FIELD_TYPE_TO_WIRE_TYPE = {
|
||||
_FieldDescriptor.TYPE_DOUBLE: wire_format.WIRETYPE_FIXED64,
|
||||
_FieldDescriptor.TYPE_FLOAT: wire_format.WIRETYPE_FIXED32,
|
||||
_FieldDescriptor.TYPE_INT64: wire_format.WIRETYPE_VARINT,
|
||||
_FieldDescriptor.TYPE_UINT64: wire_format.WIRETYPE_VARINT,
|
||||
_FieldDescriptor.TYPE_INT32: wire_format.WIRETYPE_VARINT,
|
||||
_FieldDescriptor.TYPE_FIXED64: wire_format.WIRETYPE_FIXED64,
|
||||
_FieldDescriptor.TYPE_FIXED32: wire_format.WIRETYPE_FIXED32,
|
||||
_FieldDescriptor.TYPE_BOOL: wire_format.WIRETYPE_VARINT,
|
||||
_FieldDescriptor.TYPE_STRING:
|
||||
wire_format.WIRETYPE_LENGTH_DELIMITED,
|
||||
_FieldDescriptor.TYPE_GROUP: wire_format.WIRETYPE_START_GROUP,
|
||||
_FieldDescriptor.TYPE_MESSAGE:
|
||||
wire_format.WIRETYPE_LENGTH_DELIMITED,
|
||||
_FieldDescriptor.TYPE_BYTES:
|
||||
wire_format.WIRETYPE_LENGTH_DELIMITED,
|
||||
_FieldDescriptor.TYPE_UINT32: wire_format.WIRETYPE_VARINT,
|
||||
_FieldDescriptor.TYPE_ENUM: wire_format.WIRETYPE_VARINT,
|
||||
_FieldDescriptor.TYPE_SFIXED32: wire_format.WIRETYPE_FIXED32,
|
||||
_FieldDescriptor.TYPE_SFIXED64: wire_format.WIRETYPE_FIXED64,
|
||||
_FieldDescriptor.TYPE_SINT32: wire_format.WIRETYPE_VARINT,
|
||||
_FieldDescriptor.TYPE_SINT64: wire_format.WIRETYPE_VARINT,
|
||||
}
|
||||
# Protocol Buffers - Google's data interchange format
|
||||
# Copyright 2008 Google Inc. All rights reserved.
|
||||
# http://code.google.com/p/protobuf/
|
||||
#
|
||||
# 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.
|
||||
|
||||
"""Provides type checking routines.
|
||||
|
||||
This module defines type checking utilities in the forms of dictionaries:
|
||||
|
||||
VALUE_CHECKERS: A dictionary of field types and a value validation object.
|
||||
TYPE_TO_BYTE_SIZE_FN: A dictionary with field types and a size computing
|
||||
function.
|
||||
TYPE_TO_SERIALIZE_METHOD: A dictionary with field types and serialization
|
||||
function.
|
||||
FIELD_TYPE_TO_WIRE_TYPE: A dictionary with field typed and their
|
||||
coresponding wire types.
|
||||
TYPE_TO_DESERIALIZE_METHOD: A dictionary with field types and deserialization
|
||||
function.
|
||||
"""
|
||||
|
||||
__author__ = 'robinson@google.com (Will Robinson)'
|
||||
|
||||
from google.protobuf.internal import decoder
|
||||
from google.protobuf.internal import encoder
|
||||
from google.protobuf.internal import wire_format
|
||||
from google.protobuf import descriptor
|
||||
|
||||
_FieldDescriptor = descriptor.FieldDescriptor
|
||||
|
||||
|
||||
def GetTypeChecker(cpp_type, field_type):
|
||||
"""Returns a type checker for a message field of the specified types.
|
||||
|
||||
Args:
|
||||
cpp_type: C++ type of the field (see descriptor.py).
|
||||
field_type: Protocol message field type (see descriptor.py).
|
||||
|
||||
Returns:
|
||||
An instance of TypeChecker which can be used to verify the types
|
||||
of values assigned to a field of the specified type.
|
||||
"""
|
||||
if (cpp_type == _FieldDescriptor.CPPTYPE_STRING and
|
||||
field_type == _FieldDescriptor.TYPE_STRING):
|
||||
return UnicodeValueChecker()
|
||||
return _VALUE_CHECKERS[cpp_type]
|
||||
|
||||
|
||||
# None of the typecheckers below make any attempt to guard against people
|
||||
# subclassing builtin types and doing weird things. We're not trying to
|
||||
# protect against malicious clients here, just people accidentally shooting
|
||||
# themselves in the foot in obvious ways.
|
||||
|
||||
class TypeChecker(object):
|
||||
|
||||
"""Type checker used to catch type errors as early as possible
|
||||
when the client is setting scalar fields in protocol messages.
|
||||
"""
|
||||
|
||||
def __init__(self, *acceptable_types):
|
||||
self._acceptable_types = acceptable_types
|
||||
|
||||
def CheckValue(self, proposed_value):
|
||||
if not isinstance(proposed_value, self._acceptable_types):
|
||||
message = ('%.1024r has type %s, but expected one of: %s' %
|
||||
(proposed_value, type(proposed_value), self._acceptable_types))
|
||||
raise TypeError(message)
|
||||
|
||||
|
||||
# IntValueChecker and its subclasses perform integer type-checks
|
||||
# and bounds-checks.
|
||||
class IntValueChecker(object):
|
||||
|
||||
"""Checker used for integer fields. Performs type-check and range check."""
|
||||
|
||||
def CheckValue(self, proposed_value):
|
||||
if not isinstance(proposed_value, (int, long)):
|
||||
message = ('%.1024r has type %s, but expected one of: %s' %
|
||||
(proposed_value, type(proposed_value), (int, long)))
|
||||
raise TypeError(message)
|
||||
if not self._MIN <= proposed_value <= self._MAX:
|
||||
raise ValueError('Value out of range: %d' % proposed_value)
|
||||
|
||||
|
||||
class UnicodeValueChecker(object):
|
||||
|
||||
"""Checker used for string fields."""
|
||||
|
||||
def CheckValue(self, proposed_value):
|
||||
if not isinstance(proposed_value, (str, unicode)):
|
||||
message = ('%.1024r has type %s, but expected one of: %s' %
|
||||
(proposed_value, type(proposed_value), (str, unicode)))
|
||||
raise TypeError(message)
|
||||
|
||||
# If the value is of type 'str' make sure that it is in 7-bit ASCII
|
||||
# encoding.
|
||||
if isinstance(proposed_value, str):
|
||||
try:
|
||||
unicode(proposed_value, 'ascii')
|
||||
except UnicodeDecodeError:
|
||||
raise ValueError('%.1024r has type str, but isn\'t in 7-bit ASCII '
|
||||
'encoding. Non-ASCII strings must be converted to '
|
||||
'unicode objects before being added.' %
|
||||
(proposed_value))
|
||||
|
||||
|
||||
class Int32ValueChecker(IntValueChecker):
|
||||
# We're sure to use ints instead of longs here since comparison may be more
|
||||
# efficient.
|
||||
_MIN = -2147483648
|
||||
_MAX = 2147483647
|
||||
|
||||
|
||||
class Uint32ValueChecker(IntValueChecker):
|
||||
_MIN = 0
|
||||
_MAX = (1 << 32) - 1
|
||||
|
||||
|
||||
class Int64ValueChecker(IntValueChecker):
|
||||
_MIN = -(1 << 63)
|
||||
_MAX = (1 << 63) - 1
|
||||
|
||||
|
||||
class Uint64ValueChecker(IntValueChecker):
|
||||
_MIN = 0
|
||||
_MAX = (1 << 64) - 1
|
||||
|
||||
|
||||
# Type-checkers for all scalar CPPTYPEs.
|
||||
_VALUE_CHECKERS = {
|
||||
_FieldDescriptor.CPPTYPE_INT32: Int32ValueChecker(),
|
||||
_FieldDescriptor.CPPTYPE_INT64: Int64ValueChecker(),
|
||||
_FieldDescriptor.CPPTYPE_UINT32: Uint32ValueChecker(),
|
||||
_FieldDescriptor.CPPTYPE_UINT64: Uint64ValueChecker(),
|
||||
_FieldDescriptor.CPPTYPE_DOUBLE: TypeChecker(
|
||||
float, int, long),
|
||||
_FieldDescriptor.CPPTYPE_FLOAT: TypeChecker(
|
||||
float, int, long),
|
||||
_FieldDescriptor.CPPTYPE_BOOL: TypeChecker(bool, int),
|
||||
_FieldDescriptor.CPPTYPE_ENUM: Int32ValueChecker(),
|
||||
_FieldDescriptor.CPPTYPE_STRING: TypeChecker(str),
|
||||
}
|
||||
|
||||
|
||||
# Map from field type to a function F, such that F(field_num, value)
|
||||
# gives the total byte size for a value of the given type. This
|
||||
# byte size includes tag information and any other additional space
|
||||
# associated with serializing "value".
|
||||
TYPE_TO_BYTE_SIZE_FN = {
|
||||
_FieldDescriptor.TYPE_DOUBLE: wire_format.DoubleByteSize,
|
||||
_FieldDescriptor.TYPE_FLOAT: wire_format.FloatByteSize,
|
||||
_FieldDescriptor.TYPE_INT64: wire_format.Int64ByteSize,
|
||||
_FieldDescriptor.TYPE_UINT64: wire_format.UInt64ByteSize,
|
||||
_FieldDescriptor.TYPE_INT32: wire_format.Int32ByteSize,
|
||||
_FieldDescriptor.TYPE_FIXED64: wire_format.Fixed64ByteSize,
|
||||
_FieldDescriptor.TYPE_FIXED32: wire_format.Fixed32ByteSize,
|
||||
_FieldDescriptor.TYPE_BOOL: wire_format.BoolByteSize,
|
||||
_FieldDescriptor.TYPE_STRING: wire_format.StringByteSize,
|
||||
_FieldDescriptor.TYPE_GROUP: wire_format.GroupByteSize,
|
||||
_FieldDescriptor.TYPE_MESSAGE: wire_format.MessageByteSize,
|
||||
_FieldDescriptor.TYPE_BYTES: wire_format.BytesByteSize,
|
||||
_FieldDescriptor.TYPE_UINT32: wire_format.UInt32ByteSize,
|
||||
_FieldDescriptor.TYPE_ENUM: wire_format.EnumByteSize,
|
||||
_FieldDescriptor.TYPE_SFIXED32: wire_format.SFixed32ByteSize,
|
||||
_FieldDescriptor.TYPE_SFIXED64: wire_format.SFixed64ByteSize,
|
||||
_FieldDescriptor.TYPE_SINT32: wire_format.SInt32ByteSize,
|
||||
_FieldDescriptor.TYPE_SINT64: wire_format.SInt64ByteSize
|
||||
}
|
||||
|
||||
|
||||
# Maps from field types to encoder constructors.
|
||||
TYPE_TO_ENCODER = {
|
||||
_FieldDescriptor.TYPE_DOUBLE: encoder.DoubleEncoder,
|
||||
_FieldDescriptor.TYPE_FLOAT: encoder.FloatEncoder,
|
||||
_FieldDescriptor.TYPE_INT64: encoder.Int64Encoder,
|
||||
_FieldDescriptor.TYPE_UINT64: encoder.UInt64Encoder,
|
||||
_FieldDescriptor.TYPE_INT32: encoder.Int32Encoder,
|
||||
_FieldDescriptor.TYPE_FIXED64: encoder.Fixed64Encoder,
|
||||
_FieldDescriptor.TYPE_FIXED32: encoder.Fixed32Encoder,
|
||||
_FieldDescriptor.TYPE_BOOL: encoder.BoolEncoder,
|
||||
_FieldDescriptor.TYPE_STRING: encoder.StringEncoder,
|
||||
_FieldDescriptor.TYPE_GROUP: encoder.GroupEncoder,
|
||||
_FieldDescriptor.TYPE_MESSAGE: encoder.MessageEncoder,
|
||||
_FieldDescriptor.TYPE_BYTES: encoder.BytesEncoder,
|
||||
_FieldDescriptor.TYPE_UINT32: encoder.UInt32Encoder,
|
||||
_FieldDescriptor.TYPE_ENUM: encoder.EnumEncoder,
|
||||
_FieldDescriptor.TYPE_SFIXED32: encoder.SFixed32Encoder,
|
||||
_FieldDescriptor.TYPE_SFIXED64: encoder.SFixed64Encoder,
|
||||
_FieldDescriptor.TYPE_SINT32: encoder.SInt32Encoder,
|
||||
_FieldDescriptor.TYPE_SINT64: encoder.SInt64Encoder,
|
||||
}
|
||||
|
||||
|
||||
# Maps from field types to sizer constructors.
|
||||
TYPE_TO_SIZER = {
|
||||
_FieldDescriptor.TYPE_DOUBLE: encoder.DoubleSizer,
|
||||
_FieldDescriptor.TYPE_FLOAT: encoder.FloatSizer,
|
||||
_FieldDescriptor.TYPE_INT64: encoder.Int64Sizer,
|
||||
_FieldDescriptor.TYPE_UINT64: encoder.UInt64Sizer,
|
||||
_FieldDescriptor.TYPE_INT32: encoder.Int32Sizer,
|
||||
_FieldDescriptor.TYPE_FIXED64: encoder.Fixed64Sizer,
|
||||
_FieldDescriptor.TYPE_FIXED32: encoder.Fixed32Sizer,
|
||||
_FieldDescriptor.TYPE_BOOL: encoder.BoolSizer,
|
||||
_FieldDescriptor.TYPE_STRING: encoder.StringSizer,
|
||||
_FieldDescriptor.TYPE_GROUP: encoder.GroupSizer,
|
||||
_FieldDescriptor.TYPE_MESSAGE: encoder.MessageSizer,
|
||||
_FieldDescriptor.TYPE_BYTES: encoder.BytesSizer,
|
||||
_FieldDescriptor.TYPE_UINT32: encoder.UInt32Sizer,
|
||||
_FieldDescriptor.TYPE_ENUM: encoder.EnumSizer,
|
||||
_FieldDescriptor.TYPE_SFIXED32: encoder.SFixed32Sizer,
|
||||
_FieldDescriptor.TYPE_SFIXED64: encoder.SFixed64Sizer,
|
||||
_FieldDescriptor.TYPE_SINT32: encoder.SInt32Sizer,
|
||||
_FieldDescriptor.TYPE_SINT64: encoder.SInt64Sizer,
|
||||
}
|
||||
|
||||
|
||||
# Maps from field type to a decoder constructor.
|
||||
TYPE_TO_DECODER = {
|
||||
_FieldDescriptor.TYPE_DOUBLE: decoder.DoubleDecoder,
|
||||
_FieldDescriptor.TYPE_FLOAT: decoder.FloatDecoder,
|
||||
_FieldDescriptor.TYPE_INT64: decoder.Int64Decoder,
|
||||
_FieldDescriptor.TYPE_UINT64: decoder.UInt64Decoder,
|
||||
_FieldDescriptor.TYPE_INT32: decoder.Int32Decoder,
|
||||
_FieldDescriptor.TYPE_FIXED64: decoder.Fixed64Decoder,
|
||||
_FieldDescriptor.TYPE_FIXED32: decoder.Fixed32Decoder,
|
||||
_FieldDescriptor.TYPE_BOOL: decoder.BoolDecoder,
|
||||
_FieldDescriptor.TYPE_STRING: decoder.StringDecoder,
|
||||
_FieldDescriptor.TYPE_GROUP: decoder.GroupDecoder,
|
||||
_FieldDescriptor.TYPE_MESSAGE: decoder.MessageDecoder,
|
||||
_FieldDescriptor.TYPE_BYTES: decoder.BytesDecoder,
|
||||
_FieldDescriptor.TYPE_UINT32: decoder.UInt32Decoder,
|
||||
_FieldDescriptor.TYPE_ENUM: decoder.EnumDecoder,
|
||||
_FieldDescriptor.TYPE_SFIXED32: decoder.SFixed32Decoder,
|
||||
_FieldDescriptor.TYPE_SFIXED64: decoder.SFixed64Decoder,
|
||||
_FieldDescriptor.TYPE_SINT32: decoder.SInt32Decoder,
|
||||
_FieldDescriptor.TYPE_SINT64: decoder.SInt64Decoder,
|
||||
}
|
||||
|
||||
# Maps from field type to expected wiretype.
|
||||
FIELD_TYPE_TO_WIRE_TYPE = {
|
||||
_FieldDescriptor.TYPE_DOUBLE: wire_format.WIRETYPE_FIXED64,
|
||||
_FieldDescriptor.TYPE_FLOAT: wire_format.WIRETYPE_FIXED32,
|
||||
_FieldDescriptor.TYPE_INT64: wire_format.WIRETYPE_VARINT,
|
||||
_FieldDescriptor.TYPE_UINT64: wire_format.WIRETYPE_VARINT,
|
||||
_FieldDescriptor.TYPE_INT32: wire_format.WIRETYPE_VARINT,
|
||||
_FieldDescriptor.TYPE_FIXED64: wire_format.WIRETYPE_FIXED64,
|
||||
_FieldDescriptor.TYPE_FIXED32: wire_format.WIRETYPE_FIXED32,
|
||||
_FieldDescriptor.TYPE_BOOL: wire_format.WIRETYPE_VARINT,
|
||||
_FieldDescriptor.TYPE_STRING:
|
||||
wire_format.WIRETYPE_LENGTH_DELIMITED,
|
||||
_FieldDescriptor.TYPE_GROUP: wire_format.WIRETYPE_START_GROUP,
|
||||
_FieldDescriptor.TYPE_MESSAGE:
|
||||
wire_format.WIRETYPE_LENGTH_DELIMITED,
|
||||
_FieldDescriptor.TYPE_BYTES:
|
||||
wire_format.WIRETYPE_LENGTH_DELIMITED,
|
||||
_FieldDescriptor.TYPE_UINT32: wire_format.WIRETYPE_VARINT,
|
||||
_FieldDescriptor.TYPE_ENUM: wire_format.WIRETYPE_VARINT,
|
||||
_FieldDescriptor.TYPE_SFIXED32: wire_format.WIRETYPE_FIXED32,
|
||||
_FieldDescriptor.TYPE_SFIXED64: wire_format.WIRETYPE_FIXED64,
|
||||
_FieldDescriptor.TYPE_SINT32: wire_format.WIRETYPE_VARINT,
|
||||
_FieldDescriptor.TYPE_SINT64: wire_format.WIRETYPE_VARINT,
|
||||
}
|
||||
|
||||
+268
-268
@@ -1,268 +1,268 @@
|
||||
# Protocol Buffers - Google's data interchange format
|
||||
# Copyright 2008 Google Inc. All rights reserved.
|
||||
# http://code.google.com/p/protobuf/
|
||||
#
|
||||
# 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.
|
||||
|
||||
"""Constants and static functions to support protocol buffer wire format."""
|
||||
|
||||
__author__ = 'robinson@google.com (Will Robinson)'
|
||||
|
||||
import struct
|
||||
from google.protobuf import descriptor
|
||||
from google.protobuf import message
|
||||
|
||||
|
||||
TAG_TYPE_BITS = 3 # Number of bits used to hold type info in a proto tag.
|
||||
TAG_TYPE_MASK = (1 << TAG_TYPE_BITS) - 1 # 0x7
|
||||
|
||||
# These numbers identify the wire type of a protocol buffer value.
|
||||
# We use the least-significant TAG_TYPE_BITS bits of the varint-encoded
|
||||
# tag-and-type to store one of these WIRETYPE_* constants.
|
||||
# These values must match WireType enum in google/protobuf/wire_format.h.
|
||||
WIRETYPE_VARINT = 0
|
||||
WIRETYPE_FIXED64 = 1
|
||||
WIRETYPE_LENGTH_DELIMITED = 2
|
||||
WIRETYPE_START_GROUP = 3
|
||||
WIRETYPE_END_GROUP = 4
|
||||
WIRETYPE_FIXED32 = 5
|
||||
_WIRETYPE_MAX = 5
|
||||
|
||||
|
||||
# Bounds for various integer types.
|
||||
INT32_MAX = int((1 << 31) - 1)
|
||||
INT32_MIN = int(-(1 << 31))
|
||||
UINT32_MAX = (1 << 32) - 1
|
||||
|
||||
INT64_MAX = (1 << 63) - 1
|
||||
INT64_MIN = -(1 << 63)
|
||||
UINT64_MAX = (1 << 64) - 1
|
||||
|
||||
# "struct" format strings that will encode/decode the specified formats.
|
||||
FORMAT_UINT32_LITTLE_ENDIAN = '<I'
|
||||
FORMAT_UINT64_LITTLE_ENDIAN = '<Q'
|
||||
FORMAT_FLOAT_LITTLE_ENDIAN = '<f'
|
||||
FORMAT_DOUBLE_LITTLE_ENDIAN = '<d'
|
||||
|
||||
|
||||
# We'll have to provide alternate implementations of AppendLittleEndian*() on
|
||||
# any architectures where these checks fail.
|
||||
if struct.calcsize(FORMAT_UINT32_LITTLE_ENDIAN) != 4:
|
||||
raise AssertionError('Format "I" is not a 32-bit number.')
|
||||
if struct.calcsize(FORMAT_UINT64_LITTLE_ENDIAN) != 8:
|
||||
raise AssertionError('Format "Q" is not a 64-bit number.')
|
||||
|
||||
|
||||
def PackTag(field_number, wire_type):
|
||||
"""Returns an unsigned 32-bit integer that encodes the field number and
|
||||
wire type information in standard protocol message wire format.
|
||||
|
||||
Args:
|
||||
field_number: Expected to be an integer in the range [1, 1 << 29)
|
||||
wire_type: One of the WIRETYPE_* constants.
|
||||
"""
|
||||
if not 0 <= wire_type <= _WIRETYPE_MAX:
|
||||
raise message.EncodeError('Unknown wire type: %d' % wire_type)
|
||||
return (field_number << TAG_TYPE_BITS) | wire_type
|
||||
|
||||
|
||||
def UnpackTag(tag):
|
||||
"""The inverse of PackTag(). Given an unsigned 32-bit number,
|
||||
returns a (field_number, wire_type) tuple.
|
||||
"""
|
||||
return (tag >> TAG_TYPE_BITS), (tag & TAG_TYPE_MASK)
|
||||
|
||||
|
||||
def ZigZagEncode(value):
|
||||
"""ZigZag Transform: Encodes signed integers so that they can be
|
||||
effectively used with varint encoding. See wire_format.h for
|
||||
more details.
|
||||
"""
|
||||
if value >= 0:
|
||||
return value << 1
|
||||
return (value << 1) ^ (~0)
|
||||
|
||||
|
||||
def ZigZagDecode(value):
|
||||
"""Inverse of ZigZagEncode()."""
|
||||
if not value & 0x1:
|
||||
return value >> 1
|
||||
return (value >> 1) ^ (~0)
|
||||
|
||||
|
||||
|
||||
# The *ByteSize() functions below return the number of bytes required to
|
||||
# serialize "field number + type" information and then serialize the value.
|
||||
|
||||
|
||||
def Int32ByteSize(field_number, int32):
|
||||
return Int64ByteSize(field_number, int32)
|
||||
|
||||
|
||||
def Int32ByteSizeNoTag(int32):
|
||||
return _VarUInt64ByteSizeNoTag(0xffffffffffffffff & int32)
|
||||
|
||||
|
||||
def Int64ByteSize(field_number, int64):
|
||||
# Have to convert to uint before calling UInt64ByteSize().
|
||||
return UInt64ByteSize(field_number, 0xffffffffffffffff & int64)
|
||||
|
||||
|
||||
def UInt32ByteSize(field_number, uint32):
|
||||
return UInt64ByteSize(field_number, uint32)
|
||||
|
||||
|
||||
def UInt64ByteSize(field_number, uint64):
|
||||
return TagByteSize(field_number) + _VarUInt64ByteSizeNoTag(uint64)
|
||||
|
||||
|
||||
def SInt32ByteSize(field_number, int32):
|
||||
return UInt32ByteSize(field_number, ZigZagEncode(int32))
|
||||
|
||||
|
||||
def SInt64ByteSize(field_number, int64):
|
||||
return UInt64ByteSize(field_number, ZigZagEncode(int64))
|
||||
|
||||
|
||||
def Fixed32ByteSize(field_number, fixed32):
|
||||
return TagByteSize(field_number) + 4
|
||||
|
||||
|
||||
def Fixed64ByteSize(field_number, fixed64):
|
||||
return TagByteSize(field_number) + 8
|
||||
|
||||
|
||||
def SFixed32ByteSize(field_number, sfixed32):
|
||||
return TagByteSize(field_number) + 4
|
||||
|
||||
|
||||
def SFixed64ByteSize(field_number, sfixed64):
|
||||
return TagByteSize(field_number) + 8
|
||||
|
||||
|
||||
def FloatByteSize(field_number, flt):
|
||||
return TagByteSize(field_number) + 4
|
||||
|
||||
|
||||
def DoubleByteSize(field_number, double):
|
||||
return TagByteSize(field_number) + 8
|
||||
|
||||
|
||||
def BoolByteSize(field_number, b):
|
||||
return TagByteSize(field_number) + 1
|
||||
|
||||
|
||||
def EnumByteSize(field_number, enum):
|
||||
return UInt32ByteSize(field_number, enum)
|
||||
|
||||
|
||||
def StringByteSize(field_number, string):
|
||||
return BytesByteSize(field_number, string.encode('utf-8'))
|
||||
|
||||
|
||||
def BytesByteSize(field_number, b):
|
||||
return (TagByteSize(field_number)
|
||||
+ _VarUInt64ByteSizeNoTag(len(b))
|
||||
+ len(b))
|
||||
|
||||
|
||||
def GroupByteSize(field_number, message):
|
||||
return (2 * TagByteSize(field_number) # START and END group.
|
||||
+ message.ByteSize())
|
||||
|
||||
|
||||
def MessageByteSize(field_number, message):
|
||||
return (TagByteSize(field_number)
|
||||
+ _VarUInt64ByteSizeNoTag(message.ByteSize())
|
||||
+ message.ByteSize())
|
||||
|
||||
|
||||
def MessageSetItemByteSize(field_number, msg):
|
||||
# First compute the sizes of the tags.
|
||||
# There are 2 tags for the beginning and ending of the repeated group, that
|
||||
# is field number 1, one with field number 2 (type_id) and one with field
|
||||
# number 3 (message).
|
||||
total_size = (2 * TagByteSize(1) + TagByteSize(2) + TagByteSize(3))
|
||||
|
||||
# Add the number of bytes for type_id.
|
||||
total_size += _VarUInt64ByteSizeNoTag(field_number)
|
||||
|
||||
message_size = msg.ByteSize()
|
||||
|
||||
# The number of bytes for encoding the length of the message.
|
||||
total_size += _VarUInt64ByteSizeNoTag(message_size)
|
||||
|
||||
# The size of the message.
|
||||
total_size += message_size
|
||||
return total_size
|
||||
|
||||
|
||||
def TagByteSize(field_number):
|
||||
"""Returns the bytes required to serialize a tag with this field number."""
|
||||
# Just pass in type 0, since the type won't affect the tag+type size.
|
||||
return _VarUInt64ByteSizeNoTag(PackTag(field_number, 0))
|
||||
|
||||
|
||||
# Private helper function for the *ByteSize() functions above.
|
||||
|
||||
def _VarUInt64ByteSizeNoTag(uint64):
|
||||
"""Returns the number of bytes required to serialize a single varint
|
||||
using boundary value comparisons. (unrolled loop optimization -WPierce)
|
||||
uint64 must be unsigned.
|
||||
"""
|
||||
if uint64 <= 0x7f: return 1
|
||||
if uint64 <= 0x3fff: return 2
|
||||
if uint64 <= 0x1fffff: return 3
|
||||
if uint64 <= 0xfffffff: return 4
|
||||
if uint64 <= 0x7ffffffff: return 5
|
||||
if uint64 <= 0x3ffffffffff: return 6
|
||||
if uint64 <= 0x1ffffffffffff: return 7
|
||||
if uint64 <= 0xffffffffffffff: return 8
|
||||
if uint64 <= 0x7fffffffffffffff: return 9
|
||||
if uint64 > UINT64_MAX:
|
||||
raise message.EncodeError('Value out of range: %d' % uint64)
|
||||
return 10
|
||||
|
||||
|
||||
NON_PACKABLE_TYPES = (
|
||||
descriptor.FieldDescriptor.TYPE_STRING,
|
||||
descriptor.FieldDescriptor.TYPE_GROUP,
|
||||
descriptor.FieldDescriptor.TYPE_MESSAGE,
|
||||
descriptor.FieldDescriptor.TYPE_BYTES
|
||||
)
|
||||
|
||||
|
||||
def IsTypePackable(field_type):
|
||||
"""Return true iff packable = true is valid for fields of this type.
|
||||
|
||||
Args:
|
||||
field_type: a FieldDescriptor::Type value.
|
||||
|
||||
Returns:
|
||||
True iff fields of this type are packable.
|
||||
"""
|
||||
return field_type not in NON_PACKABLE_TYPES
|
||||
# Protocol Buffers - Google's data interchange format
|
||||
# Copyright 2008 Google Inc. All rights reserved.
|
||||
# http://code.google.com/p/protobuf/
|
||||
#
|
||||
# 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.
|
||||
|
||||
"""Constants and static functions to support protocol buffer wire format."""
|
||||
|
||||
__author__ = 'robinson@google.com (Will Robinson)'
|
||||
|
||||
import struct
|
||||
from google.protobuf import descriptor
|
||||
from google.protobuf import message
|
||||
|
||||
|
||||
TAG_TYPE_BITS = 3 # Number of bits used to hold type info in a proto tag.
|
||||
TAG_TYPE_MASK = (1 << TAG_TYPE_BITS) - 1 # 0x7
|
||||
|
||||
# These numbers identify the wire type of a protocol buffer value.
|
||||
# We use the least-significant TAG_TYPE_BITS bits of the varint-encoded
|
||||
# tag-and-type to store one of these WIRETYPE_* constants.
|
||||
# These values must match WireType enum in google/protobuf/wire_format.h.
|
||||
WIRETYPE_VARINT = 0
|
||||
WIRETYPE_FIXED64 = 1
|
||||
WIRETYPE_LENGTH_DELIMITED = 2
|
||||
WIRETYPE_START_GROUP = 3
|
||||
WIRETYPE_END_GROUP = 4
|
||||
WIRETYPE_FIXED32 = 5
|
||||
_WIRETYPE_MAX = 5
|
||||
|
||||
|
||||
# Bounds for various integer types.
|
||||
INT32_MAX = int((1 << 31) - 1)
|
||||
INT32_MIN = int(-(1 << 31))
|
||||
UINT32_MAX = (1 << 32) - 1
|
||||
|
||||
INT64_MAX = (1 << 63) - 1
|
||||
INT64_MIN = -(1 << 63)
|
||||
UINT64_MAX = (1 << 64) - 1
|
||||
|
||||
# "struct" format strings that will encode/decode the specified formats.
|
||||
FORMAT_UINT32_LITTLE_ENDIAN = '<I'
|
||||
FORMAT_UINT64_LITTLE_ENDIAN = '<Q'
|
||||
FORMAT_FLOAT_LITTLE_ENDIAN = '<f'
|
||||
FORMAT_DOUBLE_LITTLE_ENDIAN = '<d'
|
||||
|
||||
|
||||
# We'll have to provide alternate implementations of AppendLittleEndian*() on
|
||||
# any architectures where these checks fail.
|
||||
if struct.calcsize(FORMAT_UINT32_LITTLE_ENDIAN) != 4:
|
||||
raise AssertionError('Format "I" is not a 32-bit number.')
|
||||
if struct.calcsize(FORMAT_UINT64_LITTLE_ENDIAN) != 8:
|
||||
raise AssertionError('Format "Q" is not a 64-bit number.')
|
||||
|
||||
|
||||
def PackTag(field_number, wire_type):
|
||||
"""Returns an unsigned 32-bit integer that encodes the field number and
|
||||
wire type information in standard protocol message wire format.
|
||||
|
||||
Args:
|
||||
field_number: Expected to be an integer in the range [1, 1 << 29)
|
||||
wire_type: One of the WIRETYPE_* constants.
|
||||
"""
|
||||
if not 0 <= wire_type <= _WIRETYPE_MAX:
|
||||
raise message.EncodeError('Unknown wire type: %d' % wire_type)
|
||||
return (field_number << TAG_TYPE_BITS) | wire_type
|
||||
|
||||
|
||||
def UnpackTag(tag):
|
||||
"""The inverse of PackTag(). Given an unsigned 32-bit number,
|
||||
returns a (field_number, wire_type) tuple.
|
||||
"""
|
||||
return (tag >> TAG_TYPE_BITS), (tag & TAG_TYPE_MASK)
|
||||
|
||||
|
||||
def ZigZagEncode(value):
|
||||
"""ZigZag Transform: Encodes signed integers so that they can be
|
||||
effectively used with varint encoding. See wire_format.h for
|
||||
more details.
|
||||
"""
|
||||
if value >= 0:
|
||||
return value << 1
|
||||
return (value << 1) ^ (~0)
|
||||
|
||||
|
||||
def ZigZagDecode(value):
|
||||
"""Inverse of ZigZagEncode()."""
|
||||
if not value & 0x1:
|
||||
return value >> 1
|
||||
return (value >> 1) ^ (~0)
|
||||
|
||||
|
||||
|
||||
# The *ByteSize() functions below return the number of bytes required to
|
||||
# serialize "field number + type" information and then serialize the value.
|
||||
|
||||
|
||||
def Int32ByteSize(field_number, int32):
|
||||
return Int64ByteSize(field_number, int32)
|
||||
|
||||
|
||||
def Int32ByteSizeNoTag(int32):
|
||||
return _VarUInt64ByteSizeNoTag(0xffffffffffffffff & int32)
|
||||
|
||||
|
||||
def Int64ByteSize(field_number, int64):
|
||||
# Have to convert to uint before calling UInt64ByteSize().
|
||||
return UInt64ByteSize(field_number, 0xffffffffffffffff & int64)
|
||||
|
||||
|
||||
def UInt32ByteSize(field_number, uint32):
|
||||
return UInt64ByteSize(field_number, uint32)
|
||||
|
||||
|
||||
def UInt64ByteSize(field_number, uint64):
|
||||
return TagByteSize(field_number) + _VarUInt64ByteSizeNoTag(uint64)
|
||||
|
||||
|
||||
def SInt32ByteSize(field_number, int32):
|
||||
return UInt32ByteSize(field_number, ZigZagEncode(int32))
|
||||
|
||||
|
||||
def SInt64ByteSize(field_number, int64):
|
||||
return UInt64ByteSize(field_number, ZigZagEncode(int64))
|
||||
|
||||
|
||||
def Fixed32ByteSize(field_number, fixed32):
|
||||
return TagByteSize(field_number) + 4
|
||||
|
||||
|
||||
def Fixed64ByteSize(field_number, fixed64):
|
||||
return TagByteSize(field_number) + 8
|
||||
|
||||
|
||||
def SFixed32ByteSize(field_number, sfixed32):
|
||||
return TagByteSize(field_number) + 4
|
||||
|
||||
|
||||
def SFixed64ByteSize(field_number, sfixed64):
|
||||
return TagByteSize(field_number) + 8
|
||||
|
||||
|
||||
def FloatByteSize(field_number, flt):
|
||||
return TagByteSize(field_number) + 4
|
||||
|
||||
|
||||
def DoubleByteSize(field_number, double):
|
||||
return TagByteSize(field_number) + 8
|
||||
|
||||
|
||||
def BoolByteSize(field_number, b):
|
||||
return TagByteSize(field_number) + 1
|
||||
|
||||
|
||||
def EnumByteSize(field_number, enum):
|
||||
return UInt32ByteSize(field_number, enum)
|
||||
|
||||
|
||||
def StringByteSize(field_number, string):
|
||||
return BytesByteSize(field_number, string.encode('utf-8'))
|
||||
|
||||
|
||||
def BytesByteSize(field_number, b):
|
||||
return (TagByteSize(field_number)
|
||||
+ _VarUInt64ByteSizeNoTag(len(b))
|
||||
+ len(b))
|
||||
|
||||
|
||||
def GroupByteSize(field_number, message):
|
||||
return (2 * TagByteSize(field_number) # START and END group.
|
||||
+ message.ByteSize())
|
||||
|
||||
|
||||
def MessageByteSize(field_number, message):
|
||||
return (TagByteSize(field_number)
|
||||
+ _VarUInt64ByteSizeNoTag(message.ByteSize())
|
||||
+ message.ByteSize())
|
||||
|
||||
|
||||
def MessageSetItemByteSize(field_number, msg):
|
||||
# First compute the sizes of the tags.
|
||||
# There are 2 tags for the beginning and ending of the repeated group, that
|
||||
# is field number 1, one with field number 2 (type_id) and one with field
|
||||
# number 3 (message).
|
||||
total_size = (2 * TagByteSize(1) + TagByteSize(2) + TagByteSize(3))
|
||||
|
||||
# Add the number of bytes for type_id.
|
||||
total_size += _VarUInt64ByteSizeNoTag(field_number)
|
||||
|
||||
message_size = msg.ByteSize()
|
||||
|
||||
# The number of bytes for encoding the length of the message.
|
||||
total_size += _VarUInt64ByteSizeNoTag(message_size)
|
||||
|
||||
# The size of the message.
|
||||
total_size += message_size
|
||||
return total_size
|
||||
|
||||
|
||||
def TagByteSize(field_number):
|
||||
"""Returns the bytes required to serialize a tag with this field number."""
|
||||
# Just pass in type 0, since the type won't affect the tag+type size.
|
||||
return _VarUInt64ByteSizeNoTag(PackTag(field_number, 0))
|
||||
|
||||
|
||||
# Private helper function for the *ByteSize() functions above.
|
||||
|
||||
def _VarUInt64ByteSizeNoTag(uint64):
|
||||
"""Returns the number of bytes required to serialize a single varint
|
||||
using boundary value comparisons. (unrolled loop optimization -WPierce)
|
||||
uint64 must be unsigned.
|
||||
"""
|
||||
if uint64 <= 0x7f: return 1
|
||||
if uint64 <= 0x3fff: return 2
|
||||
if uint64 <= 0x1fffff: return 3
|
||||
if uint64 <= 0xfffffff: return 4
|
||||
if uint64 <= 0x7ffffffff: return 5
|
||||
if uint64 <= 0x3ffffffffff: return 6
|
||||
if uint64 <= 0x1ffffffffffff: return 7
|
||||
if uint64 <= 0xffffffffffffff: return 8
|
||||
if uint64 <= 0x7fffffffffffffff: return 9
|
||||
if uint64 > UINT64_MAX:
|
||||
raise message.EncodeError('Value out of range: %d' % uint64)
|
||||
return 10
|
||||
|
||||
|
||||
NON_PACKABLE_TYPES = (
|
||||
descriptor.FieldDescriptor.TYPE_STRING,
|
||||
descriptor.FieldDescriptor.TYPE_GROUP,
|
||||
descriptor.FieldDescriptor.TYPE_MESSAGE,
|
||||
descriptor.FieldDescriptor.TYPE_BYTES
|
||||
)
|
||||
|
||||
|
||||
def IsTypePackable(field_type):
|
||||
"""Return true iff packable = true is valid for fields of this type.
|
||||
|
||||
Args:
|
||||
field_type: a FieldDescriptor::Type value.
|
||||
|
||||
Returns:
|
||||
True iff fields of this type are packable.
|
||||
"""
|
||||
return field_type not in NON_PACKABLE_TYPES
|
||||
|
||||
+253
-253
@@ -1,253 +1,253 @@
|
||||
#! /usr/bin/python
|
||||
#
|
||||
# Protocol Buffers - Google's data interchange format
|
||||
# Copyright 2008 Google Inc. All rights reserved.
|
||||
# http://code.google.com/p/protobuf/
|
||||
#
|
||||
# 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.
|
||||
|
||||
"""Test for google.protobuf.internal.wire_format."""
|
||||
|
||||
__author__ = 'robinson@google.com (Will Robinson)'
|
||||
|
||||
import unittest
|
||||
from google.protobuf import message
|
||||
from google.protobuf.internal import wire_format
|
||||
|
||||
|
||||
class WireFormatTest(unittest.TestCase):
|
||||
|
||||
def testPackTag(self):
|
||||
field_number = 0xabc
|
||||
tag_type = 2
|
||||
self.assertEqual((field_number << 3) | tag_type,
|
||||
wire_format.PackTag(field_number, tag_type))
|
||||
PackTag = wire_format.PackTag
|
||||
# Number too high.
|
||||
self.assertRaises(message.EncodeError, PackTag, field_number, 6)
|
||||
# Number too low.
|
||||
self.assertRaises(message.EncodeError, PackTag, field_number, -1)
|
||||
|
||||
def testUnpackTag(self):
|
||||
# Test field numbers that will require various varint sizes.
|
||||
for expected_field_number in (1, 15, 16, 2047, 2048):
|
||||
for expected_wire_type in range(6): # Highest-numbered wiretype is 5.
|
||||
field_number, wire_type = wire_format.UnpackTag(
|
||||
wire_format.PackTag(expected_field_number, expected_wire_type))
|
||||
self.assertEqual(expected_field_number, field_number)
|
||||
self.assertEqual(expected_wire_type, wire_type)
|
||||
|
||||
self.assertRaises(TypeError, wire_format.UnpackTag, None)
|
||||
self.assertRaises(TypeError, wire_format.UnpackTag, 'abc')
|
||||
self.assertRaises(TypeError, wire_format.UnpackTag, 0.0)
|
||||
self.assertRaises(TypeError, wire_format.UnpackTag, object())
|
||||
|
||||
def testZigZagEncode(self):
|
||||
Z = wire_format.ZigZagEncode
|
||||
self.assertEqual(0, Z(0))
|
||||
self.assertEqual(1, Z(-1))
|
||||
self.assertEqual(2, Z(1))
|
||||
self.assertEqual(3, Z(-2))
|
||||
self.assertEqual(4, Z(2))
|
||||
self.assertEqual(0xfffffffe, Z(0x7fffffff))
|
||||
self.assertEqual(0xffffffff, Z(-0x80000000))
|
||||
self.assertEqual(0xfffffffffffffffe, Z(0x7fffffffffffffff))
|
||||
self.assertEqual(0xffffffffffffffff, Z(-0x8000000000000000))
|
||||
|
||||
self.assertRaises(TypeError, Z, None)
|
||||
self.assertRaises(TypeError, Z, 'abcd')
|
||||
self.assertRaises(TypeError, Z, 0.0)
|
||||
self.assertRaises(TypeError, Z, object())
|
||||
|
||||
def testZigZagDecode(self):
|
||||
Z = wire_format.ZigZagDecode
|
||||
self.assertEqual(0, Z(0))
|
||||
self.assertEqual(-1, Z(1))
|
||||
self.assertEqual(1, Z(2))
|
||||
self.assertEqual(-2, Z(3))
|
||||
self.assertEqual(2, Z(4))
|
||||
self.assertEqual(0x7fffffff, Z(0xfffffffe))
|
||||
self.assertEqual(-0x80000000, Z(0xffffffff))
|
||||
self.assertEqual(0x7fffffffffffffff, Z(0xfffffffffffffffe))
|
||||
self.assertEqual(-0x8000000000000000, Z(0xffffffffffffffff))
|
||||
|
||||
self.assertRaises(TypeError, Z, None)
|
||||
self.assertRaises(TypeError, Z, 'abcd')
|
||||
self.assertRaises(TypeError, Z, 0.0)
|
||||
self.assertRaises(TypeError, Z, object())
|
||||
|
||||
def NumericByteSizeTestHelper(self, byte_size_fn, value, expected_value_size):
|
||||
# Use field numbers that cause various byte sizes for the tag information.
|
||||
for field_number, tag_bytes in ((15, 1), (16, 2), (2047, 2), (2048, 3)):
|
||||
expected_size = expected_value_size + tag_bytes
|
||||
actual_size = byte_size_fn(field_number, value)
|
||||
self.assertEqual(expected_size, actual_size,
|
||||
'byte_size_fn: %s, field_number: %d, value: %r\n'
|
||||
'Expected: %d, Actual: %d'% (
|
||||
byte_size_fn, field_number, value, expected_size, actual_size))
|
||||
|
||||
def testByteSizeFunctions(self):
|
||||
# Test all numeric *ByteSize() functions.
|
||||
NUMERIC_ARGS = [
|
||||
# Int32ByteSize().
|
||||
[wire_format.Int32ByteSize, 0, 1],
|
||||
[wire_format.Int32ByteSize, 127, 1],
|
||||
[wire_format.Int32ByteSize, 128, 2],
|
||||
[wire_format.Int32ByteSize, -1, 10],
|
||||
# Int64ByteSize().
|
||||
[wire_format.Int64ByteSize, 0, 1],
|
||||
[wire_format.Int64ByteSize, 127, 1],
|
||||
[wire_format.Int64ByteSize, 128, 2],
|
||||
[wire_format.Int64ByteSize, -1, 10],
|
||||
# UInt32ByteSize().
|
||||
[wire_format.UInt32ByteSize, 0, 1],
|
||||
[wire_format.UInt32ByteSize, 127, 1],
|
||||
[wire_format.UInt32ByteSize, 128, 2],
|
||||
[wire_format.UInt32ByteSize, wire_format.UINT32_MAX, 5],
|
||||
# UInt64ByteSize().
|
||||
[wire_format.UInt64ByteSize, 0, 1],
|
||||
[wire_format.UInt64ByteSize, 127, 1],
|
||||
[wire_format.UInt64ByteSize, 128, 2],
|
||||
[wire_format.UInt64ByteSize, wire_format.UINT64_MAX, 10],
|
||||
# SInt32ByteSize().
|
||||
[wire_format.SInt32ByteSize, 0, 1],
|
||||
[wire_format.SInt32ByteSize, -1, 1],
|
||||
[wire_format.SInt32ByteSize, 1, 1],
|
||||
[wire_format.SInt32ByteSize, -63, 1],
|
||||
[wire_format.SInt32ByteSize, 63, 1],
|
||||
[wire_format.SInt32ByteSize, -64, 1],
|
||||
[wire_format.SInt32ByteSize, 64, 2],
|
||||
# SInt64ByteSize().
|
||||
[wire_format.SInt64ByteSize, 0, 1],
|
||||
[wire_format.SInt64ByteSize, -1, 1],
|
||||
[wire_format.SInt64ByteSize, 1, 1],
|
||||
[wire_format.SInt64ByteSize, -63, 1],
|
||||
[wire_format.SInt64ByteSize, 63, 1],
|
||||
[wire_format.SInt64ByteSize, -64, 1],
|
||||
[wire_format.SInt64ByteSize, 64, 2],
|
||||
# Fixed32ByteSize().
|
||||
[wire_format.Fixed32ByteSize, 0, 4],
|
||||
[wire_format.Fixed32ByteSize, wire_format.UINT32_MAX, 4],
|
||||
# Fixed64ByteSize().
|
||||
[wire_format.Fixed64ByteSize, 0, 8],
|
||||
[wire_format.Fixed64ByteSize, wire_format.UINT64_MAX, 8],
|
||||
# SFixed32ByteSize().
|
||||
[wire_format.SFixed32ByteSize, 0, 4],
|
||||
[wire_format.SFixed32ByteSize, wire_format.INT32_MIN, 4],
|
||||
[wire_format.SFixed32ByteSize, wire_format.INT32_MAX, 4],
|
||||
# SFixed64ByteSize().
|
||||
[wire_format.SFixed64ByteSize, 0, 8],
|
||||
[wire_format.SFixed64ByteSize, wire_format.INT64_MIN, 8],
|
||||
[wire_format.SFixed64ByteSize, wire_format.INT64_MAX, 8],
|
||||
# FloatByteSize().
|
||||
[wire_format.FloatByteSize, 0.0, 4],
|
||||
[wire_format.FloatByteSize, 1000000000.0, 4],
|
||||
[wire_format.FloatByteSize, -1000000000.0, 4],
|
||||
# DoubleByteSize().
|
||||
[wire_format.DoubleByteSize, 0.0, 8],
|
||||
[wire_format.DoubleByteSize, 1000000000.0, 8],
|
||||
[wire_format.DoubleByteSize, -1000000000.0, 8],
|
||||
# BoolByteSize().
|
||||
[wire_format.BoolByteSize, False, 1],
|
||||
[wire_format.BoolByteSize, True, 1],
|
||||
# EnumByteSize().
|
||||
[wire_format.EnumByteSize, 0, 1],
|
||||
[wire_format.EnumByteSize, 127, 1],
|
||||
[wire_format.EnumByteSize, 128, 2],
|
||||
[wire_format.EnumByteSize, wire_format.UINT32_MAX, 5],
|
||||
]
|
||||
for args in NUMERIC_ARGS:
|
||||
self.NumericByteSizeTestHelper(*args)
|
||||
|
||||
# Test strings and bytes.
|
||||
for byte_size_fn in (wire_format.StringByteSize, wire_format.BytesByteSize):
|
||||
# 1 byte for tag, 1 byte for length, 3 bytes for contents.
|
||||
self.assertEqual(5, byte_size_fn(10, 'abc'))
|
||||
# 2 bytes for tag, 1 byte for length, 3 bytes for contents.
|
||||
self.assertEqual(6, byte_size_fn(16, 'abc'))
|
||||
# 2 bytes for tag, 2 bytes for length, 128 bytes for contents.
|
||||
self.assertEqual(132, byte_size_fn(16, 'a' * 128))
|
||||
|
||||
# Test UTF-8 string byte size calculation.
|
||||
# 1 byte for tag, 1 byte for length, 8 bytes for content.
|
||||
self.assertEqual(10, wire_format.StringByteSize(
|
||||
5, unicode('\xd0\xa2\xd0\xb5\xd1\x81\xd1\x82', 'utf-8')))
|
||||
|
||||
class MockMessage(object):
|
||||
def __init__(self, byte_size):
|
||||
self.byte_size = byte_size
|
||||
def ByteSize(self):
|
||||
return self.byte_size
|
||||
|
||||
message_byte_size = 10
|
||||
mock_message = MockMessage(byte_size=message_byte_size)
|
||||
# Test groups.
|
||||
# (2 * 1) bytes for begin and end tags, plus message_byte_size.
|
||||
self.assertEqual(2 + message_byte_size,
|
||||
wire_format.GroupByteSize(1, mock_message))
|
||||
# (2 * 2) bytes for begin and end tags, plus message_byte_size.
|
||||
self.assertEqual(4 + message_byte_size,
|
||||
wire_format.GroupByteSize(16, mock_message))
|
||||
|
||||
# Test messages.
|
||||
# 1 byte for tag, plus 1 byte for length, plus contents.
|
||||
self.assertEqual(2 + mock_message.byte_size,
|
||||
wire_format.MessageByteSize(1, mock_message))
|
||||
# 2 bytes for tag, plus 1 byte for length, plus contents.
|
||||
self.assertEqual(3 + mock_message.byte_size,
|
||||
wire_format.MessageByteSize(16, mock_message))
|
||||
# 2 bytes for tag, plus 2 bytes for length, plus contents.
|
||||
mock_message.byte_size = 128
|
||||
self.assertEqual(4 + mock_message.byte_size,
|
||||
wire_format.MessageByteSize(16, mock_message))
|
||||
|
||||
|
||||
# Test message set item byte size.
|
||||
# 4 bytes for tags, plus 1 byte for length, plus 1 byte for type_id,
|
||||
# plus contents.
|
||||
mock_message.byte_size = 10
|
||||
self.assertEqual(mock_message.byte_size + 6,
|
||||
wire_format.MessageSetItemByteSize(1, mock_message))
|
||||
|
||||
# 4 bytes for tags, plus 2 bytes for length, plus 1 byte for type_id,
|
||||
# plus contents.
|
||||
mock_message.byte_size = 128
|
||||
self.assertEqual(mock_message.byte_size + 7,
|
||||
wire_format.MessageSetItemByteSize(1, mock_message))
|
||||
|
||||
# 4 bytes for tags, plus 2 bytes for length, plus 2 byte for type_id,
|
||||
# plus contents.
|
||||
self.assertEqual(mock_message.byte_size + 8,
|
||||
wire_format.MessageSetItemByteSize(128, mock_message))
|
||||
|
||||
# Too-long varint.
|
||||
self.assertRaises(message.EncodeError,
|
||||
wire_format.UInt64ByteSize, 1, 1 << 128)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
#! /usr/bin/python
|
||||
#
|
||||
# Protocol Buffers - Google's data interchange format
|
||||
# Copyright 2008 Google Inc. All rights reserved.
|
||||
# http://code.google.com/p/protobuf/
|
||||
#
|
||||
# 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.
|
||||
|
||||
"""Test for google.protobuf.internal.wire_format."""
|
||||
|
||||
__author__ = 'robinson@google.com (Will Robinson)'
|
||||
|
||||
import unittest
|
||||
from google.protobuf import message
|
||||
from google.protobuf.internal import wire_format
|
||||
|
||||
|
||||
class WireFormatTest(unittest.TestCase):
|
||||
|
||||
def testPackTag(self):
|
||||
field_number = 0xabc
|
||||
tag_type = 2
|
||||
self.assertEqual((field_number << 3) | tag_type,
|
||||
wire_format.PackTag(field_number, tag_type))
|
||||
PackTag = wire_format.PackTag
|
||||
# Number too high.
|
||||
self.assertRaises(message.EncodeError, PackTag, field_number, 6)
|
||||
# Number too low.
|
||||
self.assertRaises(message.EncodeError, PackTag, field_number, -1)
|
||||
|
||||
def testUnpackTag(self):
|
||||
# Test field numbers that will require various varint sizes.
|
||||
for expected_field_number in (1, 15, 16, 2047, 2048):
|
||||
for expected_wire_type in range(6): # Highest-numbered wiretype is 5.
|
||||
field_number, wire_type = wire_format.UnpackTag(
|
||||
wire_format.PackTag(expected_field_number, expected_wire_type))
|
||||
self.assertEqual(expected_field_number, field_number)
|
||||
self.assertEqual(expected_wire_type, wire_type)
|
||||
|
||||
self.assertRaises(TypeError, wire_format.UnpackTag, None)
|
||||
self.assertRaises(TypeError, wire_format.UnpackTag, 'abc')
|
||||
self.assertRaises(TypeError, wire_format.UnpackTag, 0.0)
|
||||
self.assertRaises(TypeError, wire_format.UnpackTag, object())
|
||||
|
||||
def testZigZagEncode(self):
|
||||
Z = wire_format.ZigZagEncode
|
||||
self.assertEqual(0, Z(0))
|
||||
self.assertEqual(1, Z(-1))
|
||||
self.assertEqual(2, Z(1))
|
||||
self.assertEqual(3, Z(-2))
|
||||
self.assertEqual(4, Z(2))
|
||||
self.assertEqual(0xfffffffe, Z(0x7fffffff))
|
||||
self.assertEqual(0xffffffff, Z(-0x80000000))
|
||||
self.assertEqual(0xfffffffffffffffe, Z(0x7fffffffffffffff))
|
||||
self.assertEqual(0xffffffffffffffff, Z(-0x8000000000000000))
|
||||
|
||||
self.assertRaises(TypeError, Z, None)
|
||||
self.assertRaises(TypeError, Z, 'abcd')
|
||||
self.assertRaises(TypeError, Z, 0.0)
|
||||
self.assertRaises(TypeError, Z, object())
|
||||
|
||||
def testZigZagDecode(self):
|
||||
Z = wire_format.ZigZagDecode
|
||||
self.assertEqual(0, Z(0))
|
||||
self.assertEqual(-1, Z(1))
|
||||
self.assertEqual(1, Z(2))
|
||||
self.assertEqual(-2, Z(3))
|
||||
self.assertEqual(2, Z(4))
|
||||
self.assertEqual(0x7fffffff, Z(0xfffffffe))
|
||||
self.assertEqual(-0x80000000, Z(0xffffffff))
|
||||
self.assertEqual(0x7fffffffffffffff, Z(0xfffffffffffffffe))
|
||||
self.assertEqual(-0x8000000000000000, Z(0xffffffffffffffff))
|
||||
|
||||
self.assertRaises(TypeError, Z, None)
|
||||
self.assertRaises(TypeError, Z, 'abcd')
|
||||
self.assertRaises(TypeError, Z, 0.0)
|
||||
self.assertRaises(TypeError, Z, object())
|
||||
|
||||
def NumericByteSizeTestHelper(self, byte_size_fn, value, expected_value_size):
|
||||
# Use field numbers that cause various byte sizes for the tag information.
|
||||
for field_number, tag_bytes in ((15, 1), (16, 2), (2047, 2), (2048, 3)):
|
||||
expected_size = expected_value_size + tag_bytes
|
||||
actual_size = byte_size_fn(field_number, value)
|
||||
self.assertEqual(expected_size, actual_size,
|
||||
'byte_size_fn: %s, field_number: %d, value: %r\n'
|
||||
'Expected: %d, Actual: %d'% (
|
||||
byte_size_fn, field_number, value, expected_size, actual_size))
|
||||
|
||||
def testByteSizeFunctions(self):
|
||||
# Test all numeric *ByteSize() functions.
|
||||
NUMERIC_ARGS = [
|
||||
# Int32ByteSize().
|
||||
[wire_format.Int32ByteSize, 0, 1],
|
||||
[wire_format.Int32ByteSize, 127, 1],
|
||||
[wire_format.Int32ByteSize, 128, 2],
|
||||
[wire_format.Int32ByteSize, -1, 10],
|
||||
# Int64ByteSize().
|
||||
[wire_format.Int64ByteSize, 0, 1],
|
||||
[wire_format.Int64ByteSize, 127, 1],
|
||||
[wire_format.Int64ByteSize, 128, 2],
|
||||
[wire_format.Int64ByteSize, -1, 10],
|
||||
# UInt32ByteSize().
|
||||
[wire_format.UInt32ByteSize, 0, 1],
|
||||
[wire_format.UInt32ByteSize, 127, 1],
|
||||
[wire_format.UInt32ByteSize, 128, 2],
|
||||
[wire_format.UInt32ByteSize, wire_format.UINT32_MAX, 5],
|
||||
# UInt64ByteSize().
|
||||
[wire_format.UInt64ByteSize, 0, 1],
|
||||
[wire_format.UInt64ByteSize, 127, 1],
|
||||
[wire_format.UInt64ByteSize, 128, 2],
|
||||
[wire_format.UInt64ByteSize, wire_format.UINT64_MAX, 10],
|
||||
# SInt32ByteSize().
|
||||
[wire_format.SInt32ByteSize, 0, 1],
|
||||
[wire_format.SInt32ByteSize, -1, 1],
|
||||
[wire_format.SInt32ByteSize, 1, 1],
|
||||
[wire_format.SInt32ByteSize, -63, 1],
|
||||
[wire_format.SInt32ByteSize, 63, 1],
|
||||
[wire_format.SInt32ByteSize, -64, 1],
|
||||
[wire_format.SInt32ByteSize, 64, 2],
|
||||
# SInt64ByteSize().
|
||||
[wire_format.SInt64ByteSize, 0, 1],
|
||||
[wire_format.SInt64ByteSize, -1, 1],
|
||||
[wire_format.SInt64ByteSize, 1, 1],
|
||||
[wire_format.SInt64ByteSize, -63, 1],
|
||||
[wire_format.SInt64ByteSize, 63, 1],
|
||||
[wire_format.SInt64ByteSize, -64, 1],
|
||||
[wire_format.SInt64ByteSize, 64, 2],
|
||||
# Fixed32ByteSize().
|
||||
[wire_format.Fixed32ByteSize, 0, 4],
|
||||
[wire_format.Fixed32ByteSize, wire_format.UINT32_MAX, 4],
|
||||
# Fixed64ByteSize().
|
||||
[wire_format.Fixed64ByteSize, 0, 8],
|
||||
[wire_format.Fixed64ByteSize, wire_format.UINT64_MAX, 8],
|
||||
# SFixed32ByteSize().
|
||||
[wire_format.SFixed32ByteSize, 0, 4],
|
||||
[wire_format.SFixed32ByteSize, wire_format.INT32_MIN, 4],
|
||||
[wire_format.SFixed32ByteSize, wire_format.INT32_MAX, 4],
|
||||
# SFixed64ByteSize().
|
||||
[wire_format.SFixed64ByteSize, 0, 8],
|
||||
[wire_format.SFixed64ByteSize, wire_format.INT64_MIN, 8],
|
||||
[wire_format.SFixed64ByteSize, wire_format.INT64_MAX, 8],
|
||||
# FloatByteSize().
|
||||
[wire_format.FloatByteSize, 0.0, 4],
|
||||
[wire_format.FloatByteSize, 1000000000.0, 4],
|
||||
[wire_format.FloatByteSize, -1000000000.0, 4],
|
||||
# DoubleByteSize().
|
||||
[wire_format.DoubleByteSize, 0.0, 8],
|
||||
[wire_format.DoubleByteSize, 1000000000.0, 8],
|
||||
[wire_format.DoubleByteSize, -1000000000.0, 8],
|
||||
# BoolByteSize().
|
||||
[wire_format.BoolByteSize, False, 1],
|
||||
[wire_format.BoolByteSize, True, 1],
|
||||
# EnumByteSize().
|
||||
[wire_format.EnumByteSize, 0, 1],
|
||||
[wire_format.EnumByteSize, 127, 1],
|
||||
[wire_format.EnumByteSize, 128, 2],
|
||||
[wire_format.EnumByteSize, wire_format.UINT32_MAX, 5],
|
||||
]
|
||||
for args in NUMERIC_ARGS:
|
||||
self.NumericByteSizeTestHelper(*args)
|
||||
|
||||
# Test strings and bytes.
|
||||
for byte_size_fn in (wire_format.StringByteSize, wire_format.BytesByteSize):
|
||||
# 1 byte for tag, 1 byte for length, 3 bytes for contents.
|
||||
self.assertEqual(5, byte_size_fn(10, 'abc'))
|
||||
# 2 bytes for tag, 1 byte for length, 3 bytes for contents.
|
||||
self.assertEqual(6, byte_size_fn(16, 'abc'))
|
||||
# 2 bytes for tag, 2 bytes for length, 128 bytes for contents.
|
||||
self.assertEqual(132, byte_size_fn(16, 'a' * 128))
|
||||
|
||||
# Test UTF-8 string byte size calculation.
|
||||
# 1 byte for tag, 1 byte for length, 8 bytes for content.
|
||||
self.assertEqual(10, wire_format.StringByteSize(
|
||||
5, unicode('\xd0\xa2\xd0\xb5\xd1\x81\xd1\x82', 'utf-8')))
|
||||
|
||||
class MockMessage(object):
|
||||
def __init__(self, byte_size):
|
||||
self.byte_size = byte_size
|
||||
def ByteSize(self):
|
||||
return self.byte_size
|
||||
|
||||
message_byte_size = 10
|
||||
mock_message = MockMessage(byte_size=message_byte_size)
|
||||
# Test groups.
|
||||
# (2 * 1) bytes for begin and end tags, plus message_byte_size.
|
||||
self.assertEqual(2 + message_byte_size,
|
||||
wire_format.GroupByteSize(1, mock_message))
|
||||
# (2 * 2) bytes for begin and end tags, plus message_byte_size.
|
||||
self.assertEqual(4 + message_byte_size,
|
||||
wire_format.GroupByteSize(16, mock_message))
|
||||
|
||||
# Test messages.
|
||||
# 1 byte for tag, plus 1 byte for length, plus contents.
|
||||
self.assertEqual(2 + mock_message.byte_size,
|
||||
wire_format.MessageByteSize(1, mock_message))
|
||||
# 2 bytes for tag, plus 1 byte for length, plus contents.
|
||||
self.assertEqual(3 + mock_message.byte_size,
|
||||
wire_format.MessageByteSize(16, mock_message))
|
||||
# 2 bytes for tag, plus 2 bytes for length, plus contents.
|
||||
mock_message.byte_size = 128
|
||||
self.assertEqual(4 + mock_message.byte_size,
|
||||
wire_format.MessageByteSize(16, mock_message))
|
||||
|
||||
|
||||
# Test message set item byte size.
|
||||
# 4 bytes for tags, plus 1 byte for length, plus 1 byte for type_id,
|
||||
# plus contents.
|
||||
mock_message.byte_size = 10
|
||||
self.assertEqual(mock_message.byte_size + 6,
|
||||
wire_format.MessageSetItemByteSize(1, mock_message))
|
||||
|
||||
# 4 bytes for tags, plus 2 bytes for length, plus 1 byte for type_id,
|
||||
# plus contents.
|
||||
mock_message.byte_size = 128
|
||||
self.assertEqual(mock_message.byte_size + 7,
|
||||
wire_format.MessageSetItemByteSize(1, mock_message))
|
||||
|
||||
# 4 bytes for tags, plus 2 bytes for length, plus 2 byte for type_id,
|
||||
# plus contents.
|
||||
self.assertEqual(mock_message.byte_size + 8,
|
||||
wire_format.MessageSetItemByteSize(128, mock_message))
|
||||
|
||||
# Too-long varint.
|
||||
self.assertRaises(message.EncodeError,
|
||||
wire_format.UInt64ByteSize, 1, 1 << 128)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
|
||||
+254
-254
@@ -1,254 +1,254 @@
|
||||
# Protocol Buffers - Google's data interchange format
|
||||
# Copyright 2008 Google Inc. All rights reserved.
|
||||
# http://code.google.com/p/protobuf/
|
||||
#
|
||||
# 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.
|
||||
|
||||
# TODO(robinson): We should just make these methods all "pure-virtual" and move
|
||||
# all implementation out, into reflection.py for now.
|
||||
|
||||
|
||||
"""Contains an abstract base class for protocol messages."""
|
||||
|
||||
__author__ = 'robinson@google.com (Will Robinson)'
|
||||
|
||||
|
||||
class Error(Exception): pass
|
||||
class DecodeError(Error): pass
|
||||
class EncodeError(Error): pass
|
||||
|
||||
|
||||
class Message(object):
|
||||
|
||||
"""Abstract base class for protocol messages.
|
||||
|
||||
Protocol message classes are almost always generated by the protocol
|
||||
compiler. These generated types subclass Message and implement the methods
|
||||
shown below.
|
||||
|
||||
TODO(robinson): Link to an HTML document here.
|
||||
|
||||
TODO(robinson): Document that instances of this class will also
|
||||
have an Extensions attribute with __getitem__ and __setitem__.
|
||||
Again, not sure how to best convey this.
|
||||
|
||||
TODO(robinson): Document that the class must also have a static
|
||||
RegisterExtension(extension_field) method.
|
||||
Not sure how to best express at this point.
|
||||
"""
|
||||
|
||||
# TODO(robinson): Document these fields and methods.
|
||||
|
||||
__slots__ = []
|
||||
|
||||
DESCRIPTOR = None
|
||||
|
||||
def __eq__(self, other_msg):
|
||||
raise NotImplementedError
|
||||
|
||||
def __ne__(self, other_msg):
|
||||
# Can't just say self != other_msg, since that would infinitely recurse. :)
|
||||
return not self == other_msg
|
||||
|
||||
def __str__(self):
|
||||
raise NotImplementedError
|
||||
|
||||
def MergeFrom(self, other_msg):
|
||||
"""Merges the contents of the specified message into current message.
|
||||
|
||||
This method merges the contents of the specified message into the current
|
||||
message. Singular fields that are set in the specified message overwrite
|
||||
the corresponding fields in the current message. Repeated fields are
|
||||
appended. Singular sub-messages and groups are recursively merged.
|
||||
|
||||
Args:
|
||||
other_msg: Message to merge into the current message.
|
||||
"""
|
||||
raise NotImplementedError
|
||||
|
||||
def CopyFrom(self, other_msg):
|
||||
"""Copies the content of the specified message into the current message.
|
||||
|
||||
The method clears the current message and then merges the specified
|
||||
message using MergeFrom.
|
||||
|
||||
Args:
|
||||
other_msg: Message to copy into the current one.
|
||||
"""
|
||||
if self is other_msg:
|
||||
return
|
||||
self.Clear()
|
||||
self.MergeFrom(other_msg)
|
||||
|
||||
def Clear(self):
|
||||
"""Clears all data that was set in the message."""
|
||||
raise NotImplementedError
|
||||
|
||||
def SetInParent(self):
|
||||
"""Mark this as present in the parent.
|
||||
|
||||
This normally happens automatically when you assign a field of a
|
||||
sub-message, but sometimes you want to make the sub-message
|
||||
present while keeping it empty. If you find yourself using this,
|
||||
you may want to reconsider your design."""
|
||||
raise NotImplementedError
|
||||
|
||||
def IsInitialized(self):
|
||||
"""Checks if the message is initialized.
|
||||
|
||||
Returns:
|
||||
The method returns True if the message is initialized (i.e. all of its
|
||||
required fields are set).
|
||||
"""
|
||||
raise NotImplementedError
|
||||
|
||||
# TODO(robinson): MergeFromString() should probably return None and be
|
||||
# implemented in terms of a helper that returns the # of bytes read. Our
|
||||
# deserialization routines would use the helper when recursively
|
||||
# deserializing, but the end user would almost always just want the no-return
|
||||
# MergeFromString().
|
||||
|
||||
def MergeFromString(self, serialized):
|
||||
"""Merges serialized protocol buffer data into this message.
|
||||
|
||||
When we find a field in |serialized| that is already present
|
||||
in this message:
|
||||
- If it's a "repeated" field, we append to the end of our list.
|
||||
- Else, if it's a scalar, we overwrite our field.
|
||||
- Else, (it's a nonrepeated composite), we recursively merge
|
||||
into the existing composite.
|
||||
|
||||
TODO(robinson): Document handling of unknown fields.
|
||||
|
||||
Args:
|
||||
serialized: Any object that allows us to call buffer(serialized)
|
||||
to access a string of bytes using the buffer interface.
|
||||
|
||||
TODO(robinson): When we switch to a helper, this will return None.
|
||||
|
||||
Returns:
|
||||
The number of bytes read from |serialized|.
|
||||
For non-group messages, this will always be len(serialized),
|
||||
but for messages which are actually groups, this will
|
||||
generally be less than len(serialized), since we must
|
||||
stop when we reach an END_GROUP tag. Note that if
|
||||
we *do* stop because of an END_GROUP tag, the number
|
||||
of bytes returned does not include the bytes
|
||||
for the END_GROUP tag information.
|
||||
"""
|
||||
raise NotImplementedError
|
||||
|
||||
def ParseFromString(self, serialized):
|
||||
"""Like MergeFromString(), except we clear the object first."""
|
||||
self.Clear()
|
||||
self.MergeFromString(serialized)
|
||||
|
||||
def SerializeToString(self):
|
||||
"""Serializes the protocol message to a binary string.
|
||||
|
||||
Returns:
|
||||
A binary string representation of the message if all of the required
|
||||
fields in the message are set (i.e. the message is initialized).
|
||||
|
||||
Raises:
|
||||
message.EncodeError if the message isn't initialized.
|
||||
"""
|
||||
raise NotImplementedError
|
||||
|
||||
def SerializePartialToString(self):
|
||||
"""Serializes the protocol message to a binary string.
|
||||
|
||||
This method is similar to SerializeToString but doesn't check if the
|
||||
message is initialized.
|
||||
|
||||
Returns:
|
||||
A string representation of the partial message.
|
||||
"""
|
||||
raise NotImplementedError
|
||||
|
||||
# TODO(robinson): Decide whether we like these better
|
||||
# than auto-generated has_foo() and clear_foo() methods
|
||||
# on the instances themselves. This way is less consistent
|
||||
# with C++, but it makes reflection-type access easier and
|
||||
# reduces the number of magically autogenerated things.
|
||||
#
|
||||
# TODO(robinson): Be sure to document (and test) exactly
|
||||
# which field names are accepted here. Are we case-sensitive?
|
||||
# What do we do with fields that share names with Python keywords
|
||||
# like 'lambda' and 'yield'?
|
||||
#
|
||||
# nnorwitz says:
|
||||
# """
|
||||
# Typically (in python), an underscore is appended to names that are
|
||||
# keywords. So they would become lambda_ or yield_.
|
||||
# """
|
||||
def ListFields(self):
|
||||
"""Returns a list of (FieldDescriptor, value) tuples for all
|
||||
fields in the message which are not empty. A singular field is non-empty
|
||||
if HasField() would return true, and a repeated field is non-empty if
|
||||
it contains at least one element. The fields are ordered by field
|
||||
number"""
|
||||
raise NotImplementedError
|
||||
|
||||
def HasField(self, field_name):
|
||||
raise NotImplementedError
|
||||
|
||||
def ClearField(self, field_name):
|
||||
raise NotImplementedError
|
||||
|
||||
def HasExtension(self, extension_handle):
|
||||
raise NotImplementedError
|
||||
|
||||
def ClearExtension(self, extension_handle):
|
||||
raise NotImplementedError
|
||||
|
||||
def ByteSize(self):
|
||||
"""Returns the serialized size of this message.
|
||||
Recursively calls ByteSize() on all contained messages.
|
||||
"""
|
||||
raise NotImplementedError
|
||||
|
||||
def _SetListener(self, message_listener):
|
||||
"""Internal method used by the protocol message implementation.
|
||||
Clients should not call this directly.
|
||||
|
||||
Sets a listener that this message will call on certain state transitions.
|
||||
|
||||
The purpose of this method is to register back-edges from children to
|
||||
parents at runtime, for the purpose of setting "has" bits and
|
||||
byte-size-dirty bits in the parent and ancestor objects whenever a child or
|
||||
descendant object is modified.
|
||||
|
||||
If the client wants to disconnect this Message from the object tree, she
|
||||
explicitly sets callback to None.
|
||||
|
||||
If message_listener is None, unregisters any existing listener. Otherwise,
|
||||
message_listener must implement the MessageListener interface in
|
||||
internal/message_listener.py, and we discard any listener registered
|
||||
via a previous _SetListener() call.
|
||||
"""
|
||||
raise NotImplementedError
|
||||
# Protocol Buffers - Google's data interchange format
|
||||
# Copyright 2008 Google Inc. All rights reserved.
|
||||
# http://code.google.com/p/protobuf/
|
||||
#
|
||||
# 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.
|
||||
|
||||
# TODO(robinson): We should just make these methods all "pure-virtual" and move
|
||||
# all implementation out, into reflection.py for now.
|
||||
|
||||
|
||||
"""Contains an abstract base class for protocol messages."""
|
||||
|
||||
__author__ = 'robinson@google.com (Will Robinson)'
|
||||
|
||||
|
||||
class Error(Exception): pass
|
||||
class DecodeError(Error): pass
|
||||
class EncodeError(Error): pass
|
||||
|
||||
|
||||
class Message(object):
|
||||
|
||||
"""Abstract base class for protocol messages.
|
||||
|
||||
Protocol message classes are almost always generated by the protocol
|
||||
compiler. These generated types subclass Message and implement the methods
|
||||
shown below.
|
||||
|
||||
TODO(robinson): Link to an HTML document here.
|
||||
|
||||
TODO(robinson): Document that instances of this class will also
|
||||
have an Extensions attribute with __getitem__ and __setitem__.
|
||||
Again, not sure how to best convey this.
|
||||
|
||||
TODO(robinson): Document that the class must also have a static
|
||||
RegisterExtension(extension_field) method.
|
||||
Not sure how to best express at this point.
|
||||
"""
|
||||
|
||||
# TODO(robinson): Document these fields and methods.
|
||||
|
||||
__slots__ = []
|
||||
|
||||
DESCRIPTOR = None
|
||||
|
||||
def __eq__(self, other_msg):
|
||||
raise NotImplementedError
|
||||
|
||||
def __ne__(self, other_msg):
|
||||
# Can't just say self != other_msg, since that would infinitely recurse. :)
|
||||
return not self == other_msg
|
||||
|
||||
def __str__(self):
|
||||
raise NotImplementedError
|
||||
|
||||
def MergeFrom(self, other_msg):
|
||||
"""Merges the contents of the specified message into current message.
|
||||
|
||||
This method merges the contents of the specified message into the current
|
||||
message. Singular fields that are set in the specified message overwrite
|
||||
the corresponding fields in the current message. Repeated fields are
|
||||
appended. Singular sub-messages and groups are recursively merged.
|
||||
|
||||
Args:
|
||||
other_msg: Message to merge into the current message.
|
||||
"""
|
||||
raise NotImplementedError
|
||||
|
||||
def CopyFrom(self, other_msg):
|
||||
"""Copies the content of the specified message into the current message.
|
||||
|
||||
The method clears the current message and then merges the specified
|
||||
message using MergeFrom.
|
||||
|
||||
Args:
|
||||
other_msg: Message to copy into the current one.
|
||||
"""
|
||||
if self is other_msg:
|
||||
return
|
||||
self.Clear()
|
||||
self.MergeFrom(other_msg)
|
||||
|
||||
def Clear(self):
|
||||
"""Clears all data that was set in the message."""
|
||||
raise NotImplementedError
|
||||
|
||||
def SetInParent(self):
|
||||
"""Mark this as present in the parent.
|
||||
|
||||
This normally happens automatically when you assign a field of a
|
||||
sub-message, but sometimes you want to make the sub-message
|
||||
present while keeping it empty. If you find yourself using this,
|
||||
you may want to reconsider your design."""
|
||||
raise NotImplementedError
|
||||
|
||||
def IsInitialized(self):
|
||||
"""Checks if the message is initialized.
|
||||
|
||||
Returns:
|
||||
The method returns True if the message is initialized (i.e. all of its
|
||||
required fields are set).
|
||||
"""
|
||||
raise NotImplementedError
|
||||
|
||||
# TODO(robinson): MergeFromString() should probably return None and be
|
||||
# implemented in terms of a helper that returns the # of bytes read. Our
|
||||
# deserialization routines would use the helper when recursively
|
||||
# deserializing, but the end user would almost always just want the no-return
|
||||
# MergeFromString().
|
||||
|
||||
def MergeFromString(self, serialized):
|
||||
"""Merges serialized protocol buffer data into this message.
|
||||
|
||||
When we find a field in |serialized| that is already present
|
||||
in this message:
|
||||
- If it's a "repeated" field, we append to the end of our list.
|
||||
- Else, if it's a scalar, we overwrite our field.
|
||||
- Else, (it's a nonrepeated composite), we recursively merge
|
||||
into the existing composite.
|
||||
|
||||
TODO(robinson): Document handling of unknown fields.
|
||||
|
||||
Args:
|
||||
serialized: Any object that allows us to call buffer(serialized)
|
||||
to access a string of bytes using the buffer interface.
|
||||
|
||||
TODO(robinson): When we switch to a helper, this will return None.
|
||||
|
||||
Returns:
|
||||
The number of bytes read from |serialized|.
|
||||
For non-group messages, this will always be len(serialized),
|
||||
but for messages which are actually groups, this will
|
||||
generally be less than len(serialized), since we must
|
||||
stop when we reach an END_GROUP tag. Note that if
|
||||
we *do* stop because of an END_GROUP tag, the number
|
||||
of bytes returned does not include the bytes
|
||||
for the END_GROUP tag information.
|
||||
"""
|
||||
raise NotImplementedError
|
||||
|
||||
def ParseFromString(self, serialized):
|
||||
"""Like MergeFromString(), except we clear the object first."""
|
||||
self.Clear()
|
||||
self.MergeFromString(serialized)
|
||||
|
||||
def SerializeToString(self):
|
||||
"""Serializes the protocol message to a binary string.
|
||||
|
||||
Returns:
|
||||
A binary string representation of the message if all of the required
|
||||
fields in the message are set (i.e. the message is initialized).
|
||||
|
||||
Raises:
|
||||
message.EncodeError if the message isn't initialized.
|
||||
"""
|
||||
raise NotImplementedError
|
||||
|
||||
def SerializePartialToString(self):
|
||||
"""Serializes the protocol message to a binary string.
|
||||
|
||||
This method is similar to SerializeToString but doesn't check if the
|
||||
message is initialized.
|
||||
|
||||
Returns:
|
||||
A string representation of the partial message.
|
||||
"""
|
||||
raise NotImplementedError
|
||||
|
||||
# TODO(robinson): Decide whether we like these better
|
||||
# than auto-generated has_foo() and clear_foo() methods
|
||||
# on the instances themselves. This way is less consistent
|
||||
# with C++, but it makes reflection-type access easier and
|
||||
# reduces the number of magically autogenerated things.
|
||||
#
|
||||
# TODO(robinson): Be sure to document (and test) exactly
|
||||
# which field names are accepted here. Are we case-sensitive?
|
||||
# What do we do with fields that share names with Python keywords
|
||||
# like 'lambda' and 'yield'?
|
||||
#
|
||||
# nnorwitz says:
|
||||
# """
|
||||
# Typically (in python), an underscore is appended to names that are
|
||||
# keywords. So they would become lambda_ or yield_.
|
||||
# """
|
||||
def ListFields(self):
|
||||
"""Returns a list of (FieldDescriptor, value) tuples for all
|
||||
fields in the message which are not empty. A singular field is non-empty
|
||||
if HasField() would return true, and a repeated field is non-empty if
|
||||
it contains at least one element. The fields are ordered by field
|
||||
number"""
|
||||
raise NotImplementedError
|
||||
|
||||
def HasField(self, field_name):
|
||||
raise NotImplementedError
|
||||
|
||||
def ClearField(self, field_name):
|
||||
raise NotImplementedError
|
||||
|
||||
def HasExtension(self, extension_handle):
|
||||
raise NotImplementedError
|
||||
|
||||
def ClearExtension(self, extension_handle):
|
||||
raise NotImplementedError
|
||||
|
||||
def ByteSize(self):
|
||||
"""Returns the serialized size of this message.
|
||||
Recursively calls ByteSize() on all contained messages.
|
||||
"""
|
||||
raise NotImplementedError
|
||||
|
||||
def _SetListener(self, message_listener):
|
||||
"""Internal method used by the protocol message implementation.
|
||||
Clients should not call this directly.
|
||||
|
||||
Sets a listener that this message will call on certain state transitions.
|
||||
|
||||
The purpose of this method is to register back-edges from children to
|
||||
parents at runtime, for the purpose of setting "has" bits and
|
||||
byte-size-dirty bits in the parent and ancestor objects whenever a child or
|
||||
descendant object is modified.
|
||||
|
||||
If the client wants to disconnect this Message from the object tree, she
|
||||
explicitly sets callback to None.
|
||||
|
||||
If message_listener is None, unregisters any existing listener. Otherwise,
|
||||
message_listener must implement the MessageListener interface in
|
||||
internal/message_listener.py, and we discard any listener registered
|
||||
via a previous _SetListener() call.
|
||||
"""
|
||||
raise NotImplementedError
|
||||
|
||||
+1148
-1148
File diff suppressed because it is too large
Load Diff
+226
-226
@@ -1,226 +1,226 @@
|
||||
# Protocol Buffers - Google's data interchange format
|
||||
# Copyright 2008 Google Inc. All rights reserved.
|
||||
# http://code.google.com/p/protobuf/
|
||||
#
|
||||
# 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.
|
||||
|
||||
"""DEPRECATED: Declares the RPC service interfaces.
|
||||
|
||||
This module declares the abstract interfaces underlying proto2 RPC
|
||||
services. These are intended to be independent of any particular RPC
|
||||
implementation, so that proto2 services can be used on top of a variety
|
||||
of implementations. Starting with version 2.3.0, RPC implementations should
|
||||
not try to build on these, but should instead provide code generator plugins
|
||||
which generate code specific to the particular RPC implementation. This way
|
||||
the generated code can be more appropriate for the implementation in use
|
||||
and can avoid unnecessary layers of indirection.
|
||||
"""
|
||||
|
||||
__author__ = 'petar@google.com (Petar Petrov)'
|
||||
|
||||
|
||||
class RpcException(Exception):
|
||||
"""Exception raised on failed blocking RPC method call."""
|
||||
pass
|
||||
|
||||
|
||||
class Service(object):
|
||||
|
||||
"""Abstract base interface for protocol-buffer-based RPC services.
|
||||
|
||||
Services themselves are abstract classes (implemented either by servers or as
|
||||
stubs), but they subclass this base interface. The methods of this
|
||||
interface can be used to call the methods of the service without knowing
|
||||
its exact type at compile time (analogous to the Message interface).
|
||||
"""
|
||||
|
||||
def GetDescriptor():
|
||||
"""Retrieves this service's descriptor."""
|
||||
raise NotImplementedError
|
||||
|
||||
def CallMethod(self, method_descriptor, rpc_controller,
|
||||
request, done):
|
||||
"""Calls a method of the service specified by method_descriptor.
|
||||
|
||||
If "done" is None then the call is blocking and the response
|
||||
message will be returned directly. Otherwise the call is asynchronous
|
||||
and "done" will later be called with the response value.
|
||||
|
||||
In the blocking case, RpcException will be raised on error.
|
||||
|
||||
Preconditions:
|
||||
* method_descriptor.service == GetDescriptor
|
||||
* request is of the exact same classes as returned by
|
||||
GetRequestClass(method).
|
||||
* After the call has started, the request must not be modified.
|
||||
* "rpc_controller" is of the correct type for the RPC implementation being
|
||||
used by this Service. For stubs, the "correct type" depends on the
|
||||
RpcChannel which the stub is using.
|
||||
|
||||
Postconditions:
|
||||
* "done" will be called when the method is complete. This may be
|
||||
before CallMethod() returns or it may be at some point in the future.
|
||||
* If the RPC failed, the response value passed to "done" will be None.
|
||||
Further details about the failure can be found by querying the
|
||||
RpcController.
|
||||
"""
|
||||
raise NotImplementedError
|
||||
|
||||
def GetRequestClass(self, method_descriptor):
|
||||
"""Returns the class of the request message for the specified method.
|
||||
|
||||
CallMethod() requires that the request is of a particular subclass of
|
||||
Message. GetRequestClass() gets the default instance of this required
|
||||
type.
|
||||
|
||||
Example:
|
||||
method = service.GetDescriptor().FindMethodByName("Foo")
|
||||
request = stub.GetRequestClass(method)()
|
||||
request.ParseFromString(input)
|
||||
service.CallMethod(method, request, callback)
|
||||
"""
|
||||
raise NotImplementedError
|
||||
|
||||
def GetResponseClass(self, method_descriptor):
|
||||
"""Returns the class of the response message for the specified method.
|
||||
|
||||
This method isn't really needed, as the RpcChannel's CallMethod constructs
|
||||
the response protocol message. It's provided anyway in case it is useful
|
||||
for the caller to know the response type in advance.
|
||||
"""
|
||||
raise NotImplementedError
|
||||
|
||||
|
||||
class RpcController(object):
|
||||
|
||||
"""An RpcController mediates a single method call.
|
||||
|
||||
The primary purpose of the controller is to provide a way to manipulate
|
||||
settings specific to the RPC implementation and to find out about RPC-level
|
||||
errors. The methods provided by the RpcController interface are intended
|
||||
to be a "least common denominator" set of features which we expect all
|
||||
implementations to support. Specific implementations may provide more
|
||||
advanced features (e.g. deadline propagation).
|
||||
"""
|
||||
|
||||
# Client-side methods below
|
||||
|
||||
def Reset(self):
|
||||
"""Resets the RpcController to its initial state.
|
||||
|
||||
After the RpcController has been reset, it may be reused in
|
||||
a new call. Must not be called while an RPC is in progress.
|
||||
"""
|
||||
raise NotImplementedError
|
||||
|
||||
def Failed(self):
|
||||
"""Returns true if the call failed.
|
||||
|
||||
After a call has finished, returns true if the call failed. The possible
|
||||
reasons for failure depend on the RPC implementation. Failed() must not
|
||||
be called before a call has finished. If Failed() returns true, the
|
||||
contents of the response message are undefined.
|
||||
"""
|
||||
raise NotImplementedError
|
||||
|
||||
def ErrorText(self):
|
||||
"""If Failed is true, returns a human-readable description of the error."""
|
||||
raise NotImplementedError
|
||||
|
||||
def StartCancel(self):
|
||||
"""Initiate cancellation.
|
||||
|
||||
Advises the RPC system that the caller desires that the RPC call be
|
||||
canceled. The RPC system may cancel it immediately, may wait awhile and
|
||||
then cancel it, or may not even cancel the call at all. If the call is
|
||||
canceled, the "done" callback will still be called and the RpcController
|
||||
will indicate that the call failed at that time.
|
||||
"""
|
||||
raise NotImplementedError
|
||||
|
||||
# Server-side methods below
|
||||
|
||||
def SetFailed(self, reason):
|
||||
"""Sets a failure reason.
|
||||
|
||||
Causes Failed() to return true on the client side. "reason" will be
|
||||
incorporated into the message returned by ErrorText(). If you find
|
||||
you need to return machine-readable information about failures, you
|
||||
should incorporate it into your response protocol buffer and should
|
||||
NOT call SetFailed().
|
||||
"""
|
||||
raise NotImplementedError
|
||||
|
||||
def IsCanceled(self):
|
||||
"""Checks if the client cancelled the RPC.
|
||||
|
||||
If true, indicates that the client canceled the RPC, so the server may
|
||||
as well give up on replying to it. The server should still call the
|
||||
final "done" callback.
|
||||
"""
|
||||
raise NotImplementedError
|
||||
|
||||
def NotifyOnCancel(self, callback):
|
||||
"""Sets a callback to invoke on cancel.
|
||||
|
||||
Asks that the given callback be called when the RPC is canceled. The
|
||||
callback will always be called exactly once. If the RPC completes without
|
||||
being canceled, the callback will be called after completion. If the RPC
|
||||
has already been canceled when NotifyOnCancel() is called, the callback
|
||||
will be called immediately.
|
||||
|
||||
NotifyOnCancel() must be called no more than once per request.
|
||||
"""
|
||||
raise NotImplementedError
|
||||
|
||||
|
||||
class RpcChannel(object):
|
||||
|
||||
"""Abstract interface for an RPC channel.
|
||||
|
||||
An RpcChannel represents a communication line to a service which can be used
|
||||
to call that service's methods. The service may be running on another
|
||||
machine. Normally, you should not use an RpcChannel directly, but instead
|
||||
construct a stub {@link Service} wrapping it. Example:
|
||||
|
||||
Example:
|
||||
RpcChannel channel = rpcImpl.Channel("remotehost.example.com:1234")
|
||||
RpcController controller = rpcImpl.Controller()
|
||||
MyService service = MyService_Stub(channel)
|
||||
service.MyMethod(controller, request, callback)
|
||||
"""
|
||||
|
||||
def CallMethod(self, method_descriptor, rpc_controller,
|
||||
request, response_class, done):
|
||||
"""Calls the method identified by the descriptor.
|
||||
|
||||
Call the given method of the remote service. The signature of this
|
||||
procedure looks the same as Service.CallMethod(), but the requirements
|
||||
are less strict in one important way: the request object doesn't have to
|
||||
be of any specific class as long as its descriptor is method.input_type.
|
||||
"""
|
||||
raise NotImplementedError
|
||||
# Protocol Buffers - Google's data interchange format
|
||||
# Copyright 2008 Google Inc. All rights reserved.
|
||||
# http://code.google.com/p/protobuf/
|
||||
#
|
||||
# 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.
|
||||
|
||||
"""DEPRECATED: Declares the RPC service interfaces.
|
||||
|
||||
This module declares the abstract interfaces underlying proto2 RPC
|
||||
services. These are intended to be independent of any particular RPC
|
||||
implementation, so that proto2 services can be used on top of a variety
|
||||
of implementations. Starting with version 2.3.0, RPC implementations should
|
||||
not try to build on these, but should instead provide code generator plugins
|
||||
which generate code specific to the particular RPC implementation. This way
|
||||
the generated code can be more appropriate for the implementation in use
|
||||
and can avoid unnecessary layers of indirection.
|
||||
"""
|
||||
|
||||
__author__ = 'petar@google.com (Petar Petrov)'
|
||||
|
||||
|
||||
class RpcException(Exception):
|
||||
"""Exception raised on failed blocking RPC method call."""
|
||||
pass
|
||||
|
||||
|
||||
class Service(object):
|
||||
|
||||
"""Abstract base interface for protocol-buffer-based RPC services.
|
||||
|
||||
Services themselves are abstract classes (implemented either by servers or as
|
||||
stubs), but they subclass this base interface. The methods of this
|
||||
interface can be used to call the methods of the service without knowing
|
||||
its exact type at compile time (analogous to the Message interface).
|
||||
"""
|
||||
|
||||
def GetDescriptor():
|
||||
"""Retrieves this service's descriptor."""
|
||||
raise NotImplementedError
|
||||
|
||||
def CallMethod(self, method_descriptor, rpc_controller,
|
||||
request, done):
|
||||
"""Calls a method of the service specified by method_descriptor.
|
||||
|
||||
If "done" is None then the call is blocking and the response
|
||||
message will be returned directly. Otherwise the call is asynchronous
|
||||
and "done" will later be called with the response value.
|
||||
|
||||
In the blocking case, RpcException will be raised on error.
|
||||
|
||||
Preconditions:
|
||||
* method_descriptor.service == GetDescriptor
|
||||
* request is of the exact same classes as returned by
|
||||
GetRequestClass(method).
|
||||
* After the call has started, the request must not be modified.
|
||||
* "rpc_controller" is of the correct type for the RPC implementation being
|
||||
used by this Service. For stubs, the "correct type" depends on the
|
||||
RpcChannel which the stub is using.
|
||||
|
||||
Postconditions:
|
||||
* "done" will be called when the method is complete. This may be
|
||||
before CallMethod() returns or it may be at some point in the future.
|
||||
* If the RPC failed, the response value passed to "done" will be None.
|
||||
Further details about the failure can be found by querying the
|
||||
RpcController.
|
||||
"""
|
||||
raise NotImplementedError
|
||||
|
||||
def GetRequestClass(self, method_descriptor):
|
||||
"""Returns the class of the request message for the specified method.
|
||||
|
||||
CallMethod() requires that the request is of a particular subclass of
|
||||
Message. GetRequestClass() gets the default instance of this required
|
||||
type.
|
||||
|
||||
Example:
|
||||
method = service.GetDescriptor().FindMethodByName("Foo")
|
||||
request = stub.GetRequestClass(method)()
|
||||
request.ParseFromString(input)
|
||||
service.CallMethod(method, request, callback)
|
||||
"""
|
||||
raise NotImplementedError
|
||||
|
||||
def GetResponseClass(self, method_descriptor):
|
||||
"""Returns the class of the response message for the specified method.
|
||||
|
||||
This method isn't really needed, as the RpcChannel's CallMethod constructs
|
||||
the response protocol message. It's provided anyway in case it is useful
|
||||
for the caller to know the response type in advance.
|
||||
"""
|
||||
raise NotImplementedError
|
||||
|
||||
|
||||
class RpcController(object):
|
||||
|
||||
"""An RpcController mediates a single method call.
|
||||
|
||||
The primary purpose of the controller is to provide a way to manipulate
|
||||
settings specific to the RPC implementation and to find out about RPC-level
|
||||
errors. The methods provided by the RpcController interface are intended
|
||||
to be a "least common denominator" set of features which we expect all
|
||||
implementations to support. Specific implementations may provide more
|
||||
advanced features (e.g. deadline propagation).
|
||||
"""
|
||||
|
||||
# Client-side methods below
|
||||
|
||||
def Reset(self):
|
||||
"""Resets the RpcController to its initial state.
|
||||
|
||||
After the RpcController has been reset, it may be reused in
|
||||
a new call. Must not be called while an RPC is in progress.
|
||||
"""
|
||||
raise NotImplementedError
|
||||
|
||||
def Failed(self):
|
||||
"""Returns true if the call failed.
|
||||
|
||||
After a call has finished, returns true if the call failed. The possible
|
||||
reasons for failure depend on the RPC implementation. Failed() must not
|
||||
be called before a call has finished. If Failed() returns true, the
|
||||
contents of the response message are undefined.
|
||||
"""
|
||||
raise NotImplementedError
|
||||
|
||||
def ErrorText(self):
|
||||
"""If Failed is true, returns a human-readable description of the error."""
|
||||
raise NotImplementedError
|
||||
|
||||
def StartCancel(self):
|
||||
"""Initiate cancellation.
|
||||
|
||||
Advises the RPC system that the caller desires that the RPC call be
|
||||
canceled. The RPC system may cancel it immediately, may wait awhile and
|
||||
then cancel it, or may not even cancel the call at all. If the call is
|
||||
canceled, the "done" callback will still be called and the RpcController
|
||||
will indicate that the call failed at that time.
|
||||
"""
|
||||
raise NotImplementedError
|
||||
|
||||
# Server-side methods below
|
||||
|
||||
def SetFailed(self, reason):
|
||||
"""Sets a failure reason.
|
||||
|
||||
Causes Failed() to return true on the client side. "reason" will be
|
||||
incorporated into the message returned by ErrorText(). If you find
|
||||
you need to return machine-readable information about failures, you
|
||||
should incorporate it into your response protocol buffer and should
|
||||
NOT call SetFailed().
|
||||
"""
|
||||
raise NotImplementedError
|
||||
|
||||
def IsCanceled(self):
|
||||
"""Checks if the client cancelled the RPC.
|
||||
|
||||
If true, indicates that the client canceled the RPC, so the server may
|
||||
as well give up on replying to it. The server should still call the
|
||||
final "done" callback.
|
||||
"""
|
||||
raise NotImplementedError
|
||||
|
||||
def NotifyOnCancel(self, callback):
|
||||
"""Sets a callback to invoke on cancel.
|
||||
|
||||
Asks that the given callback be called when the RPC is canceled. The
|
||||
callback will always be called exactly once. If the RPC completes without
|
||||
being canceled, the callback will be called after completion. If the RPC
|
||||
has already been canceled when NotifyOnCancel() is called, the callback
|
||||
will be called immediately.
|
||||
|
||||
NotifyOnCancel() must be called no more than once per request.
|
||||
"""
|
||||
raise NotImplementedError
|
||||
|
||||
|
||||
class RpcChannel(object):
|
||||
|
||||
"""Abstract interface for an RPC channel.
|
||||
|
||||
An RpcChannel represents a communication line to a service which can be used
|
||||
to call that service's methods. The service may be running on another
|
||||
machine. Normally, you should not use an RpcChannel directly, but instead
|
||||
construct a stub {@link Service} wrapping it. Example:
|
||||
|
||||
Example:
|
||||
RpcChannel channel = rpcImpl.Channel("remotehost.example.com:1234")
|
||||
RpcController controller = rpcImpl.Controller()
|
||||
MyService service = MyService_Stub(channel)
|
||||
service.MyMethod(controller, request, callback)
|
||||
"""
|
||||
|
||||
def CallMethod(self, method_descriptor, rpc_controller,
|
||||
request, response_class, done):
|
||||
"""Calls the method identified by the descriptor.
|
||||
|
||||
Call the given method of the remote service. The signature of this
|
||||
procedure looks the same as Service.CallMethod(), but the requirements
|
||||
are less strict in one important way: the request object doesn't have to
|
||||
be of any specific class as long as its descriptor is method.input_type.
|
||||
"""
|
||||
raise NotImplementedError
|
||||
|
||||
+284
-284
@@ -1,284 +1,284 @@
|
||||
# Protocol Buffers - Google's data interchange format
|
||||
# Copyright 2008 Google Inc. All rights reserved.
|
||||
# http://code.google.com/p/protobuf/
|
||||
#
|
||||
# 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.
|
||||
|
||||
"""Contains metaclasses used to create protocol service and service stub
|
||||
classes from ServiceDescriptor objects at runtime.
|
||||
|
||||
The GeneratedServiceType and GeneratedServiceStubType metaclasses are used to
|
||||
inject all useful functionality into the classes output by the protocol
|
||||
compiler at compile-time.
|
||||
"""
|
||||
|
||||
__author__ = 'petar@google.com (Petar Petrov)'
|
||||
|
||||
|
||||
class GeneratedServiceType(type):
|
||||
|
||||
"""Metaclass for service classes created at runtime from ServiceDescriptors.
|
||||
|
||||
Implementations for all methods described in the Service class are added here
|
||||
by this class. We also create properties to allow getting/setting all fields
|
||||
in the protocol message.
|
||||
|
||||
The protocol compiler currently uses this metaclass to create protocol service
|
||||
classes at runtime. Clients can also manually create their own classes at
|
||||
runtime, as in this example:
|
||||
|
||||
mydescriptor = ServiceDescriptor(.....)
|
||||
class MyProtoService(service.Service):
|
||||
__metaclass__ = GeneratedServiceType
|
||||
DESCRIPTOR = mydescriptor
|
||||
myservice_instance = MyProtoService()
|
||||
...
|
||||
"""
|
||||
|
||||
_DESCRIPTOR_KEY = 'DESCRIPTOR'
|
||||
|
||||
def __init__(cls, name, bases, dictionary):
|
||||
"""Creates a message service class.
|
||||
|
||||
Args:
|
||||
name: Name of the class (ignored, but required by the metaclass
|
||||
protocol).
|
||||
bases: Base classes of the class being constructed.
|
||||
dictionary: The class dictionary of the class being constructed.
|
||||
dictionary[_DESCRIPTOR_KEY] must contain a ServiceDescriptor object
|
||||
describing this protocol service type.
|
||||
"""
|
||||
# Don't do anything if this class doesn't have a descriptor. This happens
|
||||
# when a service class is subclassed.
|
||||
if GeneratedServiceType._DESCRIPTOR_KEY not in dictionary:
|
||||
return
|
||||
descriptor = dictionary[GeneratedServiceType._DESCRIPTOR_KEY]
|
||||
service_builder = _ServiceBuilder(descriptor)
|
||||
service_builder.BuildService(cls)
|
||||
|
||||
|
||||
class GeneratedServiceStubType(GeneratedServiceType):
|
||||
|
||||
"""Metaclass for service stubs created at runtime from ServiceDescriptors.
|
||||
|
||||
This class has similar responsibilities as GeneratedServiceType, except that
|
||||
it creates the service stub classes.
|
||||
"""
|
||||
|
||||
_DESCRIPTOR_KEY = 'DESCRIPTOR'
|
||||
|
||||
def __init__(cls, name, bases, dictionary):
|
||||
"""Creates a message service stub class.
|
||||
|
||||
Args:
|
||||
name: Name of the class (ignored, here).
|
||||
bases: Base classes of the class being constructed.
|
||||
dictionary: The class dictionary of the class being constructed.
|
||||
dictionary[_DESCRIPTOR_KEY] must contain a ServiceDescriptor object
|
||||
describing this protocol service type.
|
||||
"""
|
||||
super(GeneratedServiceStubType, cls).__init__(name, bases, dictionary)
|
||||
# Don't do anything if this class doesn't have a descriptor. This happens
|
||||
# when a service stub is subclassed.
|
||||
if GeneratedServiceStubType._DESCRIPTOR_KEY not in dictionary:
|
||||
return
|
||||
descriptor = dictionary[GeneratedServiceStubType._DESCRIPTOR_KEY]
|
||||
service_stub_builder = _ServiceStubBuilder(descriptor)
|
||||
service_stub_builder.BuildServiceStub(cls)
|
||||
|
||||
|
||||
class _ServiceBuilder(object):
|
||||
|
||||
"""This class constructs a protocol service class using a service descriptor.
|
||||
|
||||
Given a service descriptor, this class constructs a class that represents
|
||||
the specified service descriptor. One service builder instance constructs
|
||||
exactly one service class. That means all instances of that class share the
|
||||
same builder.
|
||||
"""
|
||||
|
||||
def __init__(self, service_descriptor):
|
||||
"""Initializes an instance of the service class builder.
|
||||
|
||||
Args:
|
||||
service_descriptor: ServiceDescriptor to use when constructing the
|
||||
service class.
|
||||
"""
|
||||
self.descriptor = service_descriptor
|
||||
|
||||
def BuildService(self, cls):
|
||||
"""Constructs the service class.
|
||||
|
||||
Args:
|
||||
cls: The class that will be constructed.
|
||||
"""
|
||||
|
||||
# CallMethod needs to operate with an instance of the Service class. This
|
||||
# internal wrapper function exists only to be able to pass the service
|
||||
# instance to the method that does the real CallMethod work.
|
||||
def _WrapCallMethod(srvc, method_descriptor,
|
||||
rpc_controller, request, callback):
|
||||
return self._CallMethod(srvc, method_descriptor,
|
||||
rpc_controller, request, callback)
|
||||
self.cls = cls
|
||||
cls.CallMethod = _WrapCallMethod
|
||||
cls.GetDescriptor = staticmethod(lambda: self.descriptor)
|
||||
cls.GetDescriptor.__doc__ = "Returns the service descriptor."
|
||||
cls.GetRequestClass = self._GetRequestClass
|
||||
cls.GetResponseClass = self._GetResponseClass
|
||||
for method in self.descriptor.methods:
|
||||
setattr(cls, method.name, self._GenerateNonImplementedMethod(method))
|
||||
|
||||
def _CallMethod(self, srvc, method_descriptor,
|
||||
rpc_controller, request, callback):
|
||||
"""Calls the method described by a given method descriptor.
|
||||
|
||||
Args:
|
||||
srvc: Instance of the service for which this method is called.
|
||||
method_descriptor: Descriptor that represent the method to call.
|
||||
rpc_controller: RPC controller to use for this method's execution.
|
||||
request: Request protocol message.
|
||||
callback: A callback to invoke after the method has completed.
|
||||
"""
|
||||
if method_descriptor.containing_service != self.descriptor:
|
||||
raise RuntimeError(
|
||||
'CallMethod() given method descriptor for wrong service type.')
|
||||
method = getattr(srvc, method_descriptor.name)
|
||||
return method(rpc_controller, request, callback)
|
||||
|
||||
def _GetRequestClass(self, method_descriptor):
|
||||
"""Returns the class of the request protocol message.
|
||||
|
||||
Args:
|
||||
method_descriptor: Descriptor of the method for which to return the
|
||||
request protocol message class.
|
||||
|
||||
Returns:
|
||||
A class that represents the input protocol message of the specified
|
||||
method.
|
||||
"""
|
||||
if method_descriptor.containing_service != self.descriptor:
|
||||
raise RuntimeError(
|
||||
'GetRequestClass() given method descriptor for wrong service type.')
|
||||
return method_descriptor.input_type._concrete_class
|
||||
|
||||
def _GetResponseClass(self, method_descriptor):
|
||||
"""Returns the class of the response protocol message.
|
||||
|
||||
Args:
|
||||
method_descriptor: Descriptor of the method for which to return the
|
||||
response protocol message class.
|
||||
|
||||
Returns:
|
||||
A class that represents the output protocol message of the specified
|
||||
method.
|
||||
"""
|
||||
if method_descriptor.containing_service != self.descriptor:
|
||||
raise RuntimeError(
|
||||
'GetResponseClass() given method descriptor for wrong service type.')
|
||||
return method_descriptor.output_type._concrete_class
|
||||
|
||||
def _GenerateNonImplementedMethod(self, method):
|
||||
"""Generates and returns a method that can be set for a service methods.
|
||||
|
||||
Args:
|
||||
method: Descriptor of the service method for which a method is to be
|
||||
generated.
|
||||
|
||||
Returns:
|
||||
A method that can be added to the service class.
|
||||
"""
|
||||
return lambda inst, rpc_controller, request, callback: (
|
||||
self._NonImplementedMethod(method.name, rpc_controller, callback))
|
||||
|
||||
def _NonImplementedMethod(self, method_name, rpc_controller, callback):
|
||||
"""The body of all methods in the generated service class.
|
||||
|
||||
Args:
|
||||
method_name: Name of the method being executed.
|
||||
rpc_controller: RPC controller used to execute this method.
|
||||
callback: A callback which will be invoked when the method finishes.
|
||||
"""
|
||||
rpc_controller.SetFailed('Method %s not implemented.' % method_name)
|
||||
callback(None)
|
||||
|
||||
|
||||
class _ServiceStubBuilder(object):
|
||||
|
||||
"""Constructs a protocol service stub class using a service descriptor.
|
||||
|
||||
Given a service descriptor, this class constructs a suitable stub class.
|
||||
A stub is just a type-safe wrapper around an RpcChannel which emulates a
|
||||
local implementation of the service.
|
||||
|
||||
One service stub builder instance constructs exactly one class. It means all
|
||||
instances of that class share the same service stub builder.
|
||||
"""
|
||||
|
||||
def __init__(self, service_descriptor):
|
||||
"""Initializes an instance of the service stub class builder.
|
||||
|
||||
Args:
|
||||
service_descriptor: ServiceDescriptor to use when constructing the
|
||||
stub class.
|
||||
"""
|
||||
self.descriptor = service_descriptor
|
||||
|
||||
def BuildServiceStub(self, cls):
|
||||
"""Constructs the stub class.
|
||||
|
||||
Args:
|
||||
cls: The class that will be constructed.
|
||||
"""
|
||||
|
||||
def _ServiceStubInit(stub, rpc_channel):
|
||||
stub.rpc_channel = rpc_channel
|
||||
self.cls = cls
|
||||
cls.__init__ = _ServiceStubInit
|
||||
for method in self.descriptor.methods:
|
||||
setattr(cls, method.name, self._GenerateStubMethod(method))
|
||||
|
||||
def _GenerateStubMethod(self, method):
|
||||
return (lambda inst, rpc_controller, request, callback=None:
|
||||
self._StubMethod(inst, method, rpc_controller, request, callback))
|
||||
|
||||
def _StubMethod(self, stub, method_descriptor,
|
||||
rpc_controller, request, callback):
|
||||
"""The body of all service methods in the generated stub class.
|
||||
|
||||
Args:
|
||||
stub: Stub instance.
|
||||
method_descriptor: Descriptor of the invoked method.
|
||||
rpc_controller: Rpc controller to execute the method.
|
||||
request: Request protocol message.
|
||||
callback: A callback to execute when the method finishes.
|
||||
Returns:
|
||||
Response message (in case of blocking call).
|
||||
"""
|
||||
return stub.rpc_channel.CallMethod(
|
||||
method_descriptor, rpc_controller, request,
|
||||
method_descriptor.output_type._concrete_class, callback)
|
||||
# Protocol Buffers - Google's data interchange format
|
||||
# Copyright 2008 Google Inc. All rights reserved.
|
||||
# http://code.google.com/p/protobuf/
|
||||
#
|
||||
# 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.
|
||||
|
||||
"""Contains metaclasses used to create protocol service and service stub
|
||||
classes from ServiceDescriptor objects at runtime.
|
||||
|
||||
The GeneratedServiceType and GeneratedServiceStubType metaclasses are used to
|
||||
inject all useful functionality into the classes output by the protocol
|
||||
compiler at compile-time.
|
||||
"""
|
||||
|
||||
__author__ = 'petar@google.com (Petar Petrov)'
|
||||
|
||||
|
||||
class GeneratedServiceType(type):
|
||||
|
||||
"""Metaclass for service classes created at runtime from ServiceDescriptors.
|
||||
|
||||
Implementations for all methods described in the Service class are added here
|
||||
by this class. We also create properties to allow getting/setting all fields
|
||||
in the protocol message.
|
||||
|
||||
The protocol compiler currently uses this metaclass to create protocol service
|
||||
classes at runtime. Clients can also manually create their own classes at
|
||||
runtime, as in this example:
|
||||
|
||||
mydescriptor = ServiceDescriptor(.....)
|
||||
class MyProtoService(service.Service):
|
||||
__metaclass__ = GeneratedServiceType
|
||||
DESCRIPTOR = mydescriptor
|
||||
myservice_instance = MyProtoService()
|
||||
...
|
||||
"""
|
||||
|
||||
_DESCRIPTOR_KEY = 'DESCRIPTOR'
|
||||
|
||||
def __init__(cls, name, bases, dictionary):
|
||||
"""Creates a message service class.
|
||||
|
||||
Args:
|
||||
name: Name of the class (ignored, but required by the metaclass
|
||||
protocol).
|
||||
bases: Base classes of the class being constructed.
|
||||
dictionary: The class dictionary of the class being constructed.
|
||||
dictionary[_DESCRIPTOR_KEY] must contain a ServiceDescriptor object
|
||||
describing this protocol service type.
|
||||
"""
|
||||
# Don't do anything if this class doesn't have a descriptor. This happens
|
||||
# when a service class is subclassed.
|
||||
if GeneratedServiceType._DESCRIPTOR_KEY not in dictionary:
|
||||
return
|
||||
descriptor = dictionary[GeneratedServiceType._DESCRIPTOR_KEY]
|
||||
service_builder = _ServiceBuilder(descriptor)
|
||||
service_builder.BuildService(cls)
|
||||
|
||||
|
||||
class GeneratedServiceStubType(GeneratedServiceType):
|
||||
|
||||
"""Metaclass for service stubs created at runtime from ServiceDescriptors.
|
||||
|
||||
This class has similar responsibilities as GeneratedServiceType, except that
|
||||
it creates the service stub classes.
|
||||
"""
|
||||
|
||||
_DESCRIPTOR_KEY = 'DESCRIPTOR'
|
||||
|
||||
def __init__(cls, name, bases, dictionary):
|
||||
"""Creates a message service stub class.
|
||||
|
||||
Args:
|
||||
name: Name of the class (ignored, here).
|
||||
bases: Base classes of the class being constructed.
|
||||
dictionary: The class dictionary of the class being constructed.
|
||||
dictionary[_DESCRIPTOR_KEY] must contain a ServiceDescriptor object
|
||||
describing this protocol service type.
|
||||
"""
|
||||
super(GeneratedServiceStubType, cls).__init__(name, bases, dictionary)
|
||||
# Don't do anything if this class doesn't have a descriptor. This happens
|
||||
# when a service stub is subclassed.
|
||||
if GeneratedServiceStubType._DESCRIPTOR_KEY not in dictionary:
|
||||
return
|
||||
descriptor = dictionary[GeneratedServiceStubType._DESCRIPTOR_KEY]
|
||||
service_stub_builder = _ServiceStubBuilder(descriptor)
|
||||
service_stub_builder.BuildServiceStub(cls)
|
||||
|
||||
|
||||
class _ServiceBuilder(object):
|
||||
|
||||
"""This class constructs a protocol service class using a service descriptor.
|
||||
|
||||
Given a service descriptor, this class constructs a class that represents
|
||||
the specified service descriptor. One service builder instance constructs
|
||||
exactly one service class. That means all instances of that class share the
|
||||
same builder.
|
||||
"""
|
||||
|
||||
def __init__(self, service_descriptor):
|
||||
"""Initializes an instance of the service class builder.
|
||||
|
||||
Args:
|
||||
service_descriptor: ServiceDescriptor to use when constructing the
|
||||
service class.
|
||||
"""
|
||||
self.descriptor = service_descriptor
|
||||
|
||||
def BuildService(self, cls):
|
||||
"""Constructs the service class.
|
||||
|
||||
Args:
|
||||
cls: The class that will be constructed.
|
||||
"""
|
||||
|
||||
# CallMethod needs to operate with an instance of the Service class. This
|
||||
# internal wrapper function exists only to be able to pass the service
|
||||
# instance to the method that does the real CallMethod work.
|
||||
def _WrapCallMethod(srvc, method_descriptor,
|
||||
rpc_controller, request, callback):
|
||||
return self._CallMethod(srvc, method_descriptor,
|
||||
rpc_controller, request, callback)
|
||||
self.cls = cls
|
||||
cls.CallMethod = _WrapCallMethod
|
||||
cls.GetDescriptor = staticmethod(lambda: self.descriptor)
|
||||
cls.GetDescriptor.__doc__ = "Returns the service descriptor."
|
||||
cls.GetRequestClass = self._GetRequestClass
|
||||
cls.GetResponseClass = self._GetResponseClass
|
||||
for method in self.descriptor.methods:
|
||||
setattr(cls, method.name, self._GenerateNonImplementedMethod(method))
|
||||
|
||||
def _CallMethod(self, srvc, method_descriptor,
|
||||
rpc_controller, request, callback):
|
||||
"""Calls the method described by a given method descriptor.
|
||||
|
||||
Args:
|
||||
srvc: Instance of the service for which this method is called.
|
||||
method_descriptor: Descriptor that represent the method to call.
|
||||
rpc_controller: RPC controller to use for this method's execution.
|
||||
request: Request protocol message.
|
||||
callback: A callback to invoke after the method has completed.
|
||||
"""
|
||||
if method_descriptor.containing_service != self.descriptor:
|
||||
raise RuntimeError(
|
||||
'CallMethod() given method descriptor for wrong service type.')
|
||||
method = getattr(srvc, method_descriptor.name)
|
||||
return method(rpc_controller, request, callback)
|
||||
|
||||
def _GetRequestClass(self, method_descriptor):
|
||||
"""Returns the class of the request protocol message.
|
||||
|
||||
Args:
|
||||
method_descriptor: Descriptor of the method for which to return the
|
||||
request protocol message class.
|
||||
|
||||
Returns:
|
||||
A class that represents the input protocol message of the specified
|
||||
method.
|
||||
"""
|
||||
if method_descriptor.containing_service != self.descriptor:
|
||||
raise RuntimeError(
|
||||
'GetRequestClass() given method descriptor for wrong service type.')
|
||||
return method_descriptor.input_type._concrete_class
|
||||
|
||||
def _GetResponseClass(self, method_descriptor):
|
||||
"""Returns the class of the response protocol message.
|
||||
|
||||
Args:
|
||||
method_descriptor: Descriptor of the method for which to return the
|
||||
response protocol message class.
|
||||
|
||||
Returns:
|
||||
A class that represents the output protocol message of the specified
|
||||
method.
|
||||
"""
|
||||
if method_descriptor.containing_service != self.descriptor:
|
||||
raise RuntimeError(
|
||||
'GetResponseClass() given method descriptor for wrong service type.')
|
||||
return method_descriptor.output_type._concrete_class
|
||||
|
||||
def _GenerateNonImplementedMethod(self, method):
|
||||
"""Generates and returns a method that can be set for a service methods.
|
||||
|
||||
Args:
|
||||
method: Descriptor of the service method for which a method is to be
|
||||
generated.
|
||||
|
||||
Returns:
|
||||
A method that can be added to the service class.
|
||||
"""
|
||||
return lambda inst, rpc_controller, request, callback: (
|
||||
self._NonImplementedMethod(method.name, rpc_controller, callback))
|
||||
|
||||
def _NonImplementedMethod(self, method_name, rpc_controller, callback):
|
||||
"""The body of all methods in the generated service class.
|
||||
|
||||
Args:
|
||||
method_name: Name of the method being executed.
|
||||
rpc_controller: RPC controller used to execute this method.
|
||||
callback: A callback which will be invoked when the method finishes.
|
||||
"""
|
||||
rpc_controller.SetFailed('Method %s not implemented.' % method_name)
|
||||
callback(None)
|
||||
|
||||
|
||||
class _ServiceStubBuilder(object):
|
||||
|
||||
"""Constructs a protocol service stub class using a service descriptor.
|
||||
|
||||
Given a service descriptor, this class constructs a suitable stub class.
|
||||
A stub is just a type-safe wrapper around an RpcChannel which emulates a
|
||||
local implementation of the service.
|
||||
|
||||
One service stub builder instance constructs exactly one class. It means all
|
||||
instances of that class share the same service stub builder.
|
||||
"""
|
||||
|
||||
def __init__(self, service_descriptor):
|
||||
"""Initializes an instance of the service stub class builder.
|
||||
|
||||
Args:
|
||||
service_descriptor: ServiceDescriptor to use when constructing the
|
||||
stub class.
|
||||
"""
|
||||
self.descriptor = service_descriptor
|
||||
|
||||
def BuildServiceStub(self, cls):
|
||||
"""Constructs the stub class.
|
||||
|
||||
Args:
|
||||
cls: The class that will be constructed.
|
||||
"""
|
||||
|
||||
def _ServiceStubInit(stub, rpc_channel):
|
||||
stub.rpc_channel = rpc_channel
|
||||
self.cls = cls
|
||||
cls.__init__ = _ServiceStubInit
|
||||
for method in self.descriptor.methods:
|
||||
setattr(cls, method.name, self._GenerateStubMethod(method))
|
||||
|
||||
def _GenerateStubMethod(self, method):
|
||||
return (lambda inst, rpc_controller, request, callback=None:
|
||||
self._StubMethod(inst, method, rpc_controller, request, callback))
|
||||
|
||||
def _StubMethod(self, stub, method_descriptor,
|
||||
rpc_controller, request, callback):
|
||||
"""The body of all service methods in the generated stub class.
|
||||
|
||||
Args:
|
||||
stub: Stub instance.
|
||||
method_descriptor: Descriptor of the invoked method.
|
||||
rpc_controller: Rpc controller to execute the method.
|
||||
request: Request protocol message.
|
||||
callback: A callback to execute when the method finishes.
|
||||
Returns:
|
||||
Response message (in case of blocking call).
|
||||
"""
|
||||
return stub.rpc_channel.CallMethod(
|
||||
method_descriptor, rpc_controller, request,
|
||||
method_descriptor.output_type._concrete_class, callback)
|
||||
|
||||
+673
-673
File diff suppressed because it is too large
Load Diff
+1401
-1401
File diff suppressed because it is too large
Load Diff
+127
-127
@@ -1,127 +1,127 @@
|
||||
#! /usr/bin/python
|
||||
#
|
||||
# See README for usage instructions.
|
||||
|
||||
# We must use setuptools, not distutils, because we need to use the
|
||||
# namespace_packages option for the "google" package.
|
||||
from ez_setup import use_setuptools
|
||||
use_setuptools()
|
||||
|
||||
from setuptools import setup
|
||||
from distutils.spawn import find_executable
|
||||
import sys
|
||||
import os
|
||||
import subprocess
|
||||
|
||||
maintainer_email = "protobuf@googlegroups.com"
|
||||
|
||||
# Find the Protocol Compiler.
|
||||
if os.path.exists("../src/protoc"):
|
||||
protoc = "../src/protoc"
|
||||
elif os.path.exists("../src/protoc.exe"):
|
||||
protoc = "../src/protoc.exe"
|
||||
else:
|
||||
protoc = find_executable("protoc")
|
||||
|
||||
def generate_proto(source):
|
||||
"""Invokes the Protocol Compiler to generate a _pb2.py from the given
|
||||
.proto file. Does nothing if the output already exists and is newer than
|
||||
the input."""
|
||||
|
||||
output = source.replace(".proto", "_pb2.py").replace("../src/", "")
|
||||
|
||||
if not os.path.exists(source):
|
||||
print "Can't find required file: " + source
|
||||
sys.exit(-1)
|
||||
|
||||
if (not os.path.exists(output) or
|
||||
(os.path.exists(source) and
|
||||
os.path.getmtime(source) > os.path.getmtime(output))):
|
||||
print "Generating %s..." % output
|
||||
|
||||
if protoc == None:
|
||||
sys.stderr.write(
|
||||
"protoc is not installed nor found in ../src. Please compile it "
|
||||
"or install the binary package.\n")
|
||||
sys.exit(-1)
|
||||
|
||||
protoc_command = [ protoc, "-I../src", "-I.", "--python_out=.", source ]
|
||||
if subprocess.call(protoc_command) != 0:
|
||||
sys.exit(-1)
|
||||
|
||||
def MakeTestSuite():
|
||||
# This is apparently needed on some systems to make sure that the tests
|
||||
# work even if a previous version is already installed.
|
||||
if 'google' in sys.modules:
|
||||
del sys.modules['google']
|
||||
|
||||
generate_proto("../src/google/protobuf/unittest.proto")
|
||||
generate_proto("../src/google/protobuf/unittest_import.proto")
|
||||
generate_proto("../src/google/protobuf/unittest_mset.proto")
|
||||
generate_proto("../src/google/protobuf/unittest_no_generic_services.proto")
|
||||
generate_proto("google/protobuf/internal/more_extensions.proto")
|
||||
generate_proto("google/protobuf/internal/more_messages.proto")
|
||||
|
||||
import unittest
|
||||
import google.protobuf.internal.generator_test as generator_test
|
||||
import google.protobuf.internal.descriptor_test as descriptor_test
|
||||
import google.protobuf.internal.reflection_test as reflection_test
|
||||
import google.protobuf.internal.service_reflection_test \
|
||||
as service_reflection_test
|
||||
import google.protobuf.internal.text_format_test as text_format_test
|
||||
import google.protobuf.internal.wire_format_test as wire_format_test
|
||||
|
||||
loader = unittest.defaultTestLoader
|
||||
suite = unittest.TestSuite()
|
||||
for test in [ generator_test,
|
||||
descriptor_test,
|
||||
reflection_test,
|
||||
service_reflection_test,
|
||||
text_format_test,
|
||||
wire_format_test ]:
|
||||
suite.addTest(loader.loadTestsFromModule(test))
|
||||
|
||||
return suite
|
||||
|
||||
if __name__ == '__main__':
|
||||
# TODO(kenton): Integrate this into setuptools somehow?
|
||||
if len(sys.argv) >= 2 and sys.argv[1] == "clean":
|
||||
# Delete generated _pb2.py files and .pyc files in the code tree.
|
||||
for (dirpath, dirnames, filenames) in os.walk("."):
|
||||
for filename in filenames:
|
||||
filepath = os.path.join(dirpath, filename)
|
||||
if filepath.endswith("_pb2.py") or filepath.endswith(".pyc"):
|
||||
os.remove(filepath)
|
||||
else:
|
||||
# Generate necessary .proto file if it doesn't exist.
|
||||
# TODO(kenton): Maybe we should hook this into a distutils command?
|
||||
generate_proto("../src/google/protobuf/descriptor.proto")
|
||||
|
||||
setup(name = 'protobuf',
|
||||
version = '2.3.0',
|
||||
packages = [ 'google' ],
|
||||
namespace_packages = [ 'google' ],
|
||||
test_suite = 'setup.MakeTestSuite',
|
||||
# Must list modules explicitly so that we don't install tests.
|
||||
py_modules = [
|
||||
'google.protobuf.internal.containers',
|
||||
'google.protobuf.internal.decoder',
|
||||
'google.protobuf.internal.encoder',
|
||||
'google.protobuf.internal.message_listener',
|
||||
'google.protobuf.internal.type_checkers',
|
||||
'google.protobuf.internal.wire_format',
|
||||
'google.protobuf.descriptor',
|
||||
'google.protobuf.descriptor_pb2',
|
||||
'google.protobuf.message',
|
||||
'google.protobuf.reflection',
|
||||
'google.protobuf.service',
|
||||
'google.protobuf.service_reflection',
|
||||
'google.protobuf.text_format' ],
|
||||
url = 'http://code.google.com/p/protobuf/',
|
||||
maintainer = maintainer_email,
|
||||
maintainer_email = 'protobuf@googlegroups.com',
|
||||
license = 'New BSD License',
|
||||
description = 'Protocol Buffers',
|
||||
long_description =
|
||||
"Protocol Buffers are Google's data interchange format.",
|
||||
)
|
||||
#! /usr/bin/python
|
||||
#
|
||||
# See README for usage instructions.
|
||||
|
||||
# We must use setuptools, not distutils, because we need to use the
|
||||
# namespace_packages option for the "google" package.
|
||||
from ez_setup import use_setuptools
|
||||
use_setuptools()
|
||||
|
||||
from setuptools import setup
|
||||
from distutils.spawn import find_executable
|
||||
import sys
|
||||
import os
|
||||
import subprocess
|
||||
|
||||
maintainer_email = "protobuf@googlegroups.com"
|
||||
|
||||
# Find the Protocol Compiler.
|
||||
if os.path.exists("../src/protoc"):
|
||||
protoc = "../src/protoc"
|
||||
elif os.path.exists("../src/protoc.exe"):
|
||||
protoc = "../src/protoc.exe"
|
||||
else:
|
||||
protoc = find_executable("protoc")
|
||||
|
||||
def generate_proto(source):
|
||||
"""Invokes the Protocol Compiler to generate a _pb2.py from the given
|
||||
.proto file. Does nothing if the output already exists and is newer than
|
||||
the input."""
|
||||
|
||||
output = source.replace(".proto", "_pb2.py").replace("../src/", "")
|
||||
|
||||
if not os.path.exists(source):
|
||||
print "Can't find required file: " + source
|
||||
sys.exit(-1)
|
||||
|
||||
if (not os.path.exists(output) or
|
||||
(os.path.exists(source) and
|
||||
os.path.getmtime(source) > os.path.getmtime(output))):
|
||||
print "Generating %s..." % output
|
||||
|
||||
if protoc == None:
|
||||
sys.stderr.write(
|
||||
"protoc is not installed nor found in ../src. Please compile it "
|
||||
"or install the binary package.\n")
|
||||
sys.exit(-1)
|
||||
|
||||
protoc_command = [ protoc, "-I../src", "-I.", "--python_out=.", source ]
|
||||
if subprocess.call(protoc_command) != 0:
|
||||
sys.exit(-1)
|
||||
|
||||
def MakeTestSuite():
|
||||
# This is apparently needed on some systems to make sure that the tests
|
||||
# work even if a previous version is already installed.
|
||||
if 'google' in sys.modules:
|
||||
del sys.modules['google']
|
||||
|
||||
generate_proto("../src/google/protobuf/unittest.proto")
|
||||
generate_proto("../src/google/protobuf/unittest_import.proto")
|
||||
generate_proto("../src/google/protobuf/unittest_mset.proto")
|
||||
generate_proto("../src/google/protobuf/unittest_no_generic_services.proto")
|
||||
generate_proto("google/protobuf/internal/more_extensions.proto")
|
||||
generate_proto("google/protobuf/internal/more_messages.proto")
|
||||
|
||||
import unittest
|
||||
import google.protobuf.internal.generator_test as generator_test
|
||||
import google.protobuf.internal.descriptor_test as descriptor_test
|
||||
import google.protobuf.internal.reflection_test as reflection_test
|
||||
import google.protobuf.internal.service_reflection_test \
|
||||
as service_reflection_test
|
||||
import google.protobuf.internal.text_format_test as text_format_test
|
||||
import google.protobuf.internal.wire_format_test as wire_format_test
|
||||
|
||||
loader = unittest.defaultTestLoader
|
||||
suite = unittest.TestSuite()
|
||||
for test in [ generator_test,
|
||||
descriptor_test,
|
||||
reflection_test,
|
||||
service_reflection_test,
|
||||
text_format_test,
|
||||
wire_format_test ]:
|
||||
suite.addTest(loader.loadTestsFromModule(test))
|
||||
|
||||
return suite
|
||||
|
||||
if __name__ == '__main__':
|
||||
# TODO(kenton): Integrate this into setuptools somehow?
|
||||
if len(sys.argv) >= 2 and sys.argv[1] == "clean":
|
||||
# Delete generated _pb2.py files and .pyc files in the code tree.
|
||||
for (dirpath, dirnames, filenames) in os.walk("."):
|
||||
for filename in filenames:
|
||||
filepath = os.path.join(dirpath, filename)
|
||||
if filepath.endswith("_pb2.py") or filepath.endswith(".pyc"):
|
||||
os.remove(filepath)
|
||||
else:
|
||||
# Generate necessary .proto file if it doesn't exist.
|
||||
# TODO(kenton): Maybe we should hook this into a distutils command?
|
||||
generate_proto("../src/google/protobuf/descriptor.proto")
|
||||
|
||||
setup(name = 'protobuf',
|
||||
version = '2.3.0',
|
||||
packages = [ 'google' ],
|
||||
namespace_packages = [ 'google' ],
|
||||
test_suite = 'setup.MakeTestSuite',
|
||||
# Must list modules explicitly so that we don't install tests.
|
||||
py_modules = [
|
||||
'google.protobuf.internal.containers',
|
||||
'google.protobuf.internal.decoder',
|
||||
'google.protobuf.internal.encoder',
|
||||
'google.protobuf.internal.message_listener',
|
||||
'google.protobuf.internal.type_checkers',
|
||||
'google.protobuf.internal.wire_format',
|
||||
'google.protobuf.descriptor',
|
||||
'google.protobuf.descriptor_pb2',
|
||||
'google.protobuf.message',
|
||||
'google.protobuf.reflection',
|
||||
'google.protobuf.service',
|
||||
'google.protobuf.service_reflection',
|
||||
'google.protobuf.text_format' ],
|
||||
url = 'http://code.google.com/p/protobuf/',
|
||||
maintainer = maintainer_email,
|
||||
maintainer_email = 'protobuf@googlegroups.com',
|
||||
license = 'New BSD License',
|
||||
description = 'Protocol Buffers',
|
||||
long_description =
|
||||
"Protocol Buffers are Google's data interchange format.",
|
||||
)
|
||||
|
||||
+140
-140
@@ -1,140 +1,140 @@
|
||||
#!/usr/bin/python2.4
|
||||
#
|
||||
# Copyright 2008 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.
|
||||
|
||||
# This file is used for testing. The original is at:
|
||||
# http://code.google.com/p/pymox/
|
||||
|
||||
class StubOutForTesting:
|
||||
"""Sample Usage:
|
||||
You want os.path.exists() to always return true during testing.
|
||||
|
||||
stubs = StubOutForTesting()
|
||||
stubs.Set(os.path, 'exists', lambda x: 1)
|
||||
...
|
||||
stubs.UnsetAll()
|
||||
|
||||
The above changes os.path.exists into a lambda that returns 1. Once
|
||||
the ... part of the code finishes, the UnsetAll() looks up the old value
|
||||
of os.path.exists and restores it.
|
||||
|
||||
"""
|
||||
def __init__(self):
|
||||
self.cache = []
|
||||
self.stubs = []
|
||||
|
||||
def __del__(self):
|
||||
self.SmartUnsetAll()
|
||||
self.UnsetAll()
|
||||
|
||||
def SmartSet(self, obj, attr_name, new_attr):
|
||||
"""Replace obj.attr_name with new_attr. This method is smart and works
|
||||
at the module, class, and instance level while preserving proper
|
||||
inheritance. It will not stub out C types however unless that has been
|
||||
explicitly allowed by the type.
|
||||
|
||||
This method supports the case where attr_name is a staticmethod or a
|
||||
classmethod of obj.
|
||||
|
||||
Notes:
|
||||
- If obj is an instance, then it is its class that will actually be
|
||||
stubbed. Note that the method Set() does not do that: if obj is
|
||||
an instance, it (and not its class) will be stubbed.
|
||||
- The stubbing is using the builtin getattr and setattr. So, the __get__
|
||||
and __set__ will be called when stubbing (TODO: A better idea would
|
||||
probably be to manipulate obj.__dict__ instead of getattr() and
|
||||
setattr()).
|
||||
|
||||
Raises AttributeError if the attribute cannot be found.
|
||||
"""
|
||||
if (inspect.ismodule(obj) or
|
||||
(not inspect.isclass(obj) and obj.__dict__.has_key(attr_name))):
|
||||
orig_obj = obj
|
||||
orig_attr = getattr(obj, attr_name)
|
||||
|
||||
else:
|
||||
if not inspect.isclass(obj):
|
||||
mro = list(inspect.getmro(obj.__class__))
|
||||
else:
|
||||
mro = list(inspect.getmro(obj))
|
||||
|
||||
mro.reverse()
|
||||
|
||||
orig_attr = None
|
||||
|
||||
for cls in mro:
|
||||
try:
|
||||
orig_obj = cls
|
||||
orig_attr = getattr(obj, attr_name)
|
||||
except AttributeError:
|
||||
continue
|
||||
|
||||
if orig_attr is None:
|
||||
raise AttributeError("Attribute not found.")
|
||||
|
||||
# Calling getattr() on a staticmethod transforms it to a 'normal' function.
|
||||
# We need to ensure that we put it back as a staticmethod.
|
||||
old_attribute = obj.__dict__.get(attr_name)
|
||||
if old_attribute is not None and isinstance(old_attribute, staticmethod):
|
||||
orig_attr = staticmethod(orig_attr)
|
||||
|
||||
self.stubs.append((orig_obj, attr_name, orig_attr))
|
||||
setattr(orig_obj, attr_name, new_attr)
|
||||
|
||||
def SmartUnsetAll(self):
|
||||
"""Reverses all the SmartSet() calls, restoring things to their original
|
||||
definition. Its okay to call SmartUnsetAll() repeatedly, as later calls
|
||||
have no effect if no SmartSet() calls have been made.
|
||||
|
||||
"""
|
||||
self.stubs.reverse()
|
||||
|
||||
for args in self.stubs:
|
||||
setattr(*args)
|
||||
|
||||
self.stubs = []
|
||||
|
||||
def Set(self, parent, child_name, new_child):
|
||||
"""Replace child_name's old definition with new_child, in the context
|
||||
of the given parent. The parent could be a module when the child is a
|
||||
function at module scope. Or the parent could be a class when a class'
|
||||
method is being replaced. The named child is set to new_child, while
|
||||
the prior definition is saved away for later, when UnsetAll() is called.
|
||||
|
||||
This method supports the case where child_name is a staticmethod or a
|
||||
classmethod of parent.
|
||||
"""
|
||||
old_child = getattr(parent, child_name)
|
||||
|
||||
old_attribute = parent.__dict__.get(child_name)
|
||||
if old_attribute is not None and isinstance(old_attribute, staticmethod):
|
||||
old_child = staticmethod(old_child)
|
||||
|
||||
self.cache.append((parent, old_child, child_name))
|
||||
setattr(parent, child_name, new_child)
|
||||
|
||||
def UnsetAll(self):
|
||||
"""Reverses all the Set() calls, restoring things to their original
|
||||
definition. Its okay to call UnsetAll() repeatedly, as later calls have
|
||||
no effect if no Set() calls have been made.
|
||||
|
||||
"""
|
||||
# Undo calls to Set() in reverse order, in case Set() was called on the
|
||||
# same arguments repeatedly (want the original call to be last one undone)
|
||||
self.cache.reverse()
|
||||
|
||||
for (parent, old_child, child_name) in self.cache:
|
||||
setattr(parent, child_name, old_child)
|
||||
self.cache = []
|
||||
#!/usr/bin/python2.4
|
||||
#
|
||||
# Copyright 2008 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.
|
||||
|
||||
# This file is used for testing. The original is at:
|
||||
# http://code.google.com/p/pymox/
|
||||
|
||||
class StubOutForTesting:
|
||||
"""Sample Usage:
|
||||
You want os.path.exists() to always return true during testing.
|
||||
|
||||
stubs = StubOutForTesting()
|
||||
stubs.Set(os.path, 'exists', lambda x: 1)
|
||||
...
|
||||
stubs.UnsetAll()
|
||||
|
||||
The above changes os.path.exists into a lambda that returns 1. Once
|
||||
the ... part of the code finishes, the UnsetAll() looks up the old value
|
||||
of os.path.exists and restores it.
|
||||
|
||||
"""
|
||||
def __init__(self):
|
||||
self.cache = []
|
||||
self.stubs = []
|
||||
|
||||
def __del__(self):
|
||||
self.SmartUnsetAll()
|
||||
self.UnsetAll()
|
||||
|
||||
def SmartSet(self, obj, attr_name, new_attr):
|
||||
"""Replace obj.attr_name with new_attr. This method is smart and works
|
||||
at the module, class, and instance level while preserving proper
|
||||
inheritance. It will not stub out C types however unless that has been
|
||||
explicitly allowed by the type.
|
||||
|
||||
This method supports the case where attr_name is a staticmethod or a
|
||||
classmethod of obj.
|
||||
|
||||
Notes:
|
||||
- If obj is an instance, then it is its class that will actually be
|
||||
stubbed. Note that the method Set() does not do that: if obj is
|
||||
an instance, it (and not its class) will be stubbed.
|
||||
- The stubbing is using the builtin getattr and setattr. So, the __get__
|
||||
and __set__ will be called when stubbing (TODO: A better idea would
|
||||
probably be to manipulate obj.__dict__ instead of getattr() and
|
||||
setattr()).
|
||||
|
||||
Raises AttributeError if the attribute cannot be found.
|
||||
"""
|
||||
if (inspect.ismodule(obj) or
|
||||
(not inspect.isclass(obj) and obj.__dict__.has_key(attr_name))):
|
||||
orig_obj = obj
|
||||
orig_attr = getattr(obj, attr_name)
|
||||
|
||||
else:
|
||||
if not inspect.isclass(obj):
|
||||
mro = list(inspect.getmro(obj.__class__))
|
||||
else:
|
||||
mro = list(inspect.getmro(obj))
|
||||
|
||||
mro.reverse()
|
||||
|
||||
orig_attr = None
|
||||
|
||||
for cls in mro:
|
||||
try:
|
||||
orig_obj = cls
|
||||
orig_attr = getattr(obj, attr_name)
|
||||
except AttributeError:
|
||||
continue
|
||||
|
||||
if orig_attr is None:
|
||||
raise AttributeError("Attribute not found.")
|
||||
|
||||
# Calling getattr() on a staticmethod transforms it to a 'normal' function.
|
||||
# We need to ensure that we put it back as a staticmethod.
|
||||
old_attribute = obj.__dict__.get(attr_name)
|
||||
if old_attribute is not None and isinstance(old_attribute, staticmethod):
|
||||
orig_attr = staticmethod(orig_attr)
|
||||
|
||||
self.stubs.append((orig_obj, attr_name, orig_attr))
|
||||
setattr(orig_obj, attr_name, new_attr)
|
||||
|
||||
def SmartUnsetAll(self):
|
||||
"""Reverses all the SmartSet() calls, restoring things to their original
|
||||
definition. Its okay to call SmartUnsetAll() repeatedly, as later calls
|
||||
have no effect if no SmartSet() calls have been made.
|
||||
|
||||
"""
|
||||
self.stubs.reverse()
|
||||
|
||||
for args in self.stubs:
|
||||
setattr(*args)
|
||||
|
||||
self.stubs = []
|
||||
|
||||
def Set(self, parent, child_name, new_child):
|
||||
"""Replace child_name's old definition with new_child, in the context
|
||||
of the given parent. The parent could be a module when the child is a
|
||||
function at module scope. Or the parent could be a class when a class'
|
||||
method is being replaced. The named child is set to new_child, while
|
||||
the prior definition is saved away for later, when UnsetAll() is called.
|
||||
|
||||
This method supports the case where child_name is a staticmethod or a
|
||||
classmethod of parent.
|
||||
"""
|
||||
old_child = getattr(parent, child_name)
|
||||
|
||||
old_attribute = parent.__dict__.get(child_name)
|
||||
if old_attribute is not None and isinstance(old_attribute, staticmethod):
|
||||
old_child = staticmethod(old_child)
|
||||
|
||||
self.cache.append((parent, old_child, child_name))
|
||||
setattr(parent, child_name, new_child)
|
||||
|
||||
def UnsetAll(self):
|
||||
"""Reverses all the Set() calls, restoring things to their original
|
||||
definition. Its okay to call UnsetAll() repeatedly, as later calls have
|
||||
no effect if no Set() calls have been made.
|
||||
|
||||
"""
|
||||
# Undo calls to Set() in reverse order, in case Set() was called on the
|
||||
# same arguments repeatedly (want the original call to be last one undone)
|
||||
self.cache.reverse()
|
||||
|
||||
for (parent, old_child, child_name) in self.cache:
|
||||
setattr(parent, child_name, old_child)
|
||||
self.cache = []
|
||||
|
||||
+132
-132
@@ -1,132 +1,132 @@
|
||||
// Protocol Buffers - Google's data interchange format
|
||||
// Copyright 2008 Google Inc. All rights reserved.
|
||||
// http://code.google.com/p/protobuf/
|
||||
//
|
||||
// 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: kenton@google.com (Kenton Varda)
|
||||
// Based on original Protocol Buffers design by
|
||||
// Sanjay Ghemawat, Jeff Dean, and others.
|
||||
//
|
||||
// Defines the abstract interface implemented by each of the language-specific
|
||||
// code generators.
|
||||
|
||||
#ifndef GOOGLE_PROTOBUF_COMPILER_CODE_GENERATOR_H__
|
||||
#define GOOGLE_PROTOBUF_COMPILER_CODE_GENERATOR_H__
|
||||
|
||||
#include <google/protobuf/stubs/common.h>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
#include <utility>
|
||||
|
||||
namespace google {
|
||||
namespace protobuf {
|
||||
|
||||
namespace io { class ZeroCopyOutputStream; }
|
||||
class FileDescriptor;
|
||||
|
||||
namespace compiler {
|
||||
|
||||
// Defined in this file.
|
||||
class CodeGenerator;
|
||||
class OutputDirectory;
|
||||
|
||||
// The abstract interface to a class which generates code implementing a
|
||||
// particular proto file in a particular language. A number of these may
|
||||
// be registered with CommandLineInterface to support various languages.
|
||||
class LIBPROTOC_EXPORT CodeGenerator {
|
||||
public:
|
||||
inline CodeGenerator() {}
|
||||
virtual ~CodeGenerator();
|
||||
|
||||
// Generates code for the given proto file, generating one or more files in
|
||||
// the given output directory.
|
||||
//
|
||||
// A parameter to be passed to the generator can be specified on the
|
||||
// command line. This is intended to be used by Java and similar languages
|
||||
// to specify which specific class from the proto file is to be generated,
|
||||
// though it could have other uses as well. It is empty if no parameter was
|
||||
// given.
|
||||
//
|
||||
// Returns true if successful. Otherwise, sets *error to a description of
|
||||
// the problem (e.g. "invalid parameter") and returns false.
|
||||
virtual bool Generate(const FileDescriptor* file,
|
||||
const string& parameter,
|
||||
OutputDirectory* output_directory,
|
||||
string* error) const = 0;
|
||||
|
||||
private:
|
||||
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(CodeGenerator);
|
||||
};
|
||||
|
||||
// CodeGenerators generate one or more files in a given directory. This
|
||||
// abstract interface represents the directory to which the CodeGenerator is
|
||||
// to write.
|
||||
class LIBPROTOC_EXPORT OutputDirectory {
|
||||
public:
|
||||
inline OutputDirectory() {}
|
||||
virtual ~OutputDirectory();
|
||||
|
||||
// Opens the given file, truncating it if it exists, and returns a
|
||||
// ZeroCopyOutputStream that writes to the file. The caller takes ownership
|
||||
// of the returned object. This method never fails (a dummy stream will be
|
||||
// returned instead).
|
||||
//
|
||||
// The filename given should be relative to the root of the source tree.
|
||||
// E.g. the C++ generator, when generating code for "foo/bar.proto", will
|
||||
// generate the files "foo/bar.pb.h" and "foo/bar.pb.cc"; note that
|
||||
// "foo/" is included in these filenames. The filename is not allowed to
|
||||
// contain "." or ".." components.
|
||||
virtual io::ZeroCopyOutputStream* Open(const string& filename) = 0;
|
||||
|
||||
// Creates a ZeroCopyOutputStream which will insert code into the given file
|
||||
// at the given insertion point. See plugin.proto (plugin.pb.h) for more
|
||||
// information on insertion points. The default implementation
|
||||
// assert-fails -- it exists only for backwards-compatibility.
|
||||
//
|
||||
// WARNING: This feature is currently EXPERIMENTAL and is subject to change.
|
||||
virtual io::ZeroCopyOutputStream* OpenForInsert(
|
||||
const string& filename, const string& insertion_point);
|
||||
|
||||
private:
|
||||
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(OutputDirectory);
|
||||
};
|
||||
|
||||
// Several code generators treat the parameter argument as holding a
|
||||
// list of options separated by commas. This helper function parses
|
||||
// a set of comma-delimited name/value pairs: e.g.,
|
||||
// "foo=bar,baz,qux=corge"
|
||||
// parses to the pairs:
|
||||
// ("foo", "bar"), ("baz", ""), ("qux", "corge")
|
||||
extern void ParseGeneratorParameter(const string&,
|
||||
vector<pair<string, string> >*);
|
||||
|
||||
} // namespace compiler
|
||||
} // namespace protobuf
|
||||
|
||||
} // namespace google
|
||||
#endif // GOOGLE_PROTOBUF_COMPILER_CODE_GENERATOR_H__
|
||||
// Protocol Buffers - Google's data interchange format
|
||||
// Copyright 2008 Google Inc. All rights reserved.
|
||||
// http://code.google.com/p/protobuf/
|
||||
//
|
||||
// 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: kenton@google.com (Kenton Varda)
|
||||
// Based on original Protocol Buffers design by
|
||||
// Sanjay Ghemawat, Jeff Dean, and others.
|
||||
//
|
||||
// Defines the abstract interface implemented by each of the language-specific
|
||||
// code generators.
|
||||
|
||||
#ifndef GOOGLE_PROTOBUF_COMPILER_CODE_GENERATOR_H__
|
||||
#define GOOGLE_PROTOBUF_COMPILER_CODE_GENERATOR_H__
|
||||
|
||||
#include <google/protobuf/stubs/common.h>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
#include <utility>
|
||||
|
||||
namespace google {
|
||||
namespace protobuf {
|
||||
|
||||
namespace io { class ZeroCopyOutputStream; }
|
||||
class FileDescriptor;
|
||||
|
||||
namespace compiler {
|
||||
|
||||
// Defined in this file.
|
||||
class CodeGenerator;
|
||||
class OutputDirectory;
|
||||
|
||||
// The abstract interface to a class which generates code implementing a
|
||||
// particular proto file in a particular language. A number of these may
|
||||
// be registered with CommandLineInterface to support various languages.
|
||||
class LIBPROTOC_EXPORT CodeGenerator {
|
||||
public:
|
||||
inline CodeGenerator() {}
|
||||
virtual ~CodeGenerator();
|
||||
|
||||
// Generates code for the given proto file, generating one or more files in
|
||||
// the given output directory.
|
||||
//
|
||||
// A parameter to be passed to the generator can be specified on the
|
||||
// command line. This is intended to be used by Java and similar languages
|
||||
// to specify which specific class from the proto file is to be generated,
|
||||
// though it could have other uses as well. It is empty if no parameter was
|
||||
// given.
|
||||
//
|
||||
// Returns true if successful. Otherwise, sets *error to a description of
|
||||
// the problem (e.g. "invalid parameter") and returns false.
|
||||
virtual bool Generate(const FileDescriptor* file,
|
||||
const string& parameter,
|
||||
OutputDirectory* output_directory,
|
||||
string* error) const = 0;
|
||||
|
||||
private:
|
||||
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(CodeGenerator);
|
||||
};
|
||||
|
||||
// CodeGenerators generate one or more files in a given directory. This
|
||||
// abstract interface represents the directory to which the CodeGenerator is
|
||||
// to write.
|
||||
class LIBPROTOC_EXPORT OutputDirectory {
|
||||
public:
|
||||
inline OutputDirectory() {}
|
||||
virtual ~OutputDirectory();
|
||||
|
||||
// Opens the given file, truncating it if it exists, and returns a
|
||||
// ZeroCopyOutputStream that writes to the file. The caller takes ownership
|
||||
// of the returned object. This method never fails (a dummy stream will be
|
||||
// returned instead).
|
||||
//
|
||||
// The filename given should be relative to the root of the source tree.
|
||||
// E.g. the C++ generator, when generating code for "foo/bar.proto", will
|
||||
// generate the files "foo/bar.pb.h" and "foo/bar.pb.cc"; note that
|
||||
// "foo/" is included in these filenames. The filename is not allowed to
|
||||
// contain "." or ".." components.
|
||||
virtual io::ZeroCopyOutputStream* Open(const string& filename) = 0;
|
||||
|
||||
// Creates a ZeroCopyOutputStream which will insert code into the given file
|
||||
// at the given insertion point. See plugin.proto (plugin.pb.h) for more
|
||||
// information on insertion points. The default implementation
|
||||
// assert-fails -- it exists only for backwards-compatibility.
|
||||
//
|
||||
// WARNING: This feature is currently EXPERIMENTAL and is subject to change.
|
||||
virtual io::ZeroCopyOutputStream* OpenForInsert(
|
||||
const string& filename, const string& insertion_point);
|
||||
|
||||
private:
|
||||
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(OutputDirectory);
|
||||
};
|
||||
|
||||
// Several code generators treat the parameter argument as holding a
|
||||
// list of options separated by commas. This helper function parses
|
||||
// a set of comma-delimited name/value pairs: e.g.,
|
||||
// "foo=bar,baz,qux=corge"
|
||||
// parses to the pairs:
|
||||
// ("foo", "bar"), ("baz", ""), ("qux", "corge")
|
||||
extern void ParseGeneratorParameter(const string&,
|
||||
vector<pair<string, string> >*);
|
||||
|
||||
} // namespace compiler
|
||||
} // namespace protobuf
|
||||
|
||||
} // namespace google
|
||||
#endif // GOOGLE_PROTOBUF_COMPILER_CODE_GENERATOR_H__
|
||||
|
||||
+318
-318
@@ -1,318 +1,318 @@
|
||||
// Protocol Buffers - Google's data interchange format
|
||||
// Copyright 2008 Google Inc. All rights reserved.
|
||||
// http://code.google.com/p/protobuf/
|
||||
//
|
||||
// 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: kenton@google.com (Kenton Varda)
|
||||
// Based on original Protocol Buffers design by
|
||||
// Sanjay Ghemawat, Jeff Dean, and others.
|
||||
//
|
||||
// Implements the Protocol Compiler front-end such that it may be reused by
|
||||
// custom compilers written to support other languages.
|
||||
|
||||
#ifndef GOOGLE_PROTOBUF_COMPILER_COMMAND_LINE_INTERFACE_H__
|
||||
#define GOOGLE_PROTOBUF_COMPILER_COMMAND_LINE_INTERFACE_H__
|
||||
|
||||
#include <google/protobuf/stubs/common.h>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
#include <map>
|
||||
#include <set>
|
||||
#include <utility>
|
||||
|
||||
namespace google {
|
||||
namespace protobuf {
|
||||
|
||||
class FileDescriptor; // descriptor.h
|
||||
class DescriptorPool; // descriptor.h
|
||||
class FileDescriptorProto; // descriptor.pb.h
|
||||
template<typename T> class RepeatedPtrField; // repeated_field.h
|
||||
|
||||
namespace compiler {
|
||||
|
||||
class CodeGenerator; // code_generator.h
|
||||
class OutputDirectory; // code_generator.h
|
||||
class DiskSourceTree; // importer.h
|
||||
|
||||
// This class implements the command-line interface to the protocol compiler.
|
||||
// It is designed to make it very easy to create a custom protocol compiler
|
||||
// supporting the languages of your choice. For example, if you wanted to
|
||||
// create a custom protocol compiler binary which includes both the regular
|
||||
// C++ support plus support for your own custom output "Foo", you would
|
||||
// write a class "FooGenerator" which implements the CodeGenerator interface,
|
||||
// then write a main() procedure like this:
|
||||
//
|
||||
// int main(int argc, char* argv[]) {
|
||||
// google::protobuf::compiler::CommandLineInterface cli;
|
||||
//
|
||||
// // Support generation of C++ source and headers.
|
||||
// google::protobuf::compiler::cpp::CppGenerator cpp_generator;
|
||||
// cli.RegisterGenerator("--cpp_out", &cpp_generator,
|
||||
// "Generate C++ source and header.");
|
||||
//
|
||||
// // Support generation of Foo code.
|
||||
// FooGenerator foo_generator;
|
||||
// cli.RegisterGenerator("--foo_out", &foo_generator,
|
||||
// "Generate Foo file.");
|
||||
//
|
||||
// return cli.Run(argc, argv);
|
||||
// }
|
||||
//
|
||||
// The compiler is invoked with syntax like:
|
||||
// protoc --cpp_out=outdir --foo_out=outdir --proto_path=src src/foo.proto
|
||||
//
|
||||
// For a full description of the command-line syntax, invoke it with --help.
|
||||
class LIBPROTOC_EXPORT CommandLineInterface {
|
||||
public:
|
||||
CommandLineInterface();
|
||||
~CommandLineInterface();
|
||||
|
||||
// Register a code generator for a language.
|
||||
//
|
||||
// Parameters:
|
||||
// * flag_name: The command-line flag used to specify an output file of
|
||||
// this type. The name must start with a '-'. If the name is longer
|
||||
// than one letter, it must start with two '-'s.
|
||||
// * generator: The CodeGenerator which will be called to generate files
|
||||
// of this type.
|
||||
// * help_text: Text describing this flag in the --help output.
|
||||
//
|
||||
// Some generators accept extra parameters. You can specify this parameter
|
||||
// on the command-line by placing it before the output directory, separated
|
||||
// by a colon:
|
||||
// protoc --foo_out=enable_bar:outdir
|
||||
// The text before the colon is passed to CodeGenerator::Generate() as the
|
||||
// "parameter".
|
||||
void RegisterGenerator(const string& flag_name,
|
||||
CodeGenerator* generator,
|
||||
const string& help_text);
|
||||
|
||||
// Enables "plugins". In this mode, if a command-line flag ends with "_out"
|
||||
// but does not match any registered generator, the compiler will attempt to
|
||||
// find a "plugin" to implement the generator. Plugins are just executables.
|
||||
// They should live somewhere in the PATH.
|
||||
//
|
||||
// The compiler determines the executable name to search for by concatenating
|
||||
// exe_name_prefix with the unrecognized flag name, removing "_out". So, for
|
||||
// example, if exe_name_prefix is "protoc-" and you pass the flag --foo_out,
|
||||
// the compiler will try to run the program "protoc-foo".
|
||||
//
|
||||
// The plugin program should implement the following usage:
|
||||
// plugin [--out=OUTDIR] [--parameter=PARAMETER] PROTO_FILES < DESCRIPTORS
|
||||
// --out indicates the output directory (as passed to the --foo_out
|
||||
// parameter); if omitted, the current directory should be used. --parameter
|
||||
// gives the generator parameter, if any was provided. The PROTO_FILES list
|
||||
// the .proto files which were given on the compiler command-line; these are
|
||||
// the files for which the plugin is expected to generate output code.
|
||||
// Finally, DESCRIPTORS is an encoded FileDescriptorSet (as defined in
|
||||
// descriptor.proto). This is piped to the plugin's stdin. The set will
|
||||
// include descriptors for all the files listed in PROTO_FILES as well as
|
||||
// all files that they import. The plugin MUST NOT attempt to read the
|
||||
// PROTO_FILES directly -- it must use the FileDescriptorSet.
|
||||
//
|
||||
// The plugin should generate whatever files are necessary, as code generators
|
||||
// normally do. It should write the names of all files it generates to
|
||||
// stdout. The names should be relative to the output directory, NOT absolute
|
||||
// names or relative to the current directory. If any errors occur, error
|
||||
// messages should be written to stderr. If an error is fatal, the plugin
|
||||
// should exit with a non-zero exit code.
|
||||
void AllowPlugins(const string& exe_name_prefix);
|
||||
|
||||
// Run the Protocol Compiler with the given command-line parameters.
|
||||
// Returns the error code which should be returned by main().
|
||||
//
|
||||
// It may not be safe to call Run() in a multi-threaded environment because
|
||||
// it calls strerror(). I'm not sure why you'd want to do this anyway.
|
||||
int Run(int argc, const char* const argv[]);
|
||||
|
||||
// Call SetInputsAreCwdRelative(true) if the input files given on the command
|
||||
// line should be interpreted relative to the proto import path specified
|
||||
// using --proto_path or -I flags. Otherwise, input file names will be
|
||||
// interpreted relative to the current working directory (or as absolute
|
||||
// paths if they start with '/'), though they must still reside inside
|
||||
// a directory given by --proto_path or the compiler will fail. The latter
|
||||
// mode is generally more intuitive and easier to use, especially e.g. when
|
||||
// defining implicit rules in Makefiles.
|
||||
void SetInputsAreProtoPathRelative(bool enable) {
|
||||
inputs_are_proto_path_relative_ = enable;
|
||||
}
|
||||
|
||||
// Provides some text which will be printed when the --version flag is
|
||||
// used. The version of libprotoc will also be printed on the next line
|
||||
// after this text.
|
||||
void SetVersionInfo(const string& text) {
|
||||
version_info_ = text;
|
||||
}
|
||||
|
||||
|
||||
private:
|
||||
// -----------------------------------------------------------------
|
||||
|
||||
class ErrorPrinter;
|
||||
class MemoryOutputDirectory;
|
||||
class MemoryOutputStream;
|
||||
|
||||
// Clear state from previous Run().
|
||||
void Clear();
|
||||
|
||||
// Remaps each file in input_files_ so that it is relative to one of the
|
||||
// directories in proto_path_. Returns false if an error occurred. This
|
||||
// is only used if inputs_are_proto_path_relative_ is false.
|
||||
bool MakeInputsBeProtoPathRelative(
|
||||
DiskSourceTree* source_tree);
|
||||
|
||||
// Parse all command-line arguments.
|
||||
bool ParseArguments(int argc, const char* const argv[]);
|
||||
|
||||
// Parses a command-line argument into a name/value pair. Returns
|
||||
// true if the next argument in the argv should be used as the value,
|
||||
// false otherwise.
|
||||
//
|
||||
// Exmaples:
|
||||
// "-Isrc/protos" ->
|
||||
// name = "-I", value = "src/protos"
|
||||
// "--cpp_out=src/foo.pb2.cc" ->
|
||||
// name = "--cpp_out", value = "src/foo.pb2.cc"
|
||||
// "foo.proto" ->
|
||||
// name = "", value = "foo.proto"
|
||||
bool ParseArgument(const char* arg, string* name, string* value);
|
||||
|
||||
// Interprets arguments parsed with ParseArgument.
|
||||
bool InterpretArgument(const string& name, const string& value);
|
||||
|
||||
// Print the --help text to stderr.
|
||||
void PrintHelpText();
|
||||
|
||||
// Generate the given output file from the given input.
|
||||
struct OutputDirective; // see below
|
||||
bool GenerateOutput(const vector<const FileDescriptor*>& parsed_files,
|
||||
const OutputDirective& output_directive,
|
||||
OutputDirectory* output_directory);
|
||||
bool GeneratePluginOutput(const vector<const FileDescriptor*>& parsed_files,
|
||||
const string& plugin_name,
|
||||
const string& parameter,
|
||||
OutputDirectory* output_directory,
|
||||
string* error);
|
||||
|
||||
// Implements --encode and --decode.
|
||||
bool EncodeOrDecode(const DescriptorPool* pool);
|
||||
|
||||
// Implements the --descriptor_set_out option.
|
||||
bool WriteDescriptorSet(const vector<const FileDescriptor*> parsed_files);
|
||||
|
||||
// Get all transitive dependencies of the given file (including the file
|
||||
// itself), adding them to the given list of FileDescriptorProtos. The
|
||||
// protos will be ordered such that every file is listed before any file that
|
||||
// depends on it, so that you can call DescriptorPool::BuildFile() on them
|
||||
// in order. Any files in *already_seen will not be added, and each file
|
||||
// added will be inserted into *already_seen.
|
||||
static void GetTransitiveDependencies(
|
||||
const FileDescriptor* file,
|
||||
set<const FileDescriptor*>* already_seen,
|
||||
RepeatedPtrField<FileDescriptorProto>* output);
|
||||
|
||||
// -----------------------------------------------------------------
|
||||
|
||||
// The name of the executable as invoked (i.e. argv[0]).
|
||||
string executable_name_;
|
||||
|
||||
// Version info set with SetVersionInfo().
|
||||
string version_info_;
|
||||
|
||||
// Map from flag names to registered generators.
|
||||
struct GeneratorInfo {
|
||||
CodeGenerator* generator;
|
||||
string help_text;
|
||||
};
|
||||
typedef map<string, GeneratorInfo> GeneratorMap;
|
||||
GeneratorMap generators_;
|
||||
|
||||
// See AllowPlugins(). If this is empty, plugins aren't allowed.
|
||||
string plugin_prefix_;
|
||||
|
||||
// Maps specific plugin names to files. When executing a plugin, this map
|
||||
// is searched first to find the plugin executable. If not found here, the
|
||||
// PATH (or other OS-specific search strategy) is searched.
|
||||
map<string, string> plugins_;
|
||||
|
||||
// Stuff parsed from command line.
|
||||
enum Mode {
|
||||
MODE_COMPILE, // Normal mode: parse .proto files and compile them.
|
||||
MODE_ENCODE, // --encode: read text from stdin, write binary to stdout.
|
||||
MODE_DECODE // --decode: read binary from stdin, write text to stdout.
|
||||
};
|
||||
|
||||
Mode mode_;
|
||||
|
||||
enum ErrorFormat {
|
||||
ERROR_FORMAT_GCC, // GCC error output format (default).
|
||||
ERROR_FORMAT_MSVS // Visual Studio output (--error_format=msvs).
|
||||
};
|
||||
|
||||
ErrorFormat error_format_;
|
||||
|
||||
vector<pair<string, string> > proto_path_; // Search path for proto files.
|
||||
vector<string> input_files_; // Names of the input proto files.
|
||||
|
||||
// output_directives_ lists all the files we are supposed to output and what
|
||||
// generator to use for each.
|
||||
struct OutputDirective {
|
||||
string name; // E.g. "--foo_out"
|
||||
CodeGenerator* generator; // NULL for plugins
|
||||
string parameter;
|
||||
string output_location;
|
||||
};
|
||||
vector<OutputDirective> output_directives_;
|
||||
|
||||
// When using --encode or --decode, this names the type we are encoding or
|
||||
// decoding. (Empty string indicates --decode_raw.)
|
||||
string codec_type_;
|
||||
|
||||
// If --descriptor_set_out was given, this is the filename to which the
|
||||
// FileDescriptorSet should be written. Otherwise, empty.
|
||||
string descriptor_set_name_;
|
||||
|
||||
// True if --include_imports was given, meaning that we should
|
||||
// write all transitive dependencies to the DescriptorSet. Otherwise, only
|
||||
// the .proto files listed on the command-line are added.
|
||||
bool imports_in_descriptor_set_;
|
||||
|
||||
// Was the --disallow_services flag used?
|
||||
bool disallow_services_;
|
||||
|
||||
// See SetInputsAreProtoPathRelative().
|
||||
bool inputs_are_proto_path_relative_;
|
||||
|
||||
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(CommandLineInterface);
|
||||
};
|
||||
|
||||
} // namespace compiler
|
||||
} // namespace protobuf
|
||||
|
||||
} // namespace google
|
||||
#endif // GOOGLE_PROTOBUF_COMPILER_COMMAND_LINE_INTERFACE_H__
|
||||
// Protocol Buffers - Google's data interchange format
|
||||
// Copyright 2008 Google Inc. All rights reserved.
|
||||
// http://code.google.com/p/protobuf/
|
||||
//
|
||||
// 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: kenton@google.com (Kenton Varda)
|
||||
// Based on original Protocol Buffers design by
|
||||
// Sanjay Ghemawat, Jeff Dean, and others.
|
||||
//
|
||||
// Implements the Protocol Compiler front-end such that it may be reused by
|
||||
// custom compilers written to support other languages.
|
||||
|
||||
#ifndef GOOGLE_PROTOBUF_COMPILER_COMMAND_LINE_INTERFACE_H__
|
||||
#define GOOGLE_PROTOBUF_COMPILER_COMMAND_LINE_INTERFACE_H__
|
||||
|
||||
#include <google/protobuf/stubs/common.h>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
#include <map>
|
||||
#include <set>
|
||||
#include <utility>
|
||||
|
||||
namespace google {
|
||||
namespace protobuf {
|
||||
|
||||
class FileDescriptor; // descriptor.h
|
||||
class DescriptorPool; // descriptor.h
|
||||
class FileDescriptorProto; // descriptor.pb.h
|
||||
template<typename T> class RepeatedPtrField; // repeated_field.h
|
||||
|
||||
namespace compiler {
|
||||
|
||||
class CodeGenerator; // code_generator.h
|
||||
class OutputDirectory; // code_generator.h
|
||||
class DiskSourceTree; // importer.h
|
||||
|
||||
// This class implements the command-line interface to the protocol compiler.
|
||||
// It is designed to make it very easy to create a custom protocol compiler
|
||||
// supporting the languages of your choice. For example, if you wanted to
|
||||
// create a custom protocol compiler binary which includes both the regular
|
||||
// C++ support plus support for your own custom output "Foo", you would
|
||||
// write a class "FooGenerator" which implements the CodeGenerator interface,
|
||||
// then write a main() procedure like this:
|
||||
//
|
||||
// int main(int argc, char* argv[]) {
|
||||
// google::protobuf::compiler::CommandLineInterface cli;
|
||||
//
|
||||
// // Support generation of C++ source and headers.
|
||||
// google::protobuf::compiler::cpp::CppGenerator cpp_generator;
|
||||
// cli.RegisterGenerator("--cpp_out", &cpp_generator,
|
||||
// "Generate C++ source and header.");
|
||||
//
|
||||
// // Support generation of Foo code.
|
||||
// FooGenerator foo_generator;
|
||||
// cli.RegisterGenerator("--foo_out", &foo_generator,
|
||||
// "Generate Foo file.");
|
||||
//
|
||||
// return cli.Run(argc, argv);
|
||||
// }
|
||||
//
|
||||
// The compiler is invoked with syntax like:
|
||||
// protoc --cpp_out=outdir --foo_out=outdir --proto_path=src src/foo.proto
|
||||
//
|
||||
// For a full description of the command-line syntax, invoke it with --help.
|
||||
class LIBPROTOC_EXPORT CommandLineInterface {
|
||||
public:
|
||||
CommandLineInterface();
|
||||
~CommandLineInterface();
|
||||
|
||||
// Register a code generator for a language.
|
||||
//
|
||||
// Parameters:
|
||||
// * flag_name: The command-line flag used to specify an output file of
|
||||
// this type. The name must start with a '-'. If the name is longer
|
||||
// than one letter, it must start with two '-'s.
|
||||
// * generator: The CodeGenerator which will be called to generate files
|
||||
// of this type.
|
||||
// * help_text: Text describing this flag in the --help output.
|
||||
//
|
||||
// Some generators accept extra parameters. You can specify this parameter
|
||||
// on the command-line by placing it before the output directory, separated
|
||||
// by a colon:
|
||||
// protoc --foo_out=enable_bar:outdir
|
||||
// The text before the colon is passed to CodeGenerator::Generate() as the
|
||||
// "parameter".
|
||||
void RegisterGenerator(const string& flag_name,
|
||||
CodeGenerator* generator,
|
||||
const string& help_text);
|
||||
|
||||
// Enables "plugins". In this mode, if a command-line flag ends with "_out"
|
||||
// but does not match any registered generator, the compiler will attempt to
|
||||
// find a "plugin" to implement the generator. Plugins are just executables.
|
||||
// They should live somewhere in the PATH.
|
||||
//
|
||||
// The compiler determines the executable name to search for by concatenating
|
||||
// exe_name_prefix with the unrecognized flag name, removing "_out". So, for
|
||||
// example, if exe_name_prefix is "protoc-" and you pass the flag --foo_out,
|
||||
// the compiler will try to run the program "protoc-foo".
|
||||
//
|
||||
// The plugin program should implement the following usage:
|
||||
// plugin [--out=OUTDIR] [--parameter=PARAMETER] PROTO_FILES < DESCRIPTORS
|
||||
// --out indicates the output directory (as passed to the --foo_out
|
||||
// parameter); if omitted, the current directory should be used. --parameter
|
||||
// gives the generator parameter, if any was provided. The PROTO_FILES list
|
||||
// the .proto files which were given on the compiler command-line; these are
|
||||
// the files for which the plugin is expected to generate output code.
|
||||
// Finally, DESCRIPTORS is an encoded FileDescriptorSet (as defined in
|
||||
// descriptor.proto). This is piped to the plugin's stdin. The set will
|
||||
// include descriptors for all the files listed in PROTO_FILES as well as
|
||||
// all files that they import. The plugin MUST NOT attempt to read the
|
||||
// PROTO_FILES directly -- it must use the FileDescriptorSet.
|
||||
//
|
||||
// The plugin should generate whatever files are necessary, as code generators
|
||||
// normally do. It should write the names of all files it generates to
|
||||
// stdout. The names should be relative to the output directory, NOT absolute
|
||||
// names or relative to the current directory. If any errors occur, error
|
||||
// messages should be written to stderr. If an error is fatal, the plugin
|
||||
// should exit with a non-zero exit code.
|
||||
void AllowPlugins(const string& exe_name_prefix);
|
||||
|
||||
// Run the Protocol Compiler with the given command-line parameters.
|
||||
// Returns the error code which should be returned by main().
|
||||
//
|
||||
// It may not be safe to call Run() in a multi-threaded environment because
|
||||
// it calls strerror(). I'm not sure why you'd want to do this anyway.
|
||||
int Run(int argc, const char* const argv[]);
|
||||
|
||||
// Call SetInputsAreCwdRelative(true) if the input files given on the command
|
||||
// line should be interpreted relative to the proto import path specified
|
||||
// using --proto_path or -I flags. Otherwise, input file names will be
|
||||
// interpreted relative to the current working directory (or as absolute
|
||||
// paths if they start with '/'), though they must still reside inside
|
||||
// a directory given by --proto_path or the compiler will fail. The latter
|
||||
// mode is generally more intuitive and easier to use, especially e.g. when
|
||||
// defining implicit rules in Makefiles.
|
||||
void SetInputsAreProtoPathRelative(bool enable) {
|
||||
inputs_are_proto_path_relative_ = enable;
|
||||
}
|
||||
|
||||
// Provides some text which will be printed when the --version flag is
|
||||
// used. The version of libprotoc will also be printed on the next line
|
||||
// after this text.
|
||||
void SetVersionInfo(const string& text) {
|
||||
version_info_ = text;
|
||||
}
|
||||
|
||||
|
||||
private:
|
||||
// -----------------------------------------------------------------
|
||||
|
||||
class ErrorPrinter;
|
||||
class MemoryOutputDirectory;
|
||||
class MemoryOutputStream;
|
||||
|
||||
// Clear state from previous Run().
|
||||
void Clear();
|
||||
|
||||
// Remaps each file in input_files_ so that it is relative to one of the
|
||||
// directories in proto_path_. Returns false if an error occurred. This
|
||||
// is only used if inputs_are_proto_path_relative_ is false.
|
||||
bool MakeInputsBeProtoPathRelative(
|
||||
DiskSourceTree* source_tree);
|
||||
|
||||
// Parse all command-line arguments.
|
||||
bool ParseArguments(int argc, const char* const argv[]);
|
||||
|
||||
// Parses a command-line argument into a name/value pair. Returns
|
||||
// true if the next argument in the argv should be used as the value,
|
||||
// false otherwise.
|
||||
//
|
||||
// Exmaples:
|
||||
// "-Isrc/protos" ->
|
||||
// name = "-I", value = "src/protos"
|
||||
// "--cpp_out=src/foo.pb2.cc" ->
|
||||
// name = "--cpp_out", value = "src/foo.pb2.cc"
|
||||
// "foo.proto" ->
|
||||
// name = "", value = "foo.proto"
|
||||
bool ParseArgument(const char* arg, string* name, string* value);
|
||||
|
||||
// Interprets arguments parsed with ParseArgument.
|
||||
bool InterpretArgument(const string& name, const string& value);
|
||||
|
||||
// Print the --help text to stderr.
|
||||
void PrintHelpText();
|
||||
|
||||
// Generate the given output file from the given input.
|
||||
struct OutputDirective; // see below
|
||||
bool GenerateOutput(const vector<const FileDescriptor*>& parsed_files,
|
||||
const OutputDirective& output_directive,
|
||||
OutputDirectory* output_directory);
|
||||
bool GeneratePluginOutput(const vector<const FileDescriptor*>& parsed_files,
|
||||
const string& plugin_name,
|
||||
const string& parameter,
|
||||
OutputDirectory* output_directory,
|
||||
string* error);
|
||||
|
||||
// Implements --encode and --decode.
|
||||
bool EncodeOrDecode(const DescriptorPool* pool);
|
||||
|
||||
// Implements the --descriptor_set_out option.
|
||||
bool WriteDescriptorSet(const vector<const FileDescriptor*> parsed_files);
|
||||
|
||||
// Get all transitive dependencies of the given file (including the file
|
||||
// itself), adding them to the given list of FileDescriptorProtos. The
|
||||
// protos will be ordered such that every file is listed before any file that
|
||||
// depends on it, so that you can call DescriptorPool::BuildFile() on them
|
||||
// in order. Any files in *already_seen will not be added, and each file
|
||||
// added will be inserted into *already_seen.
|
||||
static void GetTransitiveDependencies(
|
||||
const FileDescriptor* file,
|
||||
set<const FileDescriptor*>* already_seen,
|
||||
RepeatedPtrField<FileDescriptorProto>* output);
|
||||
|
||||
// -----------------------------------------------------------------
|
||||
|
||||
// The name of the executable as invoked (i.e. argv[0]).
|
||||
string executable_name_;
|
||||
|
||||
// Version info set with SetVersionInfo().
|
||||
string version_info_;
|
||||
|
||||
// Map from flag names to registered generators.
|
||||
struct GeneratorInfo {
|
||||
CodeGenerator* generator;
|
||||
string help_text;
|
||||
};
|
||||
typedef map<string, GeneratorInfo> GeneratorMap;
|
||||
GeneratorMap generators_;
|
||||
|
||||
// See AllowPlugins(). If this is empty, plugins aren't allowed.
|
||||
string plugin_prefix_;
|
||||
|
||||
// Maps specific plugin names to files. When executing a plugin, this map
|
||||
// is searched first to find the plugin executable. If not found here, the
|
||||
// PATH (or other OS-specific search strategy) is searched.
|
||||
map<string, string> plugins_;
|
||||
|
||||
// Stuff parsed from command line.
|
||||
enum Mode {
|
||||
MODE_COMPILE, // Normal mode: parse .proto files and compile them.
|
||||
MODE_ENCODE, // --encode: read text from stdin, write binary to stdout.
|
||||
MODE_DECODE // --decode: read binary from stdin, write text to stdout.
|
||||
};
|
||||
|
||||
Mode mode_;
|
||||
|
||||
enum ErrorFormat {
|
||||
ERROR_FORMAT_GCC, // GCC error output format (default).
|
||||
ERROR_FORMAT_MSVS // Visual Studio output (--error_format=msvs).
|
||||
};
|
||||
|
||||
ErrorFormat error_format_;
|
||||
|
||||
vector<pair<string, string> > proto_path_; // Search path for proto files.
|
||||
vector<string> input_files_; // Names of the input proto files.
|
||||
|
||||
// output_directives_ lists all the files we are supposed to output and what
|
||||
// generator to use for each.
|
||||
struct OutputDirective {
|
||||
string name; // E.g. "--foo_out"
|
||||
CodeGenerator* generator; // NULL for plugins
|
||||
string parameter;
|
||||
string output_location;
|
||||
};
|
||||
vector<OutputDirective> output_directives_;
|
||||
|
||||
// When using --encode or --decode, this names the type we are encoding or
|
||||
// decoding. (Empty string indicates --decode_raw.)
|
||||
string codec_type_;
|
||||
|
||||
// If --descriptor_set_out was given, this is the filename to which the
|
||||
// FileDescriptorSet should be written. Otherwise, empty.
|
||||
string descriptor_set_name_;
|
||||
|
||||
// True if --include_imports was given, meaning that we should
|
||||
// write all transitive dependencies to the DescriptorSet. Otherwise, only
|
||||
// the .proto files listed on the command-line are added.
|
||||
bool imports_in_descriptor_set_;
|
||||
|
||||
// Was the --disallow_services flag used?
|
||||
bool disallow_services_;
|
||||
|
||||
// See SetInputsAreProtoPathRelative().
|
||||
bool inputs_are_proto_path_relative_;
|
||||
|
||||
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(CommandLineInterface);
|
||||
};
|
||||
|
||||
} // namespace compiler
|
||||
} // namespace protobuf
|
||||
|
||||
} // namespace google
|
||||
#endif // GOOGLE_PROTOBUF_COMPILER_COMMAND_LINE_INTERFACE_H__
|
||||
|
||||
+99
-99
@@ -1,99 +1,99 @@
|
||||
// Protocol Buffers - Google's data interchange format
|
||||
// Copyright 2008 Google Inc. All rights reserved.
|
||||
// http://code.google.com/p/protobuf/
|
||||
//
|
||||
// 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: kenton@google.com (Kenton Varda)
|
||||
// Based on original Protocol Buffers design by
|
||||
// Sanjay Ghemawat, Jeff Dean, and others.
|
||||
|
||||
#ifndef GOOGLE_PROTOBUF_COMPILER_CPP_ENUM_H__
|
||||
#define GOOGLE_PROTOBUF_COMPILER_CPP_ENUM_H__
|
||||
|
||||
#include <string>
|
||||
#include <google/protobuf/descriptor.h>
|
||||
|
||||
namespace google {
|
||||
namespace protobuf {
|
||||
namespace io {
|
||||
class Printer; // printer.h
|
||||
}
|
||||
}
|
||||
|
||||
namespace protobuf {
|
||||
namespace compiler {
|
||||
namespace cpp {
|
||||
|
||||
class EnumGenerator {
|
||||
public:
|
||||
// See generator.cc for the meaning of dllexport_decl.
|
||||
explicit EnumGenerator(const EnumDescriptor* descriptor,
|
||||
const string& dllexport_decl);
|
||||
~EnumGenerator();
|
||||
|
||||
// Header stuff.
|
||||
|
||||
// Generate header code defining the enum. This code should be placed
|
||||
// within the enum's package namespace, but NOT within any class, even for
|
||||
// nested enums.
|
||||
void GenerateDefinition(io::Printer* printer);
|
||||
|
||||
// Generate specialization of GetEnumDescriptor<MyEnum>().
|
||||
// Precondition: in ::google::protobuf namespace.
|
||||
void GenerateGetEnumDescriptorSpecializations(io::Printer* printer);
|
||||
|
||||
// For enums nested within a message, generate code to import all the enum's
|
||||
// symbols (e.g. the enum type name, all its values, etc.) into the class's
|
||||
// namespace. This should be placed inside the class definition in the
|
||||
// header.
|
||||
void GenerateSymbolImports(io::Printer* printer);
|
||||
|
||||
// Source file stuff.
|
||||
|
||||
// Generate code that initializes the global variable storing the enum's
|
||||
// descriptor.
|
||||
void GenerateDescriptorInitializer(io::Printer* printer, int index);
|
||||
|
||||
// Generate non-inline methods related to the enum, such as IsValidValue().
|
||||
// Goes in the .cc file.
|
||||
void GenerateMethods(io::Printer* printer);
|
||||
|
||||
private:
|
||||
const EnumDescriptor* descriptor_;
|
||||
string classname_;
|
||||
string dllexport_decl_;
|
||||
|
||||
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(EnumGenerator);
|
||||
};
|
||||
|
||||
} // namespace cpp
|
||||
} // namespace compiler
|
||||
} // namespace protobuf
|
||||
|
||||
} // namespace google
|
||||
#endif // GOOGLE_PROTOBUF_COMPILER_CPP_ENUM_H__
|
||||
// Protocol Buffers - Google's data interchange format
|
||||
// Copyright 2008 Google Inc. All rights reserved.
|
||||
// http://code.google.com/p/protobuf/
|
||||
//
|
||||
// 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: kenton@google.com (Kenton Varda)
|
||||
// Based on original Protocol Buffers design by
|
||||
// Sanjay Ghemawat, Jeff Dean, and others.
|
||||
|
||||
#ifndef GOOGLE_PROTOBUF_COMPILER_CPP_ENUM_H__
|
||||
#define GOOGLE_PROTOBUF_COMPILER_CPP_ENUM_H__
|
||||
|
||||
#include <string>
|
||||
#include <google/protobuf/descriptor.h>
|
||||
|
||||
namespace google {
|
||||
namespace protobuf {
|
||||
namespace io {
|
||||
class Printer; // printer.h
|
||||
}
|
||||
}
|
||||
|
||||
namespace protobuf {
|
||||
namespace compiler {
|
||||
namespace cpp {
|
||||
|
||||
class EnumGenerator {
|
||||
public:
|
||||
// See generator.cc for the meaning of dllexport_decl.
|
||||
explicit EnumGenerator(const EnumDescriptor* descriptor,
|
||||
const string& dllexport_decl);
|
||||
~EnumGenerator();
|
||||
|
||||
// Header stuff.
|
||||
|
||||
// Generate header code defining the enum. This code should be placed
|
||||
// within the enum's package namespace, but NOT within any class, even for
|
||||
// nested enums.
|
||||
void GenerateDefinition(io::Printer* printer);
|
||||
|
||||
// Generate specialization of GetEnumDescriptor<MyEnum>().
|
||||
// Precondition: in ::google::protobuf namespace.
|
||||
void GenerateGetEnumDescriptorSpecializations(io::Printer* printer);
|
||||
|
||||
// For enums nested within a message, generate code to import all the enum's
|
||||
// symbols (e.g. the enum type name, all its values, etc.) into the class's
|
||||
// namespace. This should be placed inside the class definition in the
|
||||
// header.
|
||||
void GenerateSymbolImports(io::Printer* printer);
|
||||
|
||||
// Source file stuff.
|
||||
|
||||
// Generate code that initializes the global variable storing the enum's
|
||||
// descriptor.
|
||||
void GenerateDescriptorInitializer(io::Printer* printer, int index);
|
||||
|
||||
// Generate non-inline methods related to the enum, such as IsValidValue().
|
||||
// Goes in the .cc file.
|
||||
void GenerateMethods(io::Printer* printer);
|
||||
|
||||
private:
|
||||
const EnumDescriptor* descriptor_;
|
||||
string classname_;
|
||||
string dllexport_decl_;
|
||||
|
||||
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(EnumGenerator);
|
||||
};
|
||||
|
||||
} // namespace cpp
|
||||
} // namespace compiler
|
||||
} // namespace protobuf
|
||||
|
||||
} // namespace google
|
||||
#endif // GOOGLE_PROTOBUF_COMPILER_CPP_ENUM_H__
|
||||
|
||||
+103
-103
@@ -1,103 +1,103 @@
|
||||
// Protocol Buffers - Google's data interchange format
|
||||
// Copyright 2008 Google Inc. All rights reserved.
|
||||
// http://code.google.com/p/protobuf/
|
||||
//
|
||||
// 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: kenton@google.com (Kenton Varda)
|
||||
// Based on original Protocol Buffers design by
|
||||
// Sanjay Ghemawat, Jeff Dean, and others.
|
||||
|
||||
#ifndef GOOGLE_PROTOBUF_COMPILER_CPP_ENUM_FIELD_H__
|
||||
#define GOOGLE_PROTOBUF_COMPILER_CPP_ENUM_FIELD_H__
|
||||
|
||||
#include <map>
|
||||
#include <string>
|
||||
#include <google/protobuf/compiler/cpp/cpp_field.h>
|
||||
|
||||
namespace google {
|
||||
namespace protobuf {
|
||||
namespace compiler {
|
||||
namespace cpp {
|
||||
|
||||
class EnumFieldGenerator : public FieldGenerator {
|
||||
public:
|
||||
explicit EnumFieldGenerator(const FieldDescriptor* descriptor);
|
||||
~EnumFieldGenerator();
|
||||
|
||||
// implements FieldGenerator ---------------------------------------
|
||||
void GeneratePrivateMembers(io::Printer* printer) const;
|
||||
void GenerateAccessorDeclarations(io::Printer* printer) const;
|
||||
void GenerateInlineAccessorDefinitions(io::Printer* printer) const;
|
||||
void GenerateClearingCode(io::Printer* printer) const;
|
||||
void GenerateMergingCode(io::Printer* printer) const;
|
||||
void GenerateSwappingCode(io::Printer* printer) const;
|
||||
void GenerateConstructorCode(io::Printer* printer) const;
|
||||
void GenerateMergeFromCodedStream(io::Printer* printer) const;
|
||||
void GenerateSerializeWithCachedSizes(io::Printer* printer) const;
|
||||
void GenerateSerializeWithCachedSizesToArray(io::Printer* printer) const;
|
||||
void GenerateByteSize(io::Printer* printer) const;
|
||||
|
||||
private:
|
||||
const FieldDescriptor* descriptor_;
|
||||
map<string, string> variables_;
|
||||
|
||||
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(EnumFieldGenerator);
|
||||
};
|
||||
|
||||
class RepeatedEnumFieldGenerator : public FieldGenerator {
|
||||
public:
|
||||
explicit RepeatedEnumFieldGenerator(const FieldDescriptor* descriptor);
|
||||
~RepeatedEnumFieldGenerator();
|
||||
|
||||
// implements FieldGenerator ---------------------------------------
|
||||
void GeneratePrivateMembers(io::Printer* printer) const;
|
||||
void GenerateAccessorDeclarations(io::Printer* printer) const;
|
||||
void GenerateInlineAccessorDefinitions(io::Printer* printer) const;
|
||||
void GenerateClearingCode(io::Printer* printer) const;
|
||||
void GenerateMergingCode(io::Printer* printer) const;
|
||||
void GenerateSwappingCode(io::Printer* printer) const;
|
||||
void GenerateConstructorCode(io::Printer* printer) const;
|
||||
void GenerateMergeFromCodedStream(io::Printer* printer) const;
|
||||
void GenerateMergeFromCodedStreamWithPacking(io::Printer* printer) const;
|
||||
void GenerateSerializeWithCachedSizes(io::Printer* printer) const;
|
||||
void GenerateSerializeWithCachedSizesToArray(io::Printer* printer) const;
|
||||
void GenerateByteSize(io::Printer* printer) const;
|
||||
|
||||
private:
|
||||
const FieldDescriptor* descriptor_;
|
||||
map<string, string> variables_;
|
||||
|
||||
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(RepeatedEnumFieldGenerator);
|
||||
};
|
||||
|
||||
} // namespace cpp
|
||||
} // namespace compiler
|
||||
} // namespace protobuf
|
||||
|
||||
} // namespace google
|
||||
#endif // GOOGLE_PROTOBUF_COMPILER_CPP_ENUM_FIELD_H__
|
||||
// Protocol Buffers - Google's data interchange format
|
||||
// Copyright 2008 Google Inc. All rights reserved.
|
||||
// http://code.google.com/p/protobuf/
|
||||
//
|
||||
// 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: kenton@google.com (Kenton Varda)
|
||||
// Based on original Protocol Buffers design by
|
||||
// Sanjay Ghemawat, Jeff Dean, and others.
|
||||
|
||||
#ifndef GOOGLE_PROTOBUF_COMPILER_CPP_ENUM_FIELD_H__
|
||||
#define GOOGLE_PROTOBUF_COMPILER_CPP_ENUM_FIELD_H__
|
||||
|
||||
#include <map>
|
||||
#include <string>
|
||||
#include <google/protobuf/compiler/cpp/cpp_field.h>
|
||||
|
||||
namespace google {
|
||||
namespace protobuf {
|
||||
namespace compiler {
|
||||
namespace cpp {
|
||||
|
||||
class EnumFieldGenerator : public FieldGenerator {
|
||||
public:
|
||||
explicit EnumFieldGenerator(const FieldDescriptor* descriptor);
|
||||
~EnumFieldGenerator();
|
||||
|
||||
// implements FieldGenerator ---------------------------------------
|
||||
void GeneratePrivateMembers(io::Printer* printer) const;
|
||||
void GenerateAccessorDeclarations(io::Printer* printer) const;
|
||||
void GenerateInlineAccessorDefinitions(io::Printer* printer) const;
|
||||
void GenerateClearingCode(io::Printer* printer) const;
|
||||
void GenerateMergingCode(io::Printer* printer) const;
|
||||
void GenerateSwappingCode(io::Printer* printer) const;
|
||||
void GenerateConstructorCode(io::Printer* printer) const;
|
||||
void GenerateMergeFromCodedStream(io::Printer* printer) const;
|
||||
void GenerateSerializeWithCachedSizes(io::Printer* printer) const;
|
||||
void GenerateSerializeWithCachedSizesToArray(io::Printer* printer) const;
|
||||
void GenerateByteSize(io::Printer* printer) const;
|
||||
|
||||
private:
|
||||
const FieldDescriptor* descriptor_;
|
||||
map<string, string> variables_;
|
||||
|
||||
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(EnumFieldGenerator);
|
||||
};
|
||||
|
||||
class RepeatedEnumFieldGenerator : public FieldGenerator {
|
||||
public:
|
||||
explicit RepeatedEnumFieldGenerator(const FieldDescriptor* descriptor);
|
||||
~RepeatedEnumFieldGenerator();
|
||||
|
||||
// implements FieldGenerator ---------------------------------------
|
||||
void GeneratePrivateMembers(io::Printer* printer) const;
|
||||
void GenerateAccessorDeclarations(io::Printer* printer) const;
|
||||
void GenerateInlineAccessorDefinitions(io::Printer* printer) const;
|
||||
void GenerateClearingCode(io::Printer* printer) const;
|
||||
void GenerateMergingCode(io::Printer* printer) const;
|
||||
void GenerateSwappingCode(io::Printer* printer) const;
|
||||
void GenerateConstructorCode(io::Printer* printer) const;
|
||||
void GenerateMergeFromCodedStream(io::Printer* printer) const;
|
||||
void GenerateMergeFromCodedStreamWithPacking(io::Printer* printer) const;
|
||||
void GenerateSerializeWithCachedSizes(io::Printer* printer) const;
|
||||
void GenerateSerializeWithCachedSizesToArray(io::Printer* printer) const;
|
||||
void GenerateByteSize(io::Printer* printer) const;
|
||||
|
||||
private:
|
||||
const FieldDescriptor* descriptor_;
|
||||
map<string, string> variables_;
|
||||
|
||||
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(RepeatedEnumFieldGenerator);
|
||||
};
|
||||
|
||||
} // namespace cpp
|
||||
} // namespace compiler
|
||||
} // namespace protobuf
|
||||
|
||||
} // namespace google
|
||||
#endif // GOOGLE_PROTOBUF_COMPILER_CPP_ENUM_FIELD_H__
|
||||
|
||||
+85
-85
@@ -1,85 +1,85 @@
|
||||
// Protocol Buffers - Google's data interchange format
|
||||
// Copyright 2008 Google Inc. All rights reserved.
|
||||
// http://code.google.com/p/protobuf/
|
||||
//
|
||||
// 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: kenton@google.com (Kenton Varda)
|
||||
// Based on original Protocol Buffers design by
|
||||
// Sanjay Ghemawat, Jeff Dean, and others.
|
||||
|
||||
#ifndef GOOGLE_PROTOBUF_COMPILER_CPP_EXTENSION_H__
|
||||
#define GOOGLE_PROTOBUF_COMPILER_CPP_EXTENSION_H__
|
||||
|
||||
#include <string>
|
||||
#include <google/protobuf/stubs/common.h>
|
||||
|
||||
namespace google {
|
||||
namespace protobuf {
|
||||
class FieldDescriptor; // descriptor.h
|
||||
namespace io {
|
||||
class Printer; // printer.h
|
||||
}
|
||||
}
|
||||
|
||||
namespace protobuf {
|
||||
namespace compiler {
|
||||
namespace cpp {
|
||||
|
||||
// Generates code for an extension, which may be within the scope of some
|
||||
// message or may be at file scope. This is much simpler than FieldGenerator
|
||||
// since extensions are just simple identifiers with interesting types.
|
||||
class ExtensionGenerator {
|
||||
public:
|
||||
// See generator.cc for the meaning of dllexport_decl.
|
||||
explicit ExtensionGenerator(const FieldDescriptor* descriptor,
|
||||
const string& dllexport_decl);
|
||||
~ExtensionGenerator();
|
||||
|
||||
// Header stuff.
|
||||
void GenerateDeclaration(io::Printer* printer);
|
||||
|
||||
// Source file stuff.
|
||||
void GenerateDefinition(io::Printer* printer);
|
||||
|
||||
// Generate code to register the extension.
|
||||
void GenerateRegistration(io::Printer* printer);
|
||||
|
||||
private:
|
||||
const FieldDescriptor* descriptor_;
|
||||
string type_traits_;
|
||||
string dllexport_decl_;
|
||||
|
||||
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(ExtensionGenerator);
|
||||
};
|
||||
|
||||
} // namespace cpp
|
||||
} // namespace compiler
|
||||
} // namespace protobuf
|
||||
|
||||
} // namespace google
|
||||
#endif // GOOGLE_PROTOBUF_COMPILER_CPP_MESSAGE_H__
|
||||
// Protocol Buffers - Google's data interchange format
|
||||
// Copyright 2008 Google Inc. All rights reserved.
|
||||
// http://code.google.com/p/protobuf/
|
||||
//
|
||||
// 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: kenton@google.com (Kenton Varda)
|
||||
// Based on original Protocol Buffers design by
|
||||
// Sanjay Ghemawat, Jeff Dean, and others.
|
||||
|
||||
#ifndef GOOGLE_PROTOBUF_COMPILER_CPP_EXTENSION_H__
|
||||
#define GOOGLE_PROTOBUF_COMPILER_CPP_EXTENSION_H__
|
||||
|
||||
#include <string>
|
||||
#include <google/protobuf/stubs/common.h>
|
||||
|
||||
namespace google {
|
||||
namespace protobuf {
|
||||
class FieldDescriptor; // descriptor.h
|
||||
namespace io {
|
||||
class Printer; // printer.h
|
||||
}
|
||||
}
|
||||
|
||||
namespace protobuf {
|
||||
namespace compiler {
|
||||
namespace cpp {
|
||||
|
||||
// Generates code for an extension, which may be within the scope of some
|
||||
// message or may be at file scope. This is much simpler than FieldGenerator
|
||||
// since extensions are just simple identifiers with interesting types.
|
||||
class ExtensionGenerator {
|
||||
public:
|
||||
// See generator.cc for the meaning of dllexport_decl.
|
||||
explicit ExtensionGenerator(const FieldDescriptor* descriptor,
|
||||
const string& dllexport_decl);
|
||||
~ExtensionGenerator();
|
||||
|
||||
// Header stuff.
|
||||
void GenerateDeclaration(io::Printer* printer);
|
||||
|
||||
// Source file stuff.
|
||||
void GenerateDefinition(io::Printer* printer);
|
||||
|
||||
// Generate code to register the extension.
|
||||
void GenerateRegistration(io::Printer* printer);
|
||||
|
||||
private:
|
||||
const FieldDescriptor* descriptor_;
|
||||
string type_traits_;
|
||||
string dllexport_decl_;
|
||||
|
||||
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(ExtensionGenerator);
|
||||
};
|
||||
|
||||
} // namespace cpp
|
||||
} // namespace compiler
|
||||
} // namespace protobuf
|
||||
|
||||
} // namespace google
|
||||
#endif // GOOGLE_PROTOBUF_COMPILER_CPP_MESSAGE_H__
|
||||
|
||||
+167
-167
@@ -1,167 +1,167 @@
|
||||
// Protocol Buffers - Google's data interchange format
|
||||
// Copyright 2008 Google Inc. All rights reserved.
|
||||
// http://code.google.com/p/protobuf/
|
||||
//
|
||||
// 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: kenton@google.com (Kenton Varda)
|
||||
// Based on original Protocol Buffers design by
|
||||
// Sanjay Ghemawat, Jeff Dean, and others.
|
||||
|
||||
#ifndef GOOGLE_PROTOBUF_COMPILER_CPP_FIELD_H__
|
||||
#define GOOGLE_PROTOBUF_COMPILER_CPP_FIELD_H__
|
||||
|
||||
#include <map>
|
||||
#include <string>
|
||||
|
||||
#include <google/protobuf/stubs/common.h>
|
||||
#include <google/protobuf/descriptor.h>
|
||||
|
||||
namespace google {
|
||||
namespace protobuf {
|
||||
namespace io {
|
||||
class Printer; // printer.h
|
||||
}
|
||||
}
|
||||
|
||||
namespace protobuf {
|
||||
namespace compiler {
|
||||
namespace cpp {
|
||||
|
||||
// Helper function: set variables in the map that are the same for all
|
||||
// field code generators.
|
||||
// ['name', 'index', 'number', 'classname', 'declared_type', 'tag_size',
|
||||
// 'deprecation'].
|
||||
void SetCommonFieldVariables(const FieldDescriptor* descriptor,
|
||||
map<string, string>* variables);
|
||||
|
||||
class FieldGenerator {
|
||||
public:
|
||||
FieldGenerator() {}
|
||||
virtual ~FieldGenerator();
|
||||
|
||||
// Generate lines of code declaring members fields of the message class
|
||||
// needed to represent this field. These are placed inside the message
|
||||
// class.
|
||||
virtual void GeneratePrivateMembers(io::Printer* printer) const = 0;
|
||||
|
||||
// Generate prototypes for all of the accessor functions related to this
|
||||
// field. These are placed inside the class definition.
|
||||
virtual void GenerateAccessorDeclarations(io::Printer* printer) const = 0;
|
||||
|
||||
// Generate inline definitions of accessor functions for this field.
|
||||
// These are placed inside the header after all class definitions.
|
||||
virtual void GenerateInlineAccessorDefinitions(
|
||||
io::Printer* printer) const = 0;
|
||||
|
||||
// Generate definitions of accessors that aren't inlined. These are
|
||||
// placed somewhere in the .cc file.
|
||||
// Most field types don't need this, so the default implementation is empty.
|
||||
virtual void GenerateNonInlineAccessorDefinitions(
|
||||
io::Printer* printer) const {}
|
||||
|
||||
// Generate lines of code (statements, not declarations) which clear the
|
||||
// field. This is used to define the clear_$name$() method as well as
|
||||
// the Clear() method for the whole message.
|
||||
virtual void GenerateClearingCode(io::Printer* printer) const = 0;
|
||||
|
||||
// Generate lines of code (statements, not declarations) which merges the
|
||||
// contents of the field from the current message to the target message,
|
||||
// which is stored in the generated code variable "from".
|
||||
// This is used to fill in the MergeFrom method for the whole message.
|
||||
// Details of this usage can be found in message.cc under the
|
||||
// GenerateMergeFrom method.
|
||||
virtual void GenerateMergingCode(io::Printer* printer) const = 0;
|
||||
|
||||
// Generate lines of code (statements, not declarations) which swaps
|
||||
// this field and the corresponding field of another message, which
|
||||
// is stored in the generated code variable "other". This is used to
|
||||
// define the Swap method. Details of usage can be found in
|
||||
// message.cc under the GenerateSwap method.
|
||||
virtual void GenerateSwappingCode(io::Printer* printer) const = 0;
|
||||
|
||||
// Generate initialization code for private members declared by
|
||||
// GeneratePrivateMembers(). These go into the message class's SharedCtor()
|
||||
// method, invoked by each of the generated constructors.
|
||||
virtual void GenerateConstructorCode(io::Printer* printer) const = 0;
|
||||
|
||||
// Generate any code that needs to go in the class's SharedDtor() method,
|
||||
// invoked by the destructor.
|
||||
// Most field types don't need this, so the default implementation is empty.
|
||||
virtual void GenerateDestructorCode(io::Printer* printer) const {}
|
||||
|
||||
// Generate lines to decode this field, which will be placed inside the
|
||||
// message's MergeFromCodedStream() method.
|
||||
virtual void GenerateMergeFromCodedStream(io::Printer* printer) const = 0;
|
||||
|
||||
// Generate lines to decode this field from a packed value, which will be
|
||||
// placed inside the message's MergeFromCodedStream() method.
|
||||
virtual void GenerateMergeFromCodedStreamWithPacking(io::Printer* printer)
|
||||
const;
|
||||
|
||||
// Generate lines to serialize this field, which are placed within the
|
||||
// message's SerializeWithCachedSizes() method.
|
||||
virtual void GenerateSerializeWithCachedSizes(io::Printer* printer) const = 0;
|
||||
|
||||
// Generate lines to serialize this field directly to the array "target",
|
||||
// which are placed within the message's SerializeWithCachedSizesToArray()
|
||||
// method. This must also advance "target" past the written bytes.
|
||||
virtual void GenerateSerializeWithCachedSizesToArray(
|
||||
io::Printer* printer) const = 0;
|
||||
|
||||
// Generate lines to compute the serialized size of this field, which
|
||||
// are placed in the message's ByteSize() method.
|
||||
virtual void GenerateByteSize(io::Printer* printer) const = 0;
|
||||
|
||||
private:
|
||||
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(FieldGenerator);
|
||||
};
|
||||
|
||||
// Convenience class which constructs FieldGenerators for a Descriptor.
|
||||
class FieldGeneratorMap {
|
||||
public:
|
||||
explicit FieldGeneratorMap(const Descriptor* descriptor);
|
||||
~FieldGeneratorMap();
|
||||
|
||||
const FieldGenerator& get(const FieldDescriptor* field) const;
|
||||
|
||||
private:
|
||||
const Descriptor* descriptor_;
|
||||
scoped_array<scoped_ptr<FieldGenerator> > field_generators_;
|
||||
|
||||
static FieldGenerator* MakeGenerator(const FieldDescriptor* field);
|
||||
|
||||
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(FieldGeneratorMap);
|
||||
};
|
||||
|
||||
|
||||
} // namespace cpp
|
||||
} // namespace compiler
|
||||
} // namespace protobuf
|
||||
|
||||
} // namespace google
|
||||
#endif // GOOGLE_PROTOBUF_COMPILER_CPP_FIELD_H__
|
||||
// Protocol Buffers - Google's data interchange format
|
||||
// Copyright 2008 Google Inc. All rights reserved.
|
||||
// http://code.google.com/p/protobuf/
|
||||
//
|
||||
// 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: kenton@google.com (Kenton Varda)
|
||||
// Based on original Protocol Buffers design by
|
||||
// Sanjay Ghemawat, Jeff Dean, and others.
|
||||
|
||||
#ifndef GOOGLE_PROTOBUF_COMPILER_CPP_FIELD_H__
|
||||
#define GOOGLE_PROTOBUF_COMPILER_CPP_FIELD_H__
|
||||
|
||||
#include <map>
|
||||
#include <string>
|
||||
|
||||
#include <google/protobuf/stubs/common.h>
|
||||
#include <google/protobuf/descriptor.h>
|
||||
|
||||
namespace google {
|
||||
namespace protobuf {
|
||||
namespace io {
|
||||
class Printer; // printer.h
|
||||
}
|
||||
}
|
||||
|
||||
namespace protobuf {
|
||||
namespace compiler {
|
||||
namespace cpp {
|
||||
|
||||
// Helper function: set variables in the map that are the same for all
|
||||
// field code generators.
|
||||
// ['name', 'index', 'number', 'classname', 'declared_type', 'tag_size',
|
||||
// 'deprecation'].
|
||||
void SetCommonFieldVariables(const FieldDescriptor* descriptor,
|
||||
map<string, string>* variables);
|
||||
|
||||
class FieldGenerator {
|
||||
public:
|
||||
FieldGenerator() {}
|
||||
virtual ~FieldGenerator();
|
||||
|
||||
// Generate lines of code declaring members fields of the message class
|
||||
// needed to represent this field. These are placed inside the message
|
||||
// class.
|
||||
virtual void GeneratePrivateMembers(io::Printer* printer) const = 0;
|
||||
|
||||
// Generate prototypes for all of the accessor functions related to this
|
||||
// field. These are placed inside the class definition.
|
||||
virtual void GenerateAccessorDeclarations(io::Printer* printer) const = 0;
|
||||
|
||||
// Generate inline definitions of accessor functions for this field.
|
||||
// These are placed inside the header after all class definitions.
|
||||
virtual void GenerateInlineAccessorDefinitions(
|
||||
io::Printer* printer) const = 0;
|
||||
|
||||
// Generate definitions of accessors that aren't inlined. These are
|
||||
// placed somewhere in the .cc file.
|
||||
// Most field types don't need this, so the default implementation is empty.
|
||||
virtual void GenerateNonInlineAccessorDefinitions(
|
||||
io::Printer* printer) const {}
|
||||
|
||||
// Generate lines of code (statements, not declarations) which clear the
|
||||
// field. This is used to define the clear_$name$() method as well as
|
||||
// the Clear() method for the whole message.
|
||||
virtual void GenerateClearingCode(io::Printer* printer) const = 0;
|
||||
|
||||
// Generate lines of code (statements, not declarations) which merges the
|
||||
// contents of the field from the current message to the target message,
|
||||
// which is stored in the generated code variable "from".
|
||||
// This is used to fill in the MergeFrom method for the whole message.
|
||||
// Details of this usage can be found in message.cc under the
|
||||
// GenerateMergeFrom method.
|
||||
virtual void GenerateMergingCode(io::Printer* printer) const = 0;
|
||||
|
||||
// Generate lines of code (statements, not declarations) which swaps
|
||||
// this field and the corresponding field of another message, which
|
||||
// is stored in the generated code variable "other". This is used to
|
||||
// define the Swap method. Details of usage can be found in
|
||||
// message.cc under the GenerateSwap method.
|
||||
virtual void GenerateSwappingCode(io::Printer* printer) const = 0;
|
||||
|
||||
// Generate initialization code for private members declared by
|
||||
// GeneratePrivateMembers(). These go into the message class's SharedCtor()
|
||||
// method, invoked by each of the generated constructors.
|
||||
virtual void GenerateConstructorCode(io::Printer* printer) const = 0;
|
||||
|
||||
// Generate any code that needs to go in the class's SharedDtor() method,
|
||||
// invoked by the destructor.
|
||||
// Most field types don't need this, so the default implementation is empty.
|
||||
virtual void GenerateDestructorCode(io::Printer* printer) const {}
|
||||
|
||||
// Generate lines to decode this field, which will be placed inside the
|
||||
// message's MergeFromCodedStream() method.
|
||||
virtual void GenerateMergeFromCodedStream(io::Printer* printer) const = 0;
|
||||
|
||||
// Generate lines to decode this field from a packed value, which will be
|
||||
// placed inside the message's MergeFromCodedStream() method.
|
||||
virtual void GenerateMergeFromCodedStreamWithPacking(io::Printer* printer)
|
||||
const;
|
||||
|
||||
// Generate lines to serialize this field, which are placed within the
|
||||
// message's SerializeWithCachedSizes() method.
|
||||
virtual void GenerateSerializeWithCachedSizes(io::Printer* printer) const = 0;
|
||||
|
||||
// Generate lines to serialize this field directly to the array "target",
|
||||
// which are placed within the message's SerializeWithCachedSizesToArray()
|
||||
// method. This must also advance "target" past the written bytes.
|
||||
virtual void GenerateSerializeWithCachedSizesToArray(
|
||||
io::Printer* printer) const = 0;
|
||||
|
||||
// Generate lines to compute the serialized size of this field, which
|
||||
// are placed in the message's ByteSize() method.
|
||||
virtual void GenerateByteSize(io::Printer* printer) const = 0;
|
||||
|
||||
private:
|
||||
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(FieldGenerator);
|
||||
};
|
||||
|
||||
// Convenience class which constructs FieldGenerators for a Descriptor.
|
||||
class FieldGeneratorMap {
|
||||
public:
|
||||
explicit FieldGeneratorMap(const Descriptor* descriptor);
|
||||
~FieldGeneratorMap();
|
||||
|
||||
const FieldGenerator& get(const FieldDescriptor* field) const;
|
||||
|
||||
private:
|
||||
const Descriptor* descriptor_;
|
||||
scoped_array<scoped_ptr<FieldGenerator> > field_generators_;
|
||||
|
||||
static FieldGenerator* MakeGenerator(const FieldDescriptor* field);
|
||||
|
||||
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(FieldGeneratorMap);
|
||||
};
|
||||
|
||||
|
||||
} // namespace cpp
|
||||
} // namespace compiler
|
||||
} // namespace protobuf
|
||||
|
||||
} // namespace google
|
||||
#endif // GOOGLE_PROTOBUF_COMPILER_CPP_FIELD_H__
|
||||
|
||||
+98
-98
@@ -1,98 +1,98 @@
|
||||
// Protocol Buffers - Google's data interchange format
|
||||
// Copyright 2008 Google Inc. All rights reserved.
|
||||
// http://code.google.com/p/protobuf/
|
||||
//
|
||||
// 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: kenton@google.com (Kenton Varda)
|
||||
// Based on original Protocol Buffers design by
|
||||
// Sanjay Ghemawat, Jeff Dean, and others.
|
||||
|
||||
#ifndef GOOGLE_PROTOBUF_COMPILER_CPP_FILE_H__
|
||||
#define GOOGLE_PROTOBUF_COMPILER_CPP_FILE_H__
|
||||
|
||||
#include <string>
|
||||
#include <vector>
|
||||
#include <google/protobuf/stubs/common.h>
|
||||
#include <google/protobuf/compiler/cpp/cpp_field.h>
|
||||
|
||||
namespace google {
|
||||
namespace protobuf {
|
||||
class FileDescriptor; // descriptor.h
|
||||
namespace io {
|
||||
class Printer; // printer.h
|
||||
}
|
||||
}
|
||||
|
||||
namespace protobuf {
|
||||
namespace compiler {
|
||||
namespace cpp {
|
||||
|
||||
class EnumGenerator; // enum.h
|
||||
class MessageGenerator; // message.h
|
||||
class ServiceGenerator; // service.h
|
||||
class ExtensionGenerator; // extension.h
|
||||
|
||||
class FileGenerator {
|
||||
public:
|
||||
// See generator.cc for the meaning of dllexport_decl.
|
||||
explicit FileGenerator(const FileDescriptor* file,
|
||||
const string& dllexport_decl);
|
||||
~FileGenerator();
|
||||
|
||||
void GenerateHeader(io::Printer* printer);
|
||||
void GenerateSource(io::Printer* printer);
|
||||
|
||||
private:
|
||||
// Generate the BuildDescriptors() procedure, which builds all descriptors
|
||||
// for types defined in the file.
|
||||
void GenerateBuildDescriptors(io::Printer* printer);
|
||||
|
||||
void GenerateNamespaceOpeners(io::Printer* printer);
|
||||
void GenerateNamespaceClosers(io::Printer* printer);
|
||||
|
||||
const FileDescriptor* file_;
|
||||
|
||||
scoped_array<scoped_ptr<MessageGenerator> > message_generators_;
|
||||
scoped_array<scoped_ptr<EnumGenerator> > enum_generators_;
|
||||
scoped_array<scoped_ptr<ServiceGenerator> > service_generators_;
|
||||
scoped_array<scoped_ptr<ExtensionGenerator> > extension_generators_;
|
||||
|
||||
// E.g. if the package is foo.bar, package_parts_ is {"foo", "bar"}.
|
||||
vector<string> package_parts_;
|
||||
|
||||
string dllexport_decl_;
|
||||
|
||||
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(FileGenerator);
|
||||
};
|
||||
|
||||
} // namespace cpp
|
||||
} // namespace compiler
|
||||
} // namespace protobuf
|
||||
|
||||
} // namespace google
|
||||
#endif // GOOGLE_PROTOBUF_COMPILER_CPP_FILE_H__
|
||||
// Protocol Buffers - Google's data interchange format
|
||||
// Copyright 2008 Google Inc. All rights reserved.
|
||||
// http://code.google.com/p/protobuf/
|
||||
//
|
||||
// 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: kenton@google.com (Kenton Varda)
|
||||
// Based on original Protocol Buffers design by
|
||||
// Sanjay Ghemawat, Jeff Dean, and others.
|
||||
|
||||
#ifndef GOOGLE_PROTOBUF_COMPILER_CPP_FILE_H__
|
||||
#define GOOGLE_PROTOBUF_COMPILER_CPP_FILE_H__
|
||||
|
||||
#include <string>
|
||||
#include <vector>
|
||||
#include <google/protobuf/stubs/common.h>
|
||||
#include <google/protobuf/compiler/cpp/cpp_field.h>
|
||||
|
||||
namespace google {
|
||||
namespace protobuf {
|
||||
class FileDescriptor; // descriptor.h
|
||||
namespace io {
|
||||
class Printer; // printer.h
|
||||
}
|
||||
}
|
||||
|
||||
namespace protobuf {
|
||||
namespace compiler {
|
||||
namespace cpp {
|
||||
|
||||
class EnumGenerator; // enum.h
|
||||
class MessageGenerator; // message.h
|
||||
class ServiceGenerator; // service.h
|
||||
class ExtensionGenerator; // extension.h
|
||||
|
||||
class FileGenerator {
|
||||
public:
|
||||
// See generator.cc for the meaning of dllexport_decl.
|
||||
explicit FileGenerator(const FileDescriptor* file,
|
||||
const string& dllexport_decl);
|
||||
~FileGenerator();
|
||||
|
||||
void GenerateHeader(io::Printer* printer);
|
||||
void GenerateSource(io::Printer* printer);
|
||||
|
||||
private:
|
||||
// Generate the BuildDescriptors() procedure, which builds all descriptors
|
||||
// for types defined in the file.
|
||||
void GenerateBuildDescriptors(io::Printer* printer);
|
||||
|
||||
void GenerateNamespaceOpeners(io::Printer* printer);
|
||||
void GenerateNamespaceClosers(io::Printer* printer);
|
||||
|
||||
const FileDescriptor* file_;
|
||||
|
||||
scoped_array<scoped_ptr<MessageGenerator> > message_generators_;
|
||||
scoped_array<scoped_ptr<EnumGenerator> > enum_generators_;
|
||||
scoped_array<scoped_ptr<ServiceGenerator> > service_generators_;
|
||||
scoped_array<scoped_ptr<ExtensionGenerator> > extension_generators_;
|
||||
|
||||
// E.g. if the package is foo.bar, package_parts_ is {"foo", "bar"}.
|
||||
vector<string> package_parts_;
|
||||
|
||||
string dllexport_decl_;
|
||||
|
||||
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(FileGenerator);
|
||||
};
|
||||
|
||||
} // namespace cpp
|
||||
} // namespace compiler
|
||||
} // namespace protobuf
|
||||
|
||||
} // namespace google
|
||||
#endif // GOOGLE_PROTOBUF_COMPILER_CPP_FILE_H__
|
||||
|
||||
+72
-72
@@ -1,72 +1,72 @@
|
||||
// Protocol Buffers - Google's data interchange format
|
||||
// Copyright 2008 Google Inc. All rights reserved.
|
||||
// http://code.google.com/p/protobuf/
|
||||
//
|
||||
// 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: kenton@google.com (Kenton Varda)
|
||||
// Based on original Protocol Buffers design by
|
||||
// Sanjay Ghemawat, Jeff Dean, and others.
|
||||
//
|
||||
// Generates C++ code for a given .proto file.
|
||||
|
||||
#ifndef GOOGLE_PROTOBUF_COMPILER_CPP_GENERATOR_H__
|
||||
#define GOOGLE_PROTOBUF_COMPILER_CPP_GENERATOR_H__
|
||||
|
||||
#include <string>
|
||||
#include <google/protobuf/compiler/code_generator.h>
|
||||
|
||||
namespace google {
|
||||
namespace protobuf {
|
||||
namespace compiler {
|
||||
namespace cpp {
|
||||
|
||||
// CodeGenerator implementation which generates a C++ source file and
|
||||
// header. If you create your own protocol compiler binary and you want
|
||||
// it to support C++ output, you can do so by registering an instance of this
|
||||
// CodeGenerator with the CommandLineInterface in your main() function.
|
||||
class LIBPROTOC_EXPORT CppGenerator : public CodeGenerator {
|
||||
public:
|
||||
CppGenerator();
|
||||
~CppGenerator();
|
||||
|
||||
// implements CodeGenerator ----------------------------------------
|
||||
bool Generate(const FileDescriptor* file,
|
||||
const string& parameter,
|
||||
OutputDirectory* output_directory,
|
||||
string* error) const;
|
||||
|
||||
private:
|
||||
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(CppGenerator);
|
||||
};
|
||||
|
||||
} // namespace cpp
|
||||
} // namespace compiler
|
||||
} // namespace protobuf
|
||||
|
||||
} // namespace google
|
||||
#endif // GOOGLE_PROTOBUF_COMPILER_CPP_GENERATOR_H__
|
||||
// Protocol Buffers - Google's data interchange format
|
||||
// Copyright 2008 Google Inc. All rights reserved.
|
||||
// http://code.google.com/p/protobuf/
|
||||
//
|
||||
// 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: kenton@google.com (Kenton Varda)
|
||||
// Based on original Protocol Buffers design by
|
||||
// Sanjay Ghemawat, Jeff Dean, and others.
|
||||
//
|
||||
// Generates C++ code for a given .proto file.
|
||||
|
||||
#ifndef GOOGLE_PROTOBUF_COMPILER_CPP_GENERATOR_H__
|
||||
#define GOOGLE_PROTOBUF_COMPILER_CPP_GENERATOR_H__
|
||||
|
||||
#include <string>
|
||||
#include <google/protobuf/compiler/code_generator.h>
|
||||
|
||||
namespace google {
|
||||
namespace protobuf {
|
||||
namespace compiler {
|
||||
namespace cpp {
|
||||
|
||||
// CodeGenerator implementation which generates a C++ source file and
|
||||
// header. If you create your own protocol compiler binary and you want
|
||||
// it to support C++ output, you can do so by registering an instance of this
|
||||
// CodeGenerator with the CommandLineInterface in your main() function.
|
||||
class LIBPROTOC_EXPORT CppGenerator : public CodeGenerator {
|
||||
public:
|
||||
CppGenerator();
|
||||
~CppGenerator();
|
||||
|
||||
// implements CodeGenerator ----------------------------------------
|
||||
bool Generate(const FileDescriptor* file,
|
||||
const string& parameter,
|
||||
OutputDirectory* output_directory,
|
||||
string* error) const;
|
||||
|
||||
private:
|
||||
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(CppGenerator);
|
||||
};
|
||||
|
||||
} // namespace cpp
|
||||
} // namespace compiler
|
||||
} // namespace protobuf
|
||||
|
||||
} // namespace google
|
||||
#endif // GOOGLE_PROTOBUF_COMPILER_CPP_GENERATOR_H__
|
||||
|
||||
+156
-156
@@ -1,156 +1,156 @@
|
||||
// Protocol Buffers - Google's data interchange format
|
||||
// Copyright 2008 Google Inc. All rights reserved.
|
||||
// http://code.google.com/p/protobuf/
|
||||
//
|
||||
// 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: kenton@google.com (Kenton Varda)
|
||||
// Based on original Protocol Buffers design by
|
||||
// Sanjay Ghemawat, Jeff Dean, and others.
|
||||
|
||||
#ifndef GOOGLE_PROTOBUF_COMPILER_CPP_HELPERS_H__
|
||||
#define GOOGLE_PROTOBUF_COMPILER_CPP_HELPERS_H__
|
||||
|
||||
#include <string>
|
||||
#include <google/protobuf/descriptor.h>
|
||||
#include <google/protobuf/descriptor.pb.h>
|
||||
|
||||
namespace google {
|
||||
namespace protobuf {
|
||||
namespace compiler {
|
||||
namespace cpp {
|
||||
|
||||
// Commonly-used separator comments. Thick is a line of '=', thin is a line
|
||||
// of '-'.
|
||||
extern const char kThickSeparator[];
|
||||
extern const char kThinSeparator[];
|
||||
|
||||
// Returns the non-nested type name for the given type. If "qualified" is
|
||||
// true, prefix the type with the full namespace. For example, if you had:
|
||||
// package foo.bar;
|
||||
// message Baz { message Qux {} }
|
||||
// Then the qualified ClassName for Qux would be:
|
||||
// ::foo::bar::Baz_Qux
|
||||
// While the non-qualified version would be:
|
||||
// Baz_Qux
|
||||
string ClassName(const Descriptor* descriptor, bool qualified);
|
||||
string ClassName(const EnumDescriptor* enum_descriptor, bool qualified);
|
||||
|
||||
string SuperClassName(const Descriptor* descriptor);
|
||||
|
||||
// Get the (unqualified) name that should be used for this field in C++ code.
|
||||
// The name is coerced to lower-case to emulate proto1 behavior. People
|
||||
// should be using lowercase-with-underscores style for proto field names
|
||||
// anyway, so normally this just returns field->name().
|
||||
string FieldName(const FieldDescriptor* field);
|
||||
|
||||
// Get the unqualified name that should be used for a field's field
|
||||
// number constant.
|
||||
string FieldConstantName(const FieldDescriptor *field);
|
||||
|
||||
// Returns the scope where the field was defined (for extensions, this is
|
||||
// different from the message type to which the field applies).
|
||||
inline const Descriptor* FieldScope(const FieldDescriptor* field) {
|
||||
return field->is_extension() ?
|
||||
field->extension_scope() : field->containing_type();
|
||||
}
|
||||
|
||||
// Returns the fully-qualified type name field->message_type(). Usually this
|
||||
// is just ClassName(field->message_type(), true);
|
||||
string FieldMessageTypeName(const FieldDescriptor* field);
|
||||
|
||||
// Strips ".proto" or ".protodevel" from the end of a filename.
|
||||
string StripProto(const string& filename);
|
||||
|
||||
// Get the C++ type name for a primitive type (e.g. "double", "::google::protobuf::int32", etc.).
|
||||
// Note: non-built-in type names will be qualified, meaning they will start
|
||||
// with a ::. If you are using the type as a template parameter, you will
|
||||
// need to insure there is a space between the < and the ::, because the
|
||||
// ridiculous C++ standard defines "<:" to be a synonym for "[".
|
||||
const char* PrimitiveTypeName(FieldDescriptor::CppType type);
|
||||
|
||||
// Get the declared type name in CamelCase format, as is used e.g. for the
|
||||
// methods of WireFormat. For example, TYPE_INT32 becomes "Int32".
|
||||
const char* DeclaredTypeMethodName(FieldDescriptor::Type type);
|
||||
|
||||
// Get code that evaluates to the field's default value.
|
||||
string DefaultValue(const FieldDescriptor* field);
|
||||
|
||||
// Convert a file name into a valid identifier.
|
||||
string FilenameIdentifier(const string& filename);
|
||||
|
||||
// Return the name of the AddDescriptors() function for a given file.
|
||||
string GlobalAddDescriptorsName(const string& filename);
|
||||
|
||||
// Return the name of the AssignDescriptors() function for a given file.
|
||||
string GlobalAssignDescriptorsName(const string& filename);
|
||||
|
||||
// Return the name of the ShutdownFile() function for a given file.
|
||||
string GlobalShutdownFileName(const string& filename);
|
||||
|
||||
// Do message classes in this file keep track of unknown fields?
|
||||
inline bool HasUnknownFields(const FileDescriptor *file) {
|
||||
return file->options().optimize_for() != FileOptions::LITE_RUNTIME;
|
||||
}
|
||||
|
||||
// Does this file have generated parsing, serialization, and other
|
||||
// standard methods for which reflection-based fallback implementations exist?
|
||||
inline bool HasGeneratedMethods(const FileDescriptor *file) {
|
||||
return file->options().optimize_for() != FileOptions::CODE_SIZE;
|
||||
}
|
||||
|
||||
// Do message classes in this file have descriptor and refelction methods?
|
||||
inline bool HasDescriptorMethods(const FileDescriptor *file) {
|
||||
return file->options().optimize_for() != FileOptions::LITE_RUNTIME;
|
||||
}
|
||||
|
||||
// Should we generate generic services for this file?
|
||||
inline bool HasGenericServices(const FileDescriptor *file) {
|
||||
return file->service_count() > 0 &&
|
||||
file->options().optimize_for() != FileOptions::LITE_RUNTIME &&
|
||||
file->options().cc_generic_services();
|
||||
}
|
||||
|
||||
// Should string fields in this file verify that their contents are UTF-8?
|
||||
inline bool HasUtf8Verification(const FileDescriptor* file) {
|
||||
return file->options().optimize_for() != FileOptions::LITE_RUNTIME;
|
||||
}
|
||||
|
||||
// Should we generate a separate, super-optimized code path for serializing to
|
||||
// flat arrays? We don't do this in Lite mode because we'd rather reduce code
|
||||
// size.
|
||||
inline bool HasFastArraySerialization(const FileDescriptor* file) {
|
||||
return file->options().optimize_for() == FileOptions::SPEED;
|
||||
}
|
||||
|
||||
|
||||
} // namespace cpp
|
||||
} // namespace compiler
|
||||
} // namespace protobuf
|
||||
|
||||
} // namespace google
|
||||
#endif // GOOGLE_PROTOBUF_COMPILER_CPP_HELPERS_H__
|
||||
// Protocol Buffers - Google's data interchange format
|
||||
// Copyright 2008 Google Inc. All rights reserved.
|
||||
// http://code.google.com/p/protobuf/
|
||||
//
|
||||
// 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: kenton@google.com (Kenton Varda)
|
||||
// Based on original Protocol Buffers design by
|
||||
// Sanjay Ghemawat, Jeff Dean, and others.
|
||||
|
||||
#ifndef GOOGLE_PROTOBUF_COMPILER_CPP_HELPERS_H__
|
||||
#define GOOGLE_PROTOBUF_COMPILER_CPP_HELPERS_H__
|
||||
|
||||
#include <string>
|
||||
#include <google/protobuf/descriptor.h>
|
||||
#include <google/protobuf/descriptor.pb.h>
|
||||
|
||||
namespace google {
|
||||
namespace protobuf {
|
||||
namespace compiler {
|
||||
namespace cpp {
|
||||
|
||||
// Commonly-used separator comments. Thick is a line of '=', thin is a line
|
||||
// of '-'.
|
||||
extern const char kThickSeparator[];
|
||||
extern const char kThinSeparator[];
|
||||
|
||||
// Returns the non-nested type name for the given type. If "qualified" is
|
||||
// true, prefix the type with the full namespace. For example, if you had:
|
||||
// package foo.bar;
|
||||
// message Baz { message Qux {} }
|
||||
// Then the qualified ClassName for Qux would be:
|
||||
// ::foo::bar::Baz_Qux
|
||||
// While the non-qualified version would be:
|
||||
// Baz_Qux
|
||||
string ClassName(const Descriptor* descriptor, bool qualified);
|
||||
string ClassName(const EnumDescriptor* enum_descriptor, bool qualified);
|
||||
|
||||
string SuperClassName(const Descriptor* descriptor);
|
||||
|
||||
// Get the (unqualified) name that should be used for this field in C++ code.
|
||||
// The name is coerced to lower-case to emulate proto1 behavior. People
|
||||
// should be using lowercase-with-underscores style for proto field names
|
||||
// anyway, so normally this just returns field->name().
|
||||
string FieldName(const FieldDescriptor* field);
|
||||
|
||||
// Get the unqualified name that should be used for a field's field
|
||||
// number constant.
|
||||
string FieldConstantName(const FieldDescriptor *field);
|
||||
|
||||
// Returns the scope where the field was defined (for extensions, this is
|
||||
// different from the message type to which the field applies).
|
||||
inline const Descriptor* FieldScope(const FieldDescriptor* field) {
|
||||
return field->is_extension() ?
|
||||
field->extension_scope() : field->containing_type();
|
||||
}
|
||||
|
||||
// Returns the fully-qualified type name field->message_type(). Usually this
|
||||
// is just ClassName(field->message_type(), true);
|
||||
string FieldMessageTypeName(const FieldDescriptor* field);
|
||||
|
||||
// Strips ".proto" or ".protodevel" from the end of a filename.
|
||||
string StripProto(const string& filename);
|
||||
|
||||
// Get the C++ type name for a primitive type (e.g. "double", "::google::protobuf::int32", etc.).
|
||||
// Note: non-built-in type names will be qualified, meaning they will start
|
||||
// with a ::. If you are using the type as a template parameter, you will
|
||||
// need to insure there is a space between the < and the ::, because the
|
||||
// ridiculous C++ standard defines "<:" to be a synonym for "[".
|
||||
const char* PrimitiveTypeName(FieldDescriptor::CppType type);
|
||||
|
||||
// Get the declared type name in CamelCase format, as is used e.g. for the
|
||||
// methods of WireFormat. For example, TYPE_INT32 becomes "Int32".
|
||||
const char* DeclaredTypeMethodName(FieldDescriptor::Type type);
|
||||
|
||||
// Get code that evaluates to the field's default value.
|
||||
string DefaultValue(const FieldDescriptor* field);
|
||||
|
||||
// Convert a file name into a valid identifier.
|
||||
string FilenameIdentifier(const string& filename);
|
||||
|
||||
// Return the name of the AddDescriptors() function for a given file.
|
||||
string GlobalAddDescriptorsName(const string& filename);
|
||||
|
||||
// Return the name of the AssignDescriptors() function for a given file.
|
||||
string GlobalAssignDescriptorsName(const string& filename);
|
||||
|
||||
// Return the name of the ShutdownFile() function for a given file.
|
||||
string GlobalShutdownFileName(const string& filename);
|
||||
|
||||
// Do message classes in this file keep track of unknown fields?
|
||||
inline bool HasUnknownFields(const FileDescriptor *file) {
|
||||
return file->options().optimize_for() != FileOptions::LITE_RUNTIME;
|
||||
}
|
||||
|
||||
// Does this file have generated parsing, serialization, and other
|
||||
// standard methods for which reflection-based fallback implementations exist?
|
||||
inline bool HasGeneratedMethods(const FileDescriptor *file) {
|
||||
return file->options().optimize_for() != FileOptions::CODE_SIZE;
|
||||
}
|
||||
|
||||
// Do message classes in this file have descriptor and refelction methods?
|
||||
inline bool HasDescriptorMethods(const FileDescriptor *file) {
|
||||
return file->options().optimize_for() != FileOptions::LITE_RUNTIME;
|
||||
}
|
||||
|
||||
// Should we generate generic services for this file?
|
||||
inline bool HasGenericServices(const FileDescriptor *file) {
|
||||
return file->service_count() > 0 &&
|
||||
file->options().optimize_for() != FileOptions::LITE_RUNTIME &&
|
||||
file->options().cc_generic_services();
|
||||
}
|
||||
|
||||
// Should string fields in this file verify that their contents are UTF-8?
|
||||
inline bool HasUtf8Verification(const FileDescriptor* file) {
|
||||
return file->options().optimize_for() != FileOptions::LITE_RUNTIME;
|
||||
}
|
||||
|
||||
// Should we generate a separate, super-optimized code path for serializing to
|
||||
// flat arrays? We don't do this in Lite mode because we'd rather reduce code
|
||||
// size.
|
||||
inline bool HasFastArraySerialization(const FileDescriptor* file) {
|
||||
return file->options().optimize_for() == FileOptions::SPEED;
|
||||
}
|
||||
|
||||
|
||||
} // namespace cpp
|
||||
} // namespace compiler
|
||||
} // namespace protobuf
|
||||
|
||||
} // namespace google
|
||||
#endif // GOOGLE_PROTOBUF_COMPILER_CPP_HELPERS_H__
|
||||
|
||||
+170
-170
@@ -1,170 +1,170 @@
|
||||
// Protocol Buffers - Google's data interchange format
|
||||
// Copyright 2008 Google Inc. All rights reserved.
|
||||
// http://code.google.com/p/protobuf/
|
||||
//
|
||||
// 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: kenton@google.com (Kenton Varda)
|
||||
// Based on original Protocol Buffers design by
|
||||
// Sanjay Ghemawat, Jeff Dean, and others.
|
||||
|
||||
#ifndef GOOGLE_PROTOBUF_COMPILER_CPP_MESSAGE_H__
|
||||
#define GOOGLE_PROTOBUF_COMPILER_CPP_MESSAGE_H__
|
||||
|
||||
#include <string>
|
||||
#include <google/protobuf/stubs/common.h>
|
||||
#include <google/protobuf/compiler/cpp/cpp_field.h>
|
||||
|
||||
namespace google {
|
||||
namespace protobuf {
|
||||
namespace io {
|
||||
class Printer; // printer.h
|
||||
}
|
||||
}
|
||||
|
||||
namespace protobuf {
|
||||
namespace compiler {
|
||||
namespace cpp {
|
||||
|
||||
class EnumGenerator; // enum.h
|
||||
class ExtensionGenerator; // extension.h
|
||||
|
||||
class MessageGenerator {
|
||||
public:
|
||||
// See generator.cc for the meaning of dllexport_decl.
|
||||
explicit MessageGenerator(const Descriptor* descriptor,
|
||||
const string& dllexport_decl);
|
||||
~MessageGenerator();
|
||||
|
||||
// Header stuff.
|
||||
|
||||
// Generate foward declarations for this class and all its nested types.
|
||||
void GenerateForwardDeclaration(io::Printer* printer);
|
||||
|
||||
// Generate definitions of all nested enums (must come before class
|
||||
// definitions because those classes use the enums definitions).
|
||||
void GenerateEnumDefinitions(io::Printer* printer);
|
||||
|
||||
// Generate specializations of GetEnumDescriptor<MyEnum>().
|
||||
// Precondition: in ::google::protobuf namespace.
|
||||
void GenerateGetEnumDescriptorSpecializations(io::Printer* printer);
|
||||
|
||||
// Generate definitions for this class and all its nested types.
|
||||
void GenerateClassDefinition(io::Printer* printer);
|
||||
|
||||
// Generate definitions of inline methods (placed at the end of the header
|
||||
// file).
|
||||
void GenerateInlineMethods(io::Printer* printer);
|
||||
|
||||
// Source file stuff.
|
||||
|
||||
// Generate code which declares all the global descriptor pointers which
|
||||
// will be initialized by the methods below.
|
||||
void GenerateDescriptorDeclarations(io::Printer* printer);
|
||||
|
||||
// Generate code that initializes the global variable storing the message's
|
||||
// descriptor.
|
||||
void GenerateDescriptorInitializer(io::Printer* printer, int index);
|
||||
|
||||
// Generate code that calls MessageFactory::InternalRegisterGeneratedMessage()
|
||||
// for all types.
|
||||
void GenerateTypeRegistrations(io::Printer* printer);
|
||||
|
||||
// Generates code that allocates the message's default instance.
|
||||
void GenerateDefaultInstanceAllocator(io::Printer* printer);
|
||||
|
||||
// Generates code that initializes the message's default instance. This
|
||||
// is separate from allocating because all default instances must be
|
||||
// allocated before any can be initialized.
|
||||
void GenerateDefaultInstanceInitializer(io::Printer* printer);
|
||||
|
||||
// Generates code that should be run when ShutdownProtobufLibrary() is called,
|
||||
// to delete all dynamically-allocated objects.
|
||||
void GenerateShutdownCode(io::Printer* printer);
|
||||
|
||||
// Generate all non-inline methods for this class.
|
||||
void GenerateClassMethods(io::Printer* printer);
|
||||
|
||||
private:
|
||||
// Generate declarations and definitions of accessors for fields.
|
||||
void GenerateFieldAccessorDeclarations(io::Printer* printer);
|
||||
void GenerateFieldAccessorDefinitions(io::Printer* printer);
|
||||
|
||||
// Generate the field offsets array.
|
||||
void GenerateOffsets(io::Printer* printer);
|
||||
|
||||
// Generate constructors and destructor.
|
||||
void GenerateStructors(io::Printer* printer);
|
||||
|
||||
// The compiler typically generates multiple copies of each constructor and
|
||||
// destructor: http://gcc.gnu.org/bugs.html#nonbugs_cxx
|
||||
// Placing common code in a separate method reduces the generated code size.
|
||||
//
|
||||
// Generate the shared constructor code.
|
||||
void GenerateSharedConstructorCode(io::Printer* printer);
|
||||
// Generate the shared destructor code.
|
||||
void GenerateSharedDestructorCode(io::Printer* printer);
|
||||
|
||||
// Generate standard Message methods.
|
||||
void GenerateClear(io::Printer* printer);
|
||||
void GenerateMergeFromCodedStream(io::Printer* printer);
|
||||
void GenerateSerializeWithCachedSizes(io::Printer* printer);
|
||||
void GenerateSerializeWithCachedSizesToArray(io::Printer* printer);
|
||||
void GenerateSerializeWithCachedSizesBody(io::Printer* printer,
|
||||
bool to_array);
|
||||
void GenerateByteSize(io::Printer* printer);
|
||||
void GenerateMergeFrom(io::Printer* printer);
|
||||
void GenerateCopyFrom(io::Printer* printer);
|
||||
void GenerateSwap(io::Printer* printer);
|
||||
void GenerateIsInitialized(io::Printer* printer);
|
||||
|
||||
// Helpers for GenerateSerializeWithCachedSizes().
|
||||
void GenerateSerializeOneField(io::Printer* printer,
|
||||
const FieldDescriptor* field,
|
||||
bool unbounded);
|
||||
void GenerateSerializeOneExtensionRange(
|
||||
io::Printer* printer, const Descriptor::ExtensionRange* range,
|
||||
bool unbounded);
|
||||
|
||||
|
||||
const Descriptor* descriptor_;
|
||||
string classname_;
|
||||
string dllexport_decl_;
|
||||
FieldGeneratorMap field_generators_;
|
||||
scoped_array<scoped_ptr<MessageGenerator> > nested_generators_;
|
||||
scoped_array<scoped_ptr<EnumGenerator> > enum_generators_;
|
||||
scoped_array<scoped_ptr<ExtensionGenerator> > extension_generators_;
|
||||
|
||||
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(MessageGenerator);
|
||||
};
|
||||
|
||||
} // namespace cpp
|
||||
} // namespace compiler
|
||||
} // namespace protobuf
|
||||
|
||||
} // namespace google
|
||||
#endif // GOOGLE_PROTOBUF_COMPILER_CPP_MESSAGE_H__
|
||||
// Protocol Buffers - Google's data interchange format
|
||||
// Copyright 2008 Google Inc. All rights reserved.
|
||||
// http://code.google.com/p/protobuf/
|
||||
//
|
||||
// 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: kenton@google.com (Kenton Varda)
|
||||
// Based on original Protocol Buffers design by
|
||||
// Sanjay Ghemawat, Jeff Dean, and others.
|
||||
|
||||
#ifndef GOOGLE_PROTOBUF_COMPILER_CPP_MESSAGE_H__
|
||||
#define GOOGLE_PROTOBUF_COMPILER_CPP_MESSAGE_H__
|
||||
|
||||
#include <string>
|
||||
#include <google/protobuf/stubs/common.h>
|
||||
#include <google/protobuf/compiler/cpp/cpp_field.h>
|
||||
|
||||
namespace google {
|
||||
namespace protobuf {
|
||||
namespace io {
|
||||
class Printer; // printer.h
|
||||
}
|
||||
}
|
||||
|
||||
namespace protobuf {
|
||||
namespace compiler {
|
||||
namespace cpp {
|
||||
|
||||
class EnumGenerator; // enum.h
|
||||
class ExtensionGenerator; // extension.h
|
||||
|
||||
class MessageGenerator {
|
||||
public:
|
||||
// See generator.cc for the meaning of dllexport_decl.
|
||||
explicit MessageGenerator(const Descriptor* descriptor,
|
||||
const string& dllexport_decl);
|
||||
~MessageGenerator();
|
||||
|
||||
// Header stuff.
|
||||
|
||||
// Generate foward declarations for this class and all its nested types.
|
||||
void GenerateForwardDeclaration(io::Printer* printer);
|
||||
|
||||
// Generate definitions of all nested enums (must come before class
|
||||
// definitions because those classes use the enums definitions).
|
||||
void GenerateEnumDefinitions(io::Printer* printer);
|
||||
|
||||
// Generate specializations of GetEnumDescriptor<MyEnum>().
|
||||
// Precondition: in ::google::protobuf namespace.
|
||||
void GenerateGetEnumDescriptorSpecializations(io::Printer* printer);
|
||||
|
||||
// Generate definitions for this class and all its nested types.
|
||||
void GenerateClassDefinition(io::Printer* printer);
|
||||
|
||||
// Generate definitions of inline methods (placed at the end of the header
|
||||
// file).
|
||||
void GenerateInlineMethods(io::Printer* printer);
|
||||
|
||||
// Source file stuff.
|
||||
|
||||
// Generate code which declares all the global descriptor pointers which
|
||||
// will be initialized by the methods below.
|
||||
void GenerateDescriptorDeclarations(io::Printer* printer);
|
||||
|
||||
// Generate code that initializes the global variable storing the message's
|
||||
// descriptor.
|
||||
void GenerateDescriptorInitializer(io::Printer* printer, int index);
|
||||
|
||||
// Generate code that calls MessageFactory::InternalRegisterGeneratedMessage()
|
||||
// for all types.
|
||||
void GenerateTypeRegistrations(io::Printer* printer);
|
||||
|
||||
// Generates code that allocates the message's default instance.
|
||||
void GenerateDefaultInstanceAllocator(io::Printer* printer);
|
||||
|
||||
// Generates code that initializes the message's default instance. This
|
||||
// is separate from allocating because all default instances must be
|
||||
// allocated before any can be initialized.
|
||||
void GenerateDefaultInstanceInitializer(io::Printer* printer);
|
||||
|
||||
// Generates code that should be run when ShutdownProtobufLibrary() is called,
|
||||
// to delete all dynamically-allocated objects.
|
||||
void GenerateShutdownCode(io::Printer* printer);
|
||||
|
||||
// Generate all non-inline methods for this class.
|
||||
void GenerateClassMethods(io::Printer* printer);
|
||||
|
||||
private:
|
||||
// Generate declarations and definitions of accessors for fields.
|
||||
void GenerateFieldAccessorDeclarations(io::Printer* printer);
|
||||
void GenerateFieldAccessorDefinitions(io::Printer* printer);
|
||||
|
||||
// Generate the field offsets array.
|
||||
void GenerateOffsets(io::Printer* printer);
|
||||
|
||||
// Generate constructors and destructor.
|
||||
void GenerateStructors(io::Printer* printer);
|
||||
|
||||
// The compiler typically generates multiple copies of each constructor and
|
||||
// destructor: http://gcc.gnu.org/bugs.html#nonbugs_cxx
|
||||
// Placing common code in a separate method reduces the generated code size.
|
||||
//
|
||||
// Generate the shared constructor code.
|
||||
void GenerateSharedConstructorCode(io::Printer* printer);
|
||||
// Generate the shared destructor code.
|
||||
void GenerateSharedDestructorCode(io::Printer* printer);
|
||||
|
||||
// Generate standard Message methods.
|
||||
void GenerateClear(io::Printer* printer);
|
||||
void GenerateMergeFromCodedStream(io::Printer* printer);
|
||||
void GenerateSerializeWithCachedSizes(io::Printer* printer);
|
||||
void GenerateSerializeWithCachedSizesToArray(io::Printer* printer);
|
||||
void GenerateSerializeWithCachedSizesBody(io::Printer* printer,
|
||||
bool to_array);
|
||||
void GenerateByteSize(io::Printer* printer);
|
||||
void GenerateMergeFrom(io::Printer* printer);
|
||||
void GenerateCopyFrom(io::Printer* printer);
|
||||
void GenerateSwap(io::Printer* printer);
|
||||
void GenerateIsInitialized(io::Printer* printer);
|
||||
|
||||
// Helpers for GenerateSerializeWithCachedSizes().
|
||||
void GenerateSerializeOneField(io::Printer* printer,
|
||||
const FieldDescriptor* field,
|
||||
bool unbounded);
|
||||
void GenerateSerializeOneExtensionRange(
|
||||
io::Printer* printer, const Descriptor::ExtensionRange* range,
|
||||
bool unbounded);
|
||||
|
||||
|
||||
const Descriptor* descriptor_;
|
||||
string classname_;
|
||||
string dllexport_decl_;
|
||||
FieldGeneratorMap field_generators_;
|
||||
scoped_array<scoped_ptr<MessageGenerator> > nested_generators_;
|
||||
scoped_array<scoped_ptr<EnumGenerator> > enum_generators_;
|
||||
scoped_array<scoped_ptr<ExtensionGenerator> > extension_generators_;
|
||||
|
||||
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(MessageGenerator);
|
||||
};
|
||||
|
||||
} // namespace cpp
|
||||
} // namespace compiler
|
||||
} // namespace protobuf
|
||||
|
||||
} // namespace google
|
||||
#endif // GOOGLE_PROTOBUF_COMPILER_CPP_MESSAGE_H__
|
||||
|
||||
+102
-102
@@ -1,102 +1,102 @@
|
||||
// Protocol Buffers - Google's data interchange format
|
||||
// Copyright 2008 Google Inc. All rights reserved.
|
||||
// http://code.google.com/p/protobuf/
|
||||
//
|
||||
// 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: kenton@google.com (Kenton Varda)
|
||||
// Based on original Protocol Buffers design by
|
||||
// Sanjay Ghemawat, Jeff Dean, and others.
|
||||
|
||||
#ifndef GOOGLE_PROTOBUF_COMPILER_CPP_MESSAGE_FIELD_H__
|
||||
#define GOOGLE_PROTOBUF_COMPILER_CPP_MESSAGE_FIELD_H__
|
||||
|
||||
#include <map>
|
||||
#include <string>
|
||||
#include <google/protobuf/compiler/cpp/cpp_field.h>
|
||||
|
||||
namespace google {
|
||||
namespace protobuf {
|
||||
namespace compiler {
|
||||
namespace cpp {
|
||||
|
||||
class MessageFieldGenerator : public FieldGenerator {
|
||||
public:
|
||||
explicit MessageFieldGenerator(const FieldDescriptor* descriptor);
|
||||
~MessageFieldGenerator();
|
||||
|
||||
// implements FieldGenerator ---------------------------------------
|
||||
void GeneratePrivateMembers(io::Printer* printer) const;
|
||||
void GenerateAccessorDeclarations(io::Printer* printer) const;
|
||||
void GenerateInlineAccessorDefinitions(io::Printer* printer) const;
|
||||
void GenerateClearingCode(io::Printer* printer) const;
|
||||
void GenerateMergingCode(io::Printer* printer) const;
|
||||
void GenerateSwappingCode(io::Printer* printer) const;
|
||||
void GenerateConstructorCode(io::Printer* printer) const;
|
||||
void GenerateMergeFromCodedStream(io::Printer* printer) const;
|
||||
void GenerateSerializeWithCachedSizes(io::Printer* printer) const;
|
||||
void GenerateSerializeWithCachedSizesToArray(io::Printer* printer) const;
|
||||
void GenerateByteSize(io::Printer* printer) const;
|
||||
|
||||
private:
|
||||
const FieldDescriptor* descriptor_;
|
||||
map<string, string> variables_;
|
||||
|
||||
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(MessageFieldGenerator);
|
||||
};
|
||||
|
||||
class RepeatedMessageFieldGenerator : public FieldGenerator {
|
||||
public:
|
||||
explicit RepeatedMessageFieldGenerator(const FieldDescriptor* descriptor);
|
||||
~RepeatedMessageFieldGenerator();
|
||||
|
||||
// implements FieldGenerator ---------------------------------------
|
||||
void GeneratePrivateMembers(io::Printer* printer) const;
|
||||
void GenerateAccessorDeclarations(io::Printer* printer) const;
|
||||
void GenerateInlineAccessorDefinitions(io::Printer* printer) const;
|
||||
void GenerateClearingCode(io::Printer* printer) const;
|
||||
void GenerateMergingCode(io::Printer* printer) const;
|
||||
void GenerateSwappingCode(io::Printer* printer) const;
|
||||
void GenerateConstructorCode(io::Printer* printer) const;
|
||||
void GenerateMergeFromCodedStream(io::Printer* printer) const;
|
||||
void GenerateSerializeWithCachedSizes(io::Printer* printer) const;
|
||||
void GenerateSerializeWithCachedSizesToArray(io::Printer* printer) const;
|
||||
void GenerateByteSize(io::Printer* printer) const;
|
||||
|
||||
private:
|
||||
const FieldDescriptor* descriptor_;
|
||||
map<string, string> variables_;
|
||||
|
||||
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(RepeatedMessageFieldGenerator);
|
||||
};
|
||||
|
||||
} // namespace cpp
|
||||
} // namespace compiler
|
||||
} // namespace protobuf
|
||||
|
||||
} // namespace google
|
||||
#endif // GOOGLE_PROTOBUF_COMPILER_CPP_MESSAGE_FIELD_H__
|
||||
// Protocol Buffers - Google's data interchange format
|
||||
// Copyright 2008 Google Inc. All rights reserved.
|
||||
// http://code.google.com/p/protobuf/
|
||||
//
|
||||
// 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: kenton@google.com (Kenton Varda)
|
||||
// Based on original Protocol Buffers design by
|
||||
// Sanjay Ghemawat, Jeff Dean, and others.
|
||||
|
||||
#ifndef GOOGLE_PROTOBUF_COMPILER_CPP_MESSAGE_FIELD_H__
|
||||
#define GOOGLE_PROTOBUF_COMPILER_CPP_MESSAGE_FIELD_H__
|
||||
|
||||
#include <map>
|
||||
#include <string>
|
||||
#include <google/protobuf/compiler/cpp/cpp_field.h>
|
||||
|
||||
namespace google {
|
||||
namespace protobuf {
|
||||
namespace compiler {
|
||||
namespace cpp {
|
||||
|
||||
class MessageFieldGenerator : public FieldGenerator {
|
||||
public:
|
||||
explicit MessageFieldGenerator(const FieldDescriptor* descriptor);
|
||||
~MessageFieldGenerator();
|
||||
|
||||
// implements FieldGenerator ---------------------------------------
|
||||
void GeneratePrivateMembers(io::Printer* printer) const;
|
||||
void GenerateAccessorDeclarations(io::Printer* printer) const;
|
||||
void GenerateInlineAccessorDefinitions(io::Printer* printer) const;
|
||||
void GenerateClearingCode(io::Printer* printer) const;
|
||||
void GenerateMergingCode(io::Printer* printer) const;
|
||||
void GenerateSwappingCode(io::Printer* printer) const;
|
||||
void GenerateConstructorCode(io::Printer* printer) const;
|
||||
void GenerateMergeFromCodedStream(io::Printer* printer) const;
|
||||
void GenerateSerializeWithCachedSizes(io::Printer* printer) const;
|
||||
void GenerateSerializeWithCachedSizesToArray(io::Printer* printer) const;
|
||||
void GenerateByteSize(io::Printer* printer) const;
|
||||
|
||||
private:
|
||||
const FieldDescriptor* descriptor_;
|
||||
map<string, string> variables_;
|
||||
|
||||
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(MessageFieldGenerator);
|
||||
};
|
||||
|
||||
class RepeatedMessageFieldGenerator : public FieldGenerator {
|
||||
public:
|
||||
explicit RepeatedMessageFieldGenerator(const FieldDescriptor* descriptor);
|
||||
~RepeatedMessageFieldGenerator();
|
||||
|
||||
// implements FieldGenerator ---------------------------------------
|
||||
void GeneratePrivateMembers(io::Printer* printer) const;
|
||||
void GenerateAccessorDeclarations(io::Printer* printer) const;
|
||||
void GenerateInlineAccessorDefinitions(io::Printer* printer) const;
|
||||
void GenerateClearingCode(io::Printer* printer) const;
|
||||
void GenerateMergingCode(io::Printer* printer) const;
|
||||
void GenerateSwappingCode(io::Printer* printer) const;
|
||||
void GenerateConstructorCode(io::Printer* printer) const;
|
||||
void GenerateMergeFromCodedStream(io::Printer* printer) const;
|
||||
void GenerateSerializeWithCachedSizes(io::Printer* printer) const;
|
||||
void GenerateSerializeWithCachedSizesToArray(io::Printer* printer) const;
|
||||
void GenerateByteSize(io::Printer* printer) const;
|
||||
|
||||
private:
|
||||
const FieldDescriptor* descriptor_;
|
||||
map<string, string> variables_;
|
||||
|
||||
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(RepeatedMessageFieldGenerator);
|
||||
};
|
||||
|
||||
} // namespace cpp
|
||||
} // namespace compiler
|
||||
} // namespace protobuf
|
||||
|
||||
} // namespace google
|
||||
#endif // GOOGLE_PROTOBUF_COMPILER_CPP_MESSAGE_FIELD_H__
|
||||
|
||||
+103
-103
@@ -1,103 +1,103 @@
|
||||
// Protocol Buffers - Google's data interchange format
|
||||
// Copyright 2008 Google Inc. All rights reserved.
|
||||
// http://code.google.com/p/protobuf/
|
||||
//
|
||||
// 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: kenton@google.com (Kenton Varda)
|
||||
// Based on original Protocol Buffers design by
|
||||
// Sanjay Ghemawat, Jeff Dean, and others.
|
||||
|
||||
#ifndef GOOGLE_PROTOBUF_COMPILER_CPP_PRIMITIVE_FIELD_H__
|
||||
#define GOOGLE_PROTOBUF_COMPILER_CPP_PRIMITIVE_FIELD_H__
|
||||
|
||||
#include <map>
|
||||
#include <string>
|
||||
#include <google/protobuf/compiler/cpp/cpp_field.h>
|
||||
|
||||
namespace google {
|
||||
namespace protobuf {
|
||||
namespace compiler {
|
||||
namespace cpp {
|
||||
|
||||
class PrimitiveFieldGenerator : public FieldGenerator {
|
||||
public:
|
||||
explicit PrimitiveFieldGenerator(const FieldDescriptor* descriptor);
|
||||
~PrimitiveFieldGenerator();
|
||||
|
||||
// implements FieldGenerator ---------------------------------------
|
||||
void GeneratePrivateMembers(io::Printer* printer) const;
|
||||
void GenerateAccessorDeclarations(io::Printer* printer) const;
|
||||
void GenerateInlineAccessorDefinitions(io::Printer* printer) const;
|
||||
void GenerateClearingCode(io::Printer* printer) const;
|
||||
void GenerateMergingCode(io::Printer* printer) const;
|
||||
void GenerateSwappingCode(io::Printer* printer) const;
|
||||
void GenerateConstructorCode(io::Printer* printer) const;
|
||||
void GenerateMergeFromCodedStream(io::Printer* printer) const;
|
||||
void GenerateSerializeWithCachedSizes(io::Printer* printer) const;
|
||||
void GenerateSerializeWithCachedSizesToArray(io::Printer* printer) const;
|
||||
void GenerateByteSize(io::Printer* printer) const;
|
||||
|
||||
private:
|
||||
const FieldDescriptor* descriptor_;
|
||||
map<string, string> variables_;
|
||||
|
||||
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(PrimitiveFieldGenerator);
|
||||
};
|
||||
|
||||
class RepeatedPrimitiveFieldGenerator : public FieldGenerator {
|
||||
public:
|
||||
explicit RepeatedPrimitiveFieldGenerator(const FieldDescriptor* descriptor);
|
||||
~RepeatedPrimitiveFieldGenerator();
|
||||
|
||||
// implements FieldGenerator ---------------------------------------
|
||||
void GeneratePrivateMembers(io::Printer* printer) const;
|
||||
void GenerateAccessorDeclarations(io::Printer* printer) const;
|
||||
void GenerateInlineAccessorDefinitions(io::Printer* printer) const;
|
||||
void GenerateClearingCode(io::Printer* printer) const;
|
||||
void GenerateMergingCode(io::Printer* printer) const;
|
||||
void GenerateSwappingCode(io::Printer* printer) const;
|
||||
void GenerateConstructorCode(io::Printer* printer) const;
|
||||
void GenerateMergeFromCodedStream(io::Printer* printer) const;
|
||||
void GenerateMergeFromCodedStreamWithPacking(io::Printer* printer) const;
|
||||
void GenerateSerializeWithCachedSizes(io::Printer* printer) const;
|
||||
void GenerateSerializeWithCachedSizesToArray(io::Printer* printer) const;
|
||||
void GenerateByteSize(io::Printer* printer) const;
|
||||
|
||||
private:
|
||||
const FieldDescriptor* descriptor_;
|
||||
map<string, string> variables_;
|
||||
|
||||
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(RepeatedPrimitiveFieldGenerator);
|
||||
};
|
||||
|
||||
} // namespace cpp
|
||||
} // namespace compiler
|
||||
} // namespace protobuf
|
||||
|
||||
} // namespace google
|
||||
#endif // GOOGLE_PROTOBUF_COMPILER_CPP_PRIMITIVE_FIELD_H__
|
||||
// Protocol Buffers - Google's data interchange format
|
||||
// Copyright 2008 Google Inc. All rights reserved.
|
||||
// http://code.google.com/p/protobuf/
|
||||
//
|
||||
// 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: kenton@google.com (Kenton Varda)
|
||||
// Based on original Protocol Buffers design by
|
||||
// Sanjay Ghemawat, Jeff Dean, and others.
|
||||
|
||||
#ifndef GOOGLE_PROTOBUF_COMPILER_CPP_PRIMITIVE_FIELD_H__
|
||||
#define GOOGLE_PROTOBUF_COMPILER_CPP_PRIMITIVE_FIELD_H__
|
||||
|
||||
#include <map>
|
||||
#include <string>
|
||||
#include <google/protobuf/compiler/cpp/cpp_field.h>
|
||||
|
||||
namespace google {
|
||||
namespace protobuf {
|
||||
namespace compiler {
|
||||
namespace cpp {
|
||||
|
||||
class PrimitiveFieldGenerator : public FieldGenerator {
|
||||
public:
|
||||
explicit PrimitiveFieldGenerator(const FieldDescriptor* descriptor);
|
||||
~PrimitiveFieldGenerator();
|
||||
|
||||
// implements FieldGenerator ---------------------------------------
|
||||
void GeneratePrivateMembers(io::Printer* printer) const;
|
||||
void GenerateAccessorDeclarations(io::Printer* printer) const;
|
||||
void GenerateInlineAccessorDefinitions(io::Printer* printer) const;
|
||||
void GenerateClearingCode(io::Printer* printer) const;
|
||||
void GenerateMergingCode(io::Printer* printer) const;
|
||||
void GenerateSwappingCode(io::Printer* printer) const;
|
||||
void GenerateConstructorCode(io::Printer* printer) const;
|
||||
void GenerateMergeFromCodedStream(io::Printer* printer) const;
|
||||
void GenerateSerializeWithCachedSizes(io::Printer* printer) const;
|
||||
void GenerateSerializeWithCachedSizesToArray(io::Printer* printer) const;
|
||||
void GenerateByteSize(io::Printer* printer) const;
|
||||
|
||||
private:
|
||||
const FieldDescriptor* descriptor_;
|
||||
map<string, string> variables_;
|
||||
|
||||
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(PrimitiveFieldGenerator);
|
||||
};
|
||||
|
||||
class RepeatedPrimitiveFieldGenerator : public FieldGenerator {
|
||||
public:
|
||||
explicit RepeatedPrimitiveFieldGenerator(const FieldDescriptor* descriptor);
|
||||
~RepeatedPrimitiveFieldGenerator();
|
||||
|
||||
// implements FieldGenerator ---------------------------------------
|
||||
void GeneratePrivateMembers(io::Printer* printer) const;
|
||||
void GenerateAccessorDeclarations(io::Printer* printer) const;
|
||||
void GenerateInlineAccessorDefinitions(io::Printer* printer) const;
|
||||
void GenerateClearingCode(io::Printer* printer) const;
|
||||
void GenerateMergingCode(io::Printer* printer) const;
|
||||
void GenerateSwappingCode(io::Printer* printer) const;
|
||||
void GenerateConstructorCode(io::Printer* printer) const;
|
||||
void GenerateMergeFromCodedStream(io::Printer* printer) const;
|
||||
void GenerateMergeFromCodedStreamWithPacking(io::Printer* printer) const;
|
||||
void GenerateSerializeWithCachedSizes(io::Printer* printer) const;
|
||||
void GenerateSerializeWithCachedSizesToArray(io::Printer* printer) const;
|
||||
void GenerateByteSize(io::Printer* printer) const;
|
||||
|
||||
private:
|
||||
const FieldDescriptor* descriptor_;
|
||||
map<string, string> variables_;
|
||||
|
||||
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(RepeatedPrimitiveFieldGenerator);
|
||||
};
|
||||
|
||||
} // namespace cpp
|
||||
} // namespace compiler
|
||||
} // namespace protobuf
|
||||
|
||||
} // namespace google
|
||||
#endif // GOOGLE_PROTOBUF_COMPILER_CPP_PRIMITIVE_FIELD_H__
|
||||
|
||||
+118
-118
@@ -1,118 +1,118 @@
|
||||
// Protocol Buffers - Google's data interchange format
|
||||
// Copyright 2008 Google Inc. All rights reserved.
|
||||
// http://code.google.com/p/protobuf/
|
||||
//
|
||||
// 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: kenton@google.com (Kenton Varda)
|
||||
// Based on original Protocol Buffers design by
|
||||
// Sanjay Ghemawat, Jeff Dean, and others.
|
||||
|
||||
#ifndef GOOGLE_PROTOBUF_COMPILER_CPP_SERVICE_H__
|
||||
#define GOOGLE_PROTOBUF_COMPILER_CPP_SERVICE_H__
|
||||
|
||||
#include <map>
|
||||
#include <string>
|
||||
#include <google/protobuf/stubs/common.h>
|
||||
#include <google/protobuf/descriptor.h>
|
||||
|
||||
namespace google {
|
||||
namespace protobuf {
|
||||
namespace io {
|
||||
class Printer; // printer.h
|
||||
}
|
||||
}
|
||||
|
||||
namespace protobuf {
|
||||
namespace compiler {
|
||||
namespace cpp {
|
||||
|
||||
class ServiceGenerator {
|
||||
public:
|
||||
// See generator.cc for the meaning of dllexport_decl.
|
||||
explicit ServiceGenerator(const ServiceDescriptor* descriptor,
|
||||
const string& dllexport_decl);
|
||||
~ServiceGenerator();
|
||||
|
||||
// Header stuff.
|
||||
|
||||
// Generate the class definitions for the service's interface and the
|
||||
// stub implementation.
|
||||
void GenerateDeclarations(io::Printer* printer);
|
||||
|
||||
// Source file stuff.
|
||||
|
||||
// Generate code that initializes the global variable storing the service's
|
||||
// descriptor.
|
||||
void GenerateDescriptorInitializer(io::Printer* printer, int index);
|
||||
|
||||
// Generate implementations of everything declared by GenerateDeclarations().
|
||||
void GenerateImplementation(io::Printer* printer);
|
||||
|
||||
private:
|
||||
enum RequestOrResponse { REQUEST, RESPONSE };
|
||||
enum VirtualOrNon { VIRTUAL, NON_VIRTUAL };
|
||||
|
||||
// Header stuff.
|
||||
|
||||
// Generate the service abstract interface.
|
||||
void GenerateInterface(io::Printer* printer);
|
||||
|
||||
// Generate the stub class definition.
|
||||
void GenerateStubDefinition(io::Printer* printer);
|
||||
|
||||
// Prints signatures for all methods in the
|
||||
void GenerateMethodSignatures(VirtualOrNon virtual_or_non,
|
||||
io::Printer* printer);
|
||||
|
||||
// Source file stuff.
|
||||
|
||||
// Generate the default implementations of the service methods, which
|
||||
// produce a "not implemented" error.
|
||||
void GenerateNotImplementedMethods(io::Printer* printer);
|
||||
|
||||
// Generate the CallMethod() method of the service.
|
||||
void GenerateCallMethod(io::Printer* printer);
|
||||
|
||||
// Generate the Get{Request,Response}Prototype() methods.
|
||||
void GenerateGetPrototype(RequestOrResponse which, io::Printer* printer);
|
||||
|
||||
// Generate the stub's implementations of the service methods.
|
||||
void GenerateStubMethods(io::Printer* printer);
|
||||
|
||||
const ServiceDescriptor* descriptor_;
|
||||
map<string, string> vars_;
|
||||
|
||||
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(ServiceGenerator);
|
||||
};
|
||||
|
||||
} // namespace cpp
|
||||
} // namespace compiler
|
||||
} // namespace protobuf
|
||||
|
||||
} // namespace google
|
||||
#endif // GOOGLE_PROTOBUF_COMPILER_CPP_SERVICE_H__
|
||||
// Protocol Buffers - Google's data interchange format
|
||||
// Copyright 2008 Google Inc. All rights reserved.
|
||||
// http://code.google.com/p/protobuf/
|
||||
//
|
||||
// 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: kenton@google.com (Kenton Varda)
|
||||
// Based on original Protocol Buffers design by
|
||||
// Sanjay Ghemawat, Jeff Dean, and others.
|
||||
|
||||
#ifndef GOOGLE_PROTOBUF_COMPILER_CPP_SERVICE_H__
|
||||
#define GOOGLE_PROTOBUF_COMPILER_CPP_SERVICE_H__
|
||||
|
||||
#include <map>
|
||||
#include <string>
|
||||
#include <google/protobuf/stubs/common.h>
|
||||
#include <google/protobuf/descriptor.h>
|
||||
|
||||
namespace google {
|
||||
namespace protobuf {
|
||||
namespace io {
|
||||
class Printer; // printer.h
|
||||
}
|
||||
}
|
||||
|
||||
namespace protobuf {
|
||||
namespace compiler {
|
||||
namespace cpp {
|
||||
|
||||
class ServiceGenerator {
|
||||
public:
|
||||
// See generator.cc for the meaning of dllexport_decl.
|
||||
explicit ServiceGenerator(const ServiceDescriptor* descriptor,
|
||||
const string& dllexport_decl);
|
||||
~ServiceGenerator();
|
||||
|
||||
// Header stuff.
|
||||
|
||||
// Generate the class definitions for the service's interface and the
|
||||
// stub implementation.
|
||||
void GenerateDeclarations(io::Printer* printer);
|
||||
|
||||
// Source file stuff.
|
||||
|
||||
// Generate code that initializes the global variable storing the service's
|
||||
// descriptor.
|
||||
void GenerateDescriptorInitializer(io::Printer* printer, int index);
|
||||
|
||||
// Generate implementations of everything declared by GenerateDeclarations().
|
||||
void GenerateImplementation(io::Printer* printer);
|
||||
|
||||
private:
|
||||
enum RequestOrResponse { REQUEST, RESPONSE };
|
||||
enum VirtualOrNon { VIRTUAL, NON_VIRTUAL };
|
||||
|
||||
// Header stuff.
|
||||
|
||||
// Generate the service abstract interface.
|
||||
void GenerateInterface(io::Printer* printer);
|
||||
|
||||
// Generate the stub class definition.
|
||||
void GenerateStubDefinition(io::Printer* printer);
|
||||
|
||||
// Prints signatures for all methods in the
|
||||
void GenerateMethodSignatures(VirtualOrNon virtual_or_non,
|
||||
io::Printer* printer);
|
||||
|
||||
// Source file stuff.
|
||||
|
||||
// Generate the default implementations of the service methods, which
|
||||
// produce a "not implemented" error.
|
||||
void GenerateNotImplementedMethods(io::Printer* printer);
|
||||
|
||||
// Generate the CallMethod() method of the service.
|
||||
void GenerateCallMethod(io::Printer* printer);
|
||||
|
||||
// Generate the Get{Request,Response}Prototype() methods.
|
||||
void GenerateGetPrototype(RequestOrResponse which, io::Printer* printer);
|
||||
|
||||
// Generate the stub's implementations of the service methods.
|
||||
void GenerateStubMethods(io::Printer* printer);
|
||||
|
||||
const ServiceDescriptor* descriptor_;
|
||||
map<string, string> vars_;
|
||||
|
||||
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(ServiceGenerator);
|
||||
};
|
||||
|
||||
} // namespace cpp
|
||||
} // namespace compiler
|
||||
} // namespace protobuf
|
||||
|
||||
} // namespace google
|
||||
#endif // GOOGLE_PROTOBUF_COMPILER_CPP_SERVICE_H__
|
||||
|
||||
+104
-104
@@ -1,104 +1,104 @@
|
||||
// Protocol Buffers - Google's data interchange format
|
||||
// Copyright 2008 Google Inc. All rights reserved.
|
||||
// http://code.google.com/p/protobuf/
|
||||
//
|
||||
// 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: kenton@google.com (Kenton Varda)
|
||||
// Based on original Protocol Buffers design by
|
||||
// Sanjay Ghemawat, Jeff Dean, and others.
|
||||
|
||||
#ifndef GOOGLE_PROTOBUF_COMPILER_CPP_STRING_FIELD_H__
|
||||
#define GOOGLE_PROTOBUF_COMPILER_CPP_STRING_FIELD_H__
|
||||
|
||||
#include <map>
|
||||
#include <string>
|
||||
#include <google/protobuf/compiler/cpp/cpp_field.h>
|
||||
|
||||
namespace google {
|
||||
namespace protobuf {
|
||||
namespace compiler {
|
||||
namespace cpp {
|
||||
|
||||
class StringFieldGenerator : public FieldGenerator {
|
||||
public:
|
||||
explicit StringFieldGenerator(const FieldDescriptor* descriptor);
|
||||
~StringFieldGenerator();
|
||||
|
||||
// implements FieldGenerator ---------------------------------------
|
||||
void GeneratePrivateMembers(io::Printer* printer) const;
|
||||
void GenerateAccessorDeclarations(io::Printer* printer) const;
|
||||
void GenerateInlineAccessorDefinitions(io::Printer* printer) const;
|
||||
void GenerateNonInlineAccessorDefinitions(io::Printer* printer) const;
|
||||
void GenerateClearingCode(io::Printer* printer) const;
|
||||
void GenerateMergingCode(io::Printer* printer) const;
|
||||
void GenerateSwappingCode(io::Printer* printer) const;
|
||||
void GenerateConstructorCode(io::Printer* printer) const;
|
||||
void GenerateDestructorCode(io::Printer* printer) const;
|
||||
void GenerateMergeFromCodedStream(io::Printer* printer) const;
|
||||
void GenerateSerializeWithCachedSizes(io::Printer* printer) const;
|
||||
void GenerateSerializeWithCachedSizesToArray(io::Printer* printer) const;
|
||||
void GenerateByteSize(io::Printer* printer) const;
|
||||
|
||||
private:
|
||||
const FieldDescriptor* descriptor_;
|
||||
map<string, string> variables_;
|
||||
|
||||
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(StringFieldGenerator);
|
||||
};
|
||||
|
||||
class RepeatedStringFieldGenerator : public FieldGenerator {
|
||||
public:
|
||||
explicit RepeatedStringFieldGenerator(const FieldDescriptor* descriptor);
|
||||
~RepeatedStringFieldGenerator();
|
||||
|
||||
// implements FieldGenerator ---------------------------------------
|
||||
void GeneratePrivateMembers(io::Printer* printer) const;
|
||||
void GenerateAccessorDeclarations(io::Printer* printer) const;
|
||||
void GenerateInlineAccessorDefinitions(io::Printer* printer) const;
|
||||
void GenerateClearingCode(io::Printer* printer) const;
|
||||
void GenerateMergingCode(io::Printer* printer) const;
|
||||
void GenerateSwappingCode(io::Printer* printer) const;
|
||||
void GenerateConstructorCode(io::Printer* printer) const;
|
||||
void GenerateMergeFromCodedStream(io::Printer* printer) const;
|
||||
void GenerateSerializeWithCachedSizes(io::Printer* printer) const;
|
||||
void GenerateSerializeWithCachedSizesToArray(io::Printer* printer) const;
|
||||
void GenerateByteSize(io::Printer* printer) const;
|
||||
|
||||
private:
|
||||
const FieldDescriptor* descriptor_;
|
||||
map<string, string> variables_;
|
||||
|
||||
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(RepeatedStringFieldGenerator);
|
||||
};
|
||||
|
||||
} // namespace cpp
|
||||
} // namespace compiler
|
||||
} // namespace protobuf
|
||||
|
||||
} // namespace google
|
||||
#endif // GOOGLE_PROTOBUF_COMPILER_CPP_STRING_FIELD_H__
|
||||
// Protocol Buffers - Google's data interchange format
|
||||
// Copyright 2008 Google Inc. All rights reserved.
|
||||
// http://code.google.com/p/protobuf/
|
||||
//
|
||||
// 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: kenton@google.com (Kenton Varda)
|
||||
// Based on original Protocol Buffers design by
|
||||
// Sanjay Ghemawat, Jeff Dean, and others.
|
||||
|
||||
#ifndef GOOGLE_PROTOBUF_COMPILER_CPP_STRING_FIELD_H__
|
||||
#define GOOGLE_PROTOBUF_COMPILER_CPP_STRING_FIELD_H__
|
||||
|
||||
#include <map>
|
||||
#include <string>
|
||||
#include <google/protobuf/compiler/cpp/cpp_field.h>
|
||||
|
||||
namespace google {
|
||||
namespace protobuf {
|
||||
namespace compiler {
|
||||
namespace cpp {
|
||||
|
||||
class StringFieldGenerator : public FieldGenerator {
|
||||
public:
|
||||
explicit StringFieldGenerator(const FieldDescriptor* descriptor);
|
||||
~StringFieldGenerator();
|
||||
|
||||
// implements FieldGenerator ---------------------------------------
|
||||
void GeneratePrivateMembers(io::Printer* printer) const;
|
||||
void GenerateAccessorDeclarations(io::Printer* printer) const;
|
||||
void GenerateInlineAccessorDefinitions(io::Printer* printer) const;
|
||||
void GenerateNonInlineAccessorDefinitions(io::Printer* printer) const;
|
||||
void GenerateClearingCode(io::Printer* printer) const;
|
||||
void GenerateMergingCode(io::Printer* printer) const;
|
||||
void GenerateSwappingCode(io::Printer* printer) const;
|
||||
void GenerateConstructorCode(io::Printer* printer) const;
|
||||
void GenerateDestructorCode(io::Printer* printer) const;
|
||||
void GenerateMergeFromCodedStream(io::Printer* printer) const;
|
||||
void GenerateSerializeWithCachedSizes(io::Printer* printer) const;
|
||||
void GenerateSerializeWithCachedSizesToArray(io::Printer* printer) const;
|
||||
void GenerateByteSize(io::Printer* printer) const;
|
||||
|
||||
private:
|
||||
const FieldDescriptor* descriptor_;
|
||||
map<string, string> variables_;
|
||||
|
||||
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(StringFieldGenerator);
|
||||
};
|
||||
|
||||
class RepeatedStringFieldGenerator : public FieldGenerator {
|
||||
public:
|
||||
explicit RepeatedStringFieldGenerator(const FieldDescriptor* descriptor);
|
||||
~RepeatedStringFieldGenerator();
|
||||
|
||||
// implements FieldGenerator ---------------------------------------
|
||||
void GeneratePrivateMembers(io::Printer* printer) const;
|
||||
void GenerateAccessorDeclarations(io::Printer* printer) const;
|
||||
void GenerateInlineAccessorDefinitions(io::Printer* printer) const;
|
||||
void GenerateClearingCode(io::Printer* printer) const;
|
||||
void GenerateMergingCode(io::Printer* printer) const;
|
||||
void GenerateSwappingCode(io::Printer* printer) const;
|
||||
void GenerateConstructorCode(io::Printer* printer) const;
|
||||
void GenerateMergeFromCodedStream(io::Printer* printer) const;
|
||||
void GenerateSerializeWithCachedSizes(io::Printer* printer) const;
|
||||
void GenerateSerializeWithCachedSizesToArray(io::Printer* printer) const;
|
||||
void GenerateByteSize(io::Printer* printer) const;
|
||||
|
||||
private:
|
||||
const FieldDescriptor* descriptor_;
|
||||
map<string, string> variables_;
|
||||
|
||||
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(RepeatedStringFieldGenerator);
|
||||
};
|
||||
|
||||
} // namespace cpp
|
||||
} // namespace compiler
|
||||
} // namespace protobuf
|
||||
|
||||
} // namespace google
|
||||
#endif // GOOGLE_PROTOBUF_COMPILER_CPP_STRING_FIELD_H__
|
||||
|
||||
+303
-303
@@ -1,303 +1,303 @@
|
||||
// Protocol Buffers - Google's data interchange format
|
||||
// Copyright 2008 Google Inc. All rights reserved.
|
||||
// http://code.google.com/p/protobuf/
|
||||
//
|
||||
// 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: kenton@google.com (Kenton Varda)
|
||||
// Based on original Protocol Buffers design by
|
||||
// Sanjay Ghemawat, Jeff Dean, and others.
|
||||
//
|
||||
// This file is the public interface to the .proto file parser.
|
||||
|
||||
#ifndef GOOGLE_PROTOBUF_COMPILER_IMPORTER_H__
|
||||
#define GOOGLE_PROTOBUF_COMPILER_IMPORTER_H__
|
||||
|
||||
#include <string>
|
||||
#include <vector>
|
||||
#include <set>
|
||||
#include <utility>
|
||||
#include <google/protobuf/descriptor.h>
|
||||
#include <google/protobuf/descriptor_database.h>
|
||||
#include <google/protobuf/compiler/parser.h>
|
||||
|
||||
namespace google {
|
||||
namespace protobuf {
|
||||
|
||||
namespace io { class ZeroCopyInputStream; }
|
||||
|
||||
namespace compiler {
|
||||
|
||||
// Defined in this file.
|
||||
class Importer;
|
||||
class MultiFileErrorCollector;
|
||||
class SourceTree;
|
||||
class DiskSourceTree;
|
||||
|
||||
// TODO(kenton): Move all SourceTree stuff to a separate file?
|
||||
|
||||
// An implementation of DescriptorDatabase which loads files from a SourceTree
|
||||
// and parses them.
|
||||
//
|
||||
// Note: This class is not thread-safe since it maintains a table of source
|
||||
// code locations for error reporting. However, when a DescriptorPool wraps
|
||||
// a DescriptorDatabase, it uses mutex locking to make sure only one method
|
||||
// of the database is called at a time, even if the DescriptorPool is used
|
||||
// from multiple threads. Therefore, there is only a problem if you create
|
||||
// multiple DescriptorPools wrapping the same SourceTreeDescriptorDatabase
|
||||
// and use them from multiple threads.
|
||||
//
|
||||
// Note: This class does not implement FindFileContainingSymbol() or
|
||||
// FindFileContainingExtension(); these will always return false.
|
||||
class LIBPROTOBUF_EXPORT SourceTreeDescriptorDatabase : public DescriptorDatabase {
|
||||
public:
|
||||
SourceTreeDescriptorDatabase(SourceTree* source_tree);
|
||||
~SourceTreeDescriptorDatabase();
|
||||
|
||||
// Instructs the SourceTreeDescriptorDatabase to report any parse errors
|
||||
// to the given MultiFileErrorCollector. This should be called before
|
||||
// parsing. error_collector must remain valid until either this method
|
||||
// is called again or the SourceTreeDescriptorDatabase is destroyed.
|
||||
void RecordErrorsTo(MultiFileErrorCollector* error_collector) {
|
||||
error_collector_ = error_collector;
|
||||
}
|
||||
|
||||
// Gets a DescriptorPool::ErrorCollector which records errors to the
|
||||
// MultiFileErrorCollector specified with RecordErrorsTo(). This collector
|
||||
// has the ability to determine exact line and column numbers of errors
|
||||
// from the information given to it by the DescriptorPool.
|
||||
DescriptorPool::ErrorCollector* GetValidationErrorCollector() {
|
||||
using_validation_error_collector_ = true;
|
||||
return &validation_error_collector_;
|
||||
}
|
||||
|
||||
// implements DescriptorDatabase -----------------------------------
|
||||
bool FindFileByName(const string& filename, FileDescriptorProto* output);
|
||||
bool FindFileContainingSymbol(const string& symbol_name,
|
||||
FileDescriptorProto* output);
|
||||
bool FindFileContainingExtension(const string& containing_type,
|
||||
int field_number,
|
||||
FileDescriptorProto* output);
|
||||
|
||||
private:
|
||||
class SingleFileErrorCollector;
|
||||
|
||||
SourceTree* source_tree_;
|
||||
MultiFileErrorCollector* error_collector_;
|
||||
|
||||
class LIBPROTOBUF_EXPORT ValidationErrorCollector : public DescriptorPool::ErrorCollector {
|
||||
public:
|
||||
ValidationErrorCollector(SourceTreeDescriptorDatabase* owner);
|
||||
~ValidationErrorCollector();
|
||||
|
||||
// implements ErrorCollector ---------------------------------------
|
||||
void AddError(const string& filename,
|
||||
const string& element_name,
|
||||
const Message* descriptor,
|
||||
ErrorLocation location,
|
||||
const string& message);
|
||||
|
||||
private:
|
||||
SourceTreeDescriptorDatabase* owner_;
|
||||
};
|
||||
friend class ValidationErrorCollector;
|
||||
|
||||
bool using_validation_error_collector_;
|
||||
SourceLocationTable source_locations_;
|
||||
ValidationErrorCollector validation_error_collector_;
|
||||
};
|
||||
|
||||
// Simple interface for parsing .proto files. This wraps the process
|
||||
// of opening the file, parsing it with a Parser, recursively parsing all its
|
||||
// imports, and then cross-linking the results to produce a FileDescriptor.
|
||||
//
|
||||
// This is really just a thin wrapper around SourceTreeDescriptorDatabase.
|
||||
// You may find that SourceTreeDescriptorDatabase is more flexible.
|
||||
//
|
||||
// TODO(kenton): I feel like this class is not well-named.
|
||||
class LIBPROTOBUF_EXPORT Importer {
|
||||
public:
|
||||
Importer(SourceTree* source_tree,
|
||||
MultiFileErrorCollector* error_collector);
|
||||
~Importer();
|
||||
|
||||
// Import the given file and build a FileDescriptor representing it. If
|
||||
// the file is already in the DescriptorPool, the existing FileDescriptor
|
||||
// will be returned. The FileDescriptor is property of the DescriptorPool,
|
||||
// and will remain valid until it is destroyed. If any errors occur, they
|
||||
// will be reported using the error collector and Import() will return NULL.
|
||||
//
|
||||
// A particular Importer object will only report errors for a particular
|
||||
// file once. All future attempts to import the same file will return NULL
|
||||
// without reporting any errors. The idea is that you might want to import
|
||||
// a lot of files without seeing the same errors over and over again. If
|
||||
// you want to see errors for the same files repeatedly, you can use a
|
||||
// separate Importer object to import each one (but use the same
|
||||
// DescriptorPool so that they can be cross-linked).
|
||||
const FileDescriptor* Import(const string& filename);
|
||||
|
||||
// The DescriptorPool in which all imported FileDescriptors and their
|
||||
// contents are stored.
|
||||
inline const DescriptorPool* pool() const {
|
||||
return &pool_;
|
||||
}
|
||||
|
||||
private:
|
||||
SourceTreeDescriptorDatabase database_;
|
||||
DescriptorPool pool_;
|
||||
|
||||
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(Importer);
|
||||
};
|
||||
|
||||
// If the importer encounters problems while trying to import the proto files,
|
||||
// it reports them to a MultiFileErrorCollector.
|
||||
class LIBPROTOBUF_EXPORT MultiFileErrorCollector {
|
||||
public:
|
||||
inline MultiFileErrorCollector() {}
|
||||
virtual ~MultiFileErrorCollector();
|
||||
|
||||
// Line and column numbers are zero-based. A line number of -1 indicates
|
||||
// an error with the entire file (e.g. "not found").
|
||||
virtual void AddError(const string& filename, int line, int column,
|
||||
const string& message) = 0;
|
||||
|
||||
private:
|
||||
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(MultiFileErrorCollector);
|
||||
};
|
||||
|
||||
// Abstract interface which represents a directory tree containing proto files.
|
||||
// Used by the default implementation of Importer to resolve import statements
|
||||
// Most users will probably want to use the DiskSourceTree implementation,
|
||||
// below.
|
||||
class LIBPROTOBUF_EXPORT SourceTree {
|
||||
public:
|
||||
inline SourceTree() {}
|
||||
virtual ~SourceTree();
|
||||
|
||||
// Open the given file and return a stream that reads it, or NULL if not
|
||||
// found. The caller takes ownership of the returned object. The filename
|
||||
// must be a path relative to the root of the source tree and must not
|
||||
// contain "." or ".." components.
|
||||
virtual io::ZeroCopyInputStream* Open(const string& filename) = 0;
|
||||
|
||||
private:
|
||||
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(SourceTree);
|
||||
};
|
||||
|
||||
// An implementation of SourceTree which loads files from locations on disk.
|
||||
// Multiple mappings can be set up to map locations in the DiskSourceTree to
|
||||
// locations in the physical filesystem.
|
||||
class LIBPROTOBUF_EXPORT DiskSourceTree : public SourceTree {
|
||||
public:
|
||||
DiskSourceTree();
|
||||
~DiskSourceTree();
|
||||
|
||||
// Map a path on disk to a location in the SourceTree. The path may be
|
||||
// either a file or a directory. If it is a directory, the entire tree
|
||||
// under it will be mapped to the given virtual location. To map a directory
|
||||
// to the root of the source tree, pass an empty string for virtual_path.
|
||||
//
|
||||
// If multiple mapped paths apply when opening a file, they will be searched
|
||||
// in order. For example, if you do:
|
||||
// MapPath("bar", "foo/bar");
|
||||
// MapPath("", "baz");
|
||||
// and then you do:
|
||||
// Open("bar/qux");
|
||||
// the DiskSourceTree will first try to open foo/bar/qux, then baz/bar/qux,
|
||||
// returning the first one that opens successfuly.
|
||||
//
|
||||
// disk_path may be an absolute path or relative to the current directory,
|
||||
// just like a path you'd pass to open().
|
||||
void MapPath(const string& virtual_path, const string& disk_path);
|
||||
|
||||
// Return type for DiskFileToVirtualFile().
|
||||
enum DiskFileToVirtualFileResult {
|
||||
SUCCESS,
|
||||
SHADOWED,
|
||||
CANNOT_OPEN,
|
||||
NO_MAPPING
|
||||
};
|
||||
|
||||
// Given a path to a file on disk, find a virtual path mapping to that
|
||||
// file. The first mapping created with MapPath() whose disk_path contains
|
||||
// the filename is used. However, that virtual path may not actually be
|
||||
// usable to open the given file. Possible return values are:
|
||||
// * SUCCESS: The mapping was found. *virtual_file is filled in so that
|
||||
// calling Open(*virtual_file) will open the file named by disk_file.
|
||||
// * SHADOWED: A mapping was found, but using Open() to open this virtual
|
||||
// path will end up returning some different file. This is because some
|
||||
// other mapping with a higher precedence also matches this virtual path
|
||||
// and maps it to a different file that exists on disk. *virtual_file
|
||||
// is filled in as it would be in the SUCCESS case. *shadowing_disk_file
|
||||
// is filled in with the disk path of the file which would be opened if
|
||||
// you were to call Open(*virtual_file).
|
||||
// * CANNOT_OPEN: The mapping was found and was not shadowed, but the
|
||||
// file specified cannot be opened. When this value is returned,
|
||||
// errno will indicate the reason the file cannot be opened. *virtual_file
|
||||
// will be set to the virtual path as in the SUCCESS case, even though
|
||||
// it is not useful.
|
||||
// * NO_MAPPING: Indicates that no mapping was found which contains this
|
||||
// file.
|
||||
DiskFileToVirtualFileResult
|
||||
DiskFileToVirtualFile(const string& disk_file,
|
||||
string* virtual_file,
|
||||
string* shadowing_disk_file);
|
||||
|
||||
// Given a virtual path, find the path to the file on disk.
|
||||
// Return true and update disk_file with the on-disk path if the file exists.
|
||||
// Return false and leave disk_file untouched if the file doesn't exist.
|
||||
bool VirtualFileToDiskFile(const string& virtual_file, string* disk_file);
|
||||
|
||||
// implements SourceTree -------------------------------------------
|
||||
io::ZeroCopyInputStream* Open(const string& filename);
|
||||
|
||||
private:
|
||||
struct Mapping {
|
||||
string virtual_path;
|
||||
string disk_path;
|
||||
|
||||
inline Mapping(const string& virtual_path, const string& disk_path)
|
||||
: virtual_path(virtual_path), disk_path(disk_path) {}
|
||||
};
|
||||
vector<Mapping> mappings_;
|
||||
|
||||
// Like Open(), but returns the on-disk path in disk_file if disk_file is
|
||||
// non-NULL and the file could be successfully opened.
|
||||
io::ZeroCopyInputStream* OpenVirtualFile(const string& virtual_file,
|
||||
string* disk_file);
|
||||
|
||||
// Like Open() but given the actual on-disk path.
|
||||
io::ZeroCopyInputStream* OpenDiskFile(const string& filename);
|
||||
|
||||
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(DiskSourceTree);
|
||||
};
|
||||
|
||||
} // namespace compiler
|
||||
} // namespace protobuf
|
||||
|
||||
} // namespace google
|
||||
#endif // GOOGLE_PROTOBUF_COMPILER_IMPORTER_H__
|
||||
// Protocol Buffers - Google's data interchange format
|
||||
// Copyright 2008 Google Inc. All rights reserved.
|
||||
// http://code.google.com/p/protobuf/
|
||||
//
|
||||
// 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: kenton@google.com (Kenton Varda)
|
||||
// Based on original Protocol Buffers design by
|
||||
// Sanjay Ghemawat, Jeff Dean, and others.
|
||||
//
|
||||
// This file is the public interface to the .proto file parser.
|
||||
|
||||
#ifndef GOOGLE_PROTOBUF_COMPILER_IMPORTER_H__
|
||||
#define GOOGLE_PROTOBUF_COMPILER_IMPORTER_H__
|
||||
|
||||
#include <string>
|
||||
#include <vector>
|
||||
#include <set>
|
||||
#include <utility>
|
||||
#include <google/protobuf/descriptor.h>
|
||||
#include <google/protobuf/descriptor_database.h>
|
||||
#include <google/protobuf/compiler/parser.h>
|
||||
|
||||
namespace google {
|
||||
namespace protobuf {
|
||||
|
||||
namespace io { class ZeroCopyInputStream; }
|
||||
|
||||
namespace compiler {
|
||||
|
||||
// Defined in this file.
|
||||
class Importer;
|
||||
class MultiFileErrorCollector;
|
||||
class SourceTree;
|
||||
class DiskSourceTree;
|
||||
|
||||
// TODO(kenton): Move all SourceTree stuff to a separate file?
|
||||
|
||||
// An implementation of DescriptorDatabase which loads files from a SourceTree
|
||||
// and parses them.
|
||||
//
|
||||
// Note: This class is not thread-safe since it maintains a table of source
|
||||
// code locations for error reporting. However, when a DescriptorPool wraps
|
||||
// a DescriptorDatabase, it uses mutex locking to make sure only one method
|
||||
// of the database is called at a time, even if the DescriptorPool is used
|
||||
// from multiple threads. Therefore, there is only a problem if you create
|
||||
// multiple DescriptorPools wrapping the same SourceTreeDescriptorDatabase
|
||||
// and use them from multiple threads.
|
||||
//
|
||||
// Note: This class does not implement FindFileContainingSymbol() or
|
||||
// FindFileContainingExtension(); these will always return false.
|
||||
class LIBPROTOBUF_EXPORT SourceTreeDescriptorDatabase : public DescriptorDatabase {
|
||||
public:
|
||||
SourceTreeDescriptorDatabase(SourceTree* source_tree);
|
||||
~SourceTreeDescriptorDatabase();
|
||||
|
||||
// Instructs the SourceTreeDescriptorDatabase to report any parse errors
|
||||
// to the given MultiFileErrorCollector. This should be called before
|
||||
// parsing. error_collector must remain valid until either this method
|
||||
// is called again or the SourceTreeDescriptorDatabase is destroyed.
|
||||
void RecordErrorsTo(MultiFileErrorCollector* error_collector) {
|
||||
error_collector_ = error_collector;
|
||||
}
|
||||
|
||||
// Gets a DescriptorPool::ErrorCollector which records errors to the
|
||||
// MultiFileErrorCollector specified with RecordErrorsTo(). This collector
|
||||
// has the ability to determine exact line and column numbers of errors
|
||||
// from the information given to it by the DescriptorPool.
|
||||
DescriptorPool::ErrorCollector* GetValidationErrorCollector() {
|
||||
using_validation_error_collector_ = true;
|
||||
return &validation_error_collector_;
|
||||
}
|
||||
|
||||
// implements DescriptorDatabase -----------------------------------
|
||||
bool FindFileByName(const string& filename, FileDescriptorProto* output);
|
||||
bool FindFileContainingSymbol(const string& symbol_name,
|
||||
FileDescriptorProto* output);
|
||||
bool FindFileContainingExtension(const string& containing_type,
|
||||
int field_number,
|
||||
FileDescriptorProto* output);
|
||||
|
||||
private:
|
||||
class SingleFileErrorCollector;
|
||||
|
||||
SourceTree* source_tree_;
|
||||
MultiFileErrorCollector* error_collector_;
|
||||
|
||||
class LIBPROTOBUF_EXPORT ValidationErrorCollector : public DescriptorPool::ErrorCollector {
|
||||
public:
|
||||
ValidationErrorCollector(SourceTreeDescriptorDatabase* owner);
|
||||
~ValidationErrorCollector();
|
||||
|
||||
// implements ErrorCollector ---------------------------------------
|
||||
void AddError(const string& filename,
|
||||
const string& element_name,
|
||||
const Message* descriptor,
|
||||
ErrorLocation location,
|
||||
const string& message);
|
||||
|
||||
private:
|
||||
SourceTreeDescriptorDatabase* owner_;
|
||||
};
|
||||
friend class ValidationErrorCollector;
|
||||
|
||||
bool using_validation_error_collector_;
|
||||
SourceLocationTable source_locations_;
|
||||
ValidationErrorCollector validation_error_collector_;
|
||||
};
|
||||
|
||||
// Simple interface for parsing .proto files. This wraps the process
|
||||
// of opening the file, parsing it with a Parser, recursively parsing all its
|
||||
// imports, and then cross-linking the results to produce a FileDescriptor.
|
||||
//
|
||||
// This is really just a thin wrapper around SourceTreeDescriptorDatabase.
|
||||
// You may find that SourceTreeDescriptorDatabase is more flexible.
|
||||
//
|
||||
// TODO(kenton): I feel like this class is not well-named.
|
||||
class LIBPROTOBUF_EXPORT Importer {
|
||||
public:
|
||||
Importer(SourceTree* source_tree,
|
||||
MultiFileErrorCollector* error_collector);
|
||||
~Importer();
|
||||
|
||||
// Import the given file and build a FileDescriptor representing it. If
|
||||
// the file is already in the DescriptorPool, the existing FileDescriptor
|
||||
// will be returned. The FileDescriptor is property of the DescriptorPool,
|
||||
// and will remain valid until it is destroyed. If any errors occur, they
|
||||
// will be reported using the error collector and Import() will return NULL.
|
||||
//
|
||||
// A particular Importer object will only report errors for a particular
|
||||
// file once. All future attempts to import the same file will return NULL
|
||||
// without reporting any errors. The idea is that you might want to import
|
||||
// a lot of files without seeing the same errors over and over again. If
|
||||
// you want to see errors for the same files repeatedly, you can use a
|
||||
// separate Importer object to import each one (but use the same
|
||||
// DescriptorPool so that they can be cross-linked).
|
||||
const FileDescriptor* Import(const string& filename);
|
||||
|
||||
// The DescriptorPool in which all imported FileDescriptors and their
|
||||
// contents are stored.
|
||||
inline const DescriptorPool* pool() const {
|
||||
return &pool_;
|
||||
}
|
||||
|
||||
private:
|
||||
SourceTreeDescriptorDatabase database_;
|
||||
DescriptorPool pool_;
|
||||
|
||||
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(Importer);
|
||||
};
|
||||
|
||||
// If the importer encounters problems while trying to import the proto files,
|
||||
// it reports them to a MultiFileErrorCollector.
|
||||
class LIBPROTOBUF_EXPORT MultiFileErrorCollector {
|
||||
public:
|
||||
inline MultiFileErrorCollector() {}
|
||||
virtual ~MultiFileErrorCollector();
|
||||
|
||||
// Line and column numbers are zero-based. A line number of -1 indicates
|
||||
// an error with the entire file (e.g. "not found").
|
||||
virtual void AddError(const string& filename, int line, int column,
|
||||
const string& message) = 0;
|
||||
|
||||
private:
|
||||
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(MultiFileErrorCollector);
|
||||
};
|
||||
|
||||
// Abstract interface which represents a directory tree containing proto files.
|
||||
// Used by the default implementation of Importer to resolve import statements
|
||||
// Most users will probably want to use the DiskSourceTree implementation,
|
||||
// below.
|
||||
class LIBPROTOBUF_EXPORT SourceTree {
|
||||
public:
|
||||
inline SourceTree() {}
|
||||
virtual ~SourceTree();
|
||||
|
||||
// Open the given file and return a stream that reads it, or NULL if not
|
||||
// found. The caller takes ownership of the returned object. The filename
|
||||
// must be a path relative to the root of the source tree and must not
|
||||
// contain "." or ".." components.
|
||||
virtual io::ZeroCopyInputStream* Open(const string& filename) = 0;
|
||||
|
||||
private:
|
||||
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(SourceTree);
|
||||
};
|
||||
|
||||
// An implementation of SourceTree which loads files from locations on disk.
|
||||
// Multiple mappings can be set up to map locations in the DiskSourceTree to
|
||||
// locations in the physical filesystem.
|
||||
class LIBPROTOBUF_EXPORT DiskSourceTree : public SourceTree {
|
||||
public:
|
||||
DiskSourceTree();
|
||||
~DiskSourceTree();
|
||||
|
||||
// Map a path on disk to a location in the SourceTree. The path may be
|
||||
// either a file or a directory. If it is a directory, the entire tree
|
||||
// under it will be mapped to the given virtual location. To map a directory
|
||||
// to the root of the source tree, pass an empty string for virtual_path.
|
||||
//
|
||||
// If multiple mapped paths apply when opening a file, they will be searched
|
||||
// in order. For example, if you do:
|
||||
// MapPath("bar", "foo/bar");
|
||||
// MapPath("", "baz");
|
||||
// and then you do:
|
||||
// Open("bar/qux");
|
||||
// the DiskSourceTree will first try to open foo/bar/qux, then baz/bar/qux,
|
||||
// returning the first one that opens successfuly.
|
||||
//
|
||||
// disk_path may be an absolute path or relative to the current directory,
|
||||
// just like a path you'd pass to open().
|
||||
void MapPath(const string& virtual_path, const string& disk_path);
|
||||
|
||||
// Return type for DiskFileToVirtualFile().
|
||||
enum DiskFileToVirtualFileResult {
|
||||
SUCCESS,
|
||||
SHADOWED,
|
||||
CANNOT_OPEN,
|
||||
NO_MAPPING
|
||||
};
|
||||
|
||||
// Given a path to a file on disk, find a virtual path mapping to that
|
||||
// file. The first mapping created with MapPath() whose disk_path contains
|
||||
// the filename is used. However, that virtual path may not actually be
|
||||
// usable to open the given file. Possible return values are:
|
||||
// * SUCCESS: The mapping was found. *virtual_file is filled in so that
|
||||
// calling Open(*virtual_file) will open the file named by disk_file.
|
||||
// * SHADOWED: A mapping was found, but using Open() to open this virtual
|
||||
// path will end up returning some different file. This is because some
|
||||
// other mapping with a higher precedence also matches this virtual path
|
||||
// and maps it to a different file that exists on disk. *virtual_file
|
||||
// is filled in as it would be in the SUCCESS case. *shadowing_disk_file
|
||||
// is filled in with the disk path of the file which would be opened if
|
||||
// you were to call Open(*virtual_file).
|
||||
// * CANNOT_OPEN: The mapping was found and was not shadowed, but the
|
||||
// file specified cannot be opened. When this value is returned,
|
||||
// errno will indicate the reason the file cannot be opened. *virtual_file
|
||||
// will be set to the virtual path as in the SUCCESS case, even though
|
||||
// it is not useful.
|
||||
// * NO_MAPPING: Indicates that no mapping was found which contains this
|
||||
// file.
|
||||
DiskFileToVirtualFileResult
|
||||
DiskFileToVirtualFile(const string& disk_file,
|
||||
string* virtual_file,
|
||||
string* shadowing_disk_file);
|
||||
|
||||
// Given a virtual path, find the path to the file on disk.
|
||||
// Return true and update disk_file with the on-disk path if the file exists.
|
||||
// Return false and leave disk_file untouched if the file doesn't exist.
|
||||
bool VirtualFileToDiskFile(const string& virtual_file, string* disk_file);
|
||||
|
||||
// implements SourceTree -------------------------------------------
|
||||
io::ZeroCopyInputStream* Open(const string& filename);
|
||||
|
||||
private:
|
||||
struct Mapping {
|
||||
string virtual_path;
|
||||
string disk_path;
|
||||
|
||||
inline Mapping(const string& virtual_path, const string& disk_path)
|
||||
: virtual_path(virtual_path), disk_path(disk_path) {}
|
||||
};
|
||||
vector<Mapping> mappings_;
|
||||
|
||||
// Like Open(), but returns the on-disk path in disk_file if disk_file is
|
||||
// non-NULL and the file could be successfully opened.
|
||||
io::ZeroCopyInputStream* OpenVirtualFile(const string& virtual_file,
|
||||
string* disk_file);
|
||||
|
||||
// Like Open() but given the actual on-disk path.
|
||||
io::ZeroCopyInputStream* OpenDiskFile(const string& filename);
|
||||
|
||||
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(DiskSourceTree);
|
||||
};
|
||||
|
||||
} // namespace compiler
|
||||
} // namespace protobuf
|
||||
|
||||
} // namespace google
|
||||
#endif // GOOGLE_PROTOBUF_COMPILER_IMPORTER_H__
|
||||
|
||||
+84
-84
@@ -1,84 +1,84 @@
|
||||
// Protocol Buffers - Google's data interchange format
|
||||
// Copyright 2008 Google Inc. All rights reserved.
|
||||
// http://code.google.com/p/protobuf/
|
||||
//
|
||||
// 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: kenton@google.com (Kenton Varda)
|
||||
// Based on original Protocol Buffers design by
|
||||
// Sanjay Ghemawat, Jeff Dean, and others.
|
||||
|
||||
#ifndef GOOGLE_PROTOBUF_COMPILER_JAVA_ENUM_H__
|
||||
#define GOOGLE_PROTOBUF_COMPILER_JAVA_ENUM_H__
|
||||
|
||||
#include <string>
|
||||
#include <vector>
|
||||
#include <google/protobuf/descriptor.h>
|
||||
|
||||
namespace google {
|
||||
namespace protobuf {
|
||||
namespace io {
|
||||
class Printer; // printer.h
|
||||
}
|
||||
}
|
||||
|
||||
namespace protobuf {
|
||||
namespace compiler {
|
||||
namespace java {
|
||||
|
||||
class EnumGenerator {
|
||||
public:
|
||||
explicit EnumGenerator(const EnumDescriptor* descriptor);
|
||||
~EnumGenerator();
|
||||
|
||||
void Generate(io::Printer* printer);
|
||||
|
||||
private:
|
||||
const EnumDescriptor* descriptor_;
|
||||
|
||||
// The proto language allows multiple enum constants to have the same numeric
|
||||
// value. Java, however, does not allow multiple enum constants to be
|
||||
// considered equivalent. We treat the first defined constant for any
|
||||
// given numeric value as "canonical" and the rest as aliases of that
|
||||
// canonical value.
|
||||
vector<const EnumValueDescriptor*> canonical_values_;
|
||||
|
||||
struct Alias {
|
||||
const EnumValueDescriptor* value;
|
||||
const EnumValueDescriptor* canonical_value;
|
||||
};
|
||||
vector<Alias> aliases_;
|
||||
|
||||
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(EnumGenerator);
|
||||
};
|
||||
|
||||
} // namespace java
|
||||
} // namespace compiler
|
||||
} // namespace protobuf
|
||||
|
||||
} // namespace google
|
||||
#endif // GOOGLE_PROTOBUF_COMPILER_JAVA_ENUM_H__
|
||||
// Protocol Buffers - Google's data interchange format
|
||||
// Copyright 2008 Google Inc. All rights reserved.
|
||||
// http://code.google.com/p/protobuf/
|
||||
//
|
||||
// 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: kenton@google.com (Kenton Varda)
|
||||
// Based on original Protocol Buffers design by
|
||||
// Sanjay Ghemawat, Jeff Dean, and others.
|
||||
|
||||
#ifndef GOOGLE_PROTOBUF_COMPILER_JAVA_ENUM_H__
|
||||
#define GOOGLE_PROTOBUF_COMPILER_JAVA_ENUM_H__
|
||||
|
||||
#include <string>
|
||||
#include <vector>
|
||||
#include <google/protobuf/descriptor.h>
|
||||
|
||||
namespace google {
|
||||
namespace protobuf {
|
||||
namespace io {
|
||||
class Printer; // printer.h
|
||||
}
|
||||
}
|
||||
|
||||
namespace protobuf {
|
||||
namespace compiler {
|
||||
namespace java {
|
||||
|
||||
class EnumGenerator {
|
||||
public:
|
||||
explicit EnumGenerator(const EnumDescriptor* descriptor);
|
||||
~EnumGenerator();
|
||||
|
||||
void Generate(io::Printer* printer);
|
||||
|
||||
private:
|
||||
const EnumDescriptor* descriptor_;
|
||||
|
||||
// The proto language allows multiple enum constants to have the same numeric
|
||||
// value. Java, however, does not allow multiple enum constants to be
|
||||
// considered equivalent. We treat the first defined constant for any
|
||||
// given numeric value as "canonical" and the rest as aliases of that
|
||||
// canonical value.
|
||||
vector<const EnumValueDescriptor*> canonical_values_;
|
||||
|
||||
struct Alias {
|
||||
const EnumValueDescriptor* value;
|
||||
const EnumValueDescriptor* canonical_value;
|
||||
};
|
||||
vector<Alias> aliases_;
|
||||
|
||||
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(EnumGenerator);
|
||||
};
|
||||
|
||||
} // namespace java
|
||||
} // namespace compiler
|
||||
} // namespace protobuf
|
||||
|
||||
} // namespace google
|
||||
#endif // GOOGLE_PROTOBUF_COMPILER_JAVA_ENUM_H__
|
||||
|
||||
+101
-101
@@ -1,101 +1,101 @@
|
||||
// Protocol Buffers - Google's data interchange format
|
||||
// Copyright 2008 Google Inc. All rights reserved.
|
||||
// http://code.google.com/p/protobuf/
|
||||
//
|
||||
// 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: kenton@google.com (Kenton Varda)
|
||||
// Based on original Protocol Buffers design by
|
||||
// Sanjay Ghemawat, Jeff Dean, and others.
|
||||
|
||||
#ifndef GOOGLE_PROTOBUF_COMPILER_JAVA_ENUM_FIELD_H__
|
||||
#define GOOGLE_PROTOBUF_COMPILER_JAVA_ENUM_FIELD_H__
|
||||
|
||||
#include <map>
|
||||
#include <string>
|
||||
#include <google/protobuf/compiler/java/java_field.h>
|
||||
|
||||
namespace google {
|
||||
namespace protobuf {
|
||||
namespace compiler {
|
||||
namespace java {
|
||||
|
||||
class EnumFieldGenerator : public FieldGenerator {
|
||||
public:
|
||||
explicit EnumFieldGenerator(const FieldDescriptor* descriptor);
|
||||
~EnumFieldGenerator();
|
||||
|
||||
// implements FieldGenerator ---------------------------------------
|
||||
void GenerateMembers(io::Printer* printer) const;
|
||||
void GenerateBuilderMembers(io::Printer* printer) const;
|
||||
void GenerateInitializationCode(io::Printer* printer) const;
|
||||
void GenerateMergingCode(io::Printer* printer) const;
|
||||
void GenerateBuildingCode(io::Printer* printer) const;
|
||||
void GenerateParsingCode(io::Printer* printer) const;
|
||||
void GenerateSerializationCode(io::Printer* printer) const;
|
||||
void GenerateSerializedSizeCode(io::Printer* printer) const;
|
||||
|
||||
string GetBoxedType() const;
|
||||
|
||||
private:
|
||||
const FieldDescriptor* descriptor_;
|
||||
map<string, string> variables_;
|
||||
|
||||
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(EnumFieldGenerator);
|
||||
};
|
||||
|
||||
class RepeatedEnumFieldGenerator : public FieldGenerator {
|
||||
public:
|
||||
explicit RepeatedEnumFieldGenerator(const FieldDescriptor* descriptor);
|
||||
~RepeatedEnumFieldGenerator();
|
||||
|
||||
// implements FieldGenerator ---------------------------------------
|
||||
void GenerateMembers(io::Printer* printer) const;
|
||||
void GenerateBuilderMembers(io::Printer* printer) const;
|
||||
void GenerateInitializationCode(io::Printer* printer) const;
|
||||
void GenerateMergingCode(io::Printer* printer) const;
|
||||
void GenerateBuildingCode(io::Printer* printer) const;
|
||||
void GenerateParsingCode(io::Printer* printer) const;
|
||||
void GenerateParsingCodeFromPacked(io::Printer* printer) const;
|
||||
void GenerateSerializationCode(io::Printer* printer) const;
|
||||
void GenerateSerializedSizeCode(io::Printer* printer) const;
|
||||
|
||||
string GetBoxedType() const;
|
||||
|
||||
private:
|
||||
const FieldDescriptor* descriptor_;
|
||||
map<string, string> variables_;
|
||||
|
||||
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(RepeatedEnumFieldGenerator);
|
||||
};
|
||||
|
||||
} // namespace java
|
||||
} // namespace compiler
|
||||
} // namespace protobuf
|
||||
|
||||
} // namespace google
|
||||
#endif // GOOGLE_PROTOBUF_COMPILER_JAVA_ENUM_FIELD_H__
|
||||
// Protocol Buffers - Google's data interchange format
|
||||
// Copyright 2008 Google Inc. All rights reserved.
|
||||
// http://code.google.com/p/protobuf/
|
||||
//
|
||||
// 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: kenton@google.com (Kenton Varda)
|
||||
// Based on original Protocol Buffers design by
|
||||
// Sanjay Ghemawat, Jeff Dean, and others.
|
||||
|
||||
#ifndef GOOGLE_PROTOBUF_COMPILER_JAVA_ENUM_FIELD_H__
|
||||
#define GOOGLE_PROTOBUF_COMPILER_JAVA_ENUM_FIELD_H__
|
||||
|
||||
#include <map>
|
||||
#include <string>
|
||||
#include <google/protobuf/compiler/java/java_field.h>
|
||||
|
||||
namespace google {
|
||||
namespace protobuf {
|
||||
namespace compiler {
|
||||
namespace java {
|
||||
|
||||
class EnumFieldGenerator : public FieldGenerator {
|
||||
public:
|
||||
explicit EnumFieldGenerator(const FieldDescriptor* descriptor);
|
||||
~EnumFieldGenerator();
|
||||
|
||||
// implements FieldGenerator ---------------------------------------
|
||||
void GenerateMembers(io::Printer* printer) const;
|
||||
void GenerateBuilderMembers(io::Printer* printer) const;
|
||||
void GenerateInitializationCode(io::Printer* printer) const;
|
||||
void GenerateMergingCode(io::Printer* printer) const;
|
||||
void GenerateBuildingCode(io::Printer* printer) const;
|
||||
void GenerateParsingCode(io::Printer* printer) const;
|
||||
void GenerateSerializationCode(io::Printer* printer) const;
|
||||
void GenerateSerializedSizeCode(io::Printer* printer) const;
|
||||
|
||||
string GetBoxedType() const;
|
||||
|
||||
private:
|
||||
const FieldDescriptor* descriptor_;
|
||||
map<string, string> variables_;
|
||||
|
||||
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(EnumFieldGenerator);
|
||||
};
|
||||
|
||||
class RepeatedEnumFieldGenerator : public FieldGenerator {
|
||||
public:
|
||||
explicit RepeatedEnumFieldGenerator(const FieldDescriptor* descriptor);
|
||||
~RepeatedEnumFieldGenerator();
|
||||
|
||||
// implements FieldGenerator ---------------------------------------
|
||||
void GenerateMembers(io::Printer* printer) const;
|
||||
void GenerateBuilderMembers(io::Printer* printer) const;
|
||||
void GenerateInitializationCode(io::Printer* printer) const;
|
||||
void GenerateMergingCode(io::Printer* printer) const;
|
||||
void GenerateBuildingCode(io::Printer* printer) const;
|
||||
void GenerateParsingCode(io::Printer* printer) const;
|
||||
void GenerateParsingCodeFromPacked(io::Printer* printer) const;
|
||||
void GenerateSerializationCode(io::Printer* printer) const;
|
||||
void GenerateSerializedSizeCode(io::Printer* printer) const;
|
||||
|
||||
string GetBoxedType() const;
|
||||
|
||||
private:
|
||||
const FieldDescriptor* descriptor_;
|
||||
map<string, string> variables_;
|
||||
|
||||
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(RepeatedEnumFieldGenerator);
|
||||
};
|
||||
|
||||
} // namespace java
|
||||
} // namespace compiler
|
||||
} // namespace protobuf
|
||||
|
||||
} // namespace google
|
||||
#endif // GOOGLE_PROTOBUF_COMPILER_JAVA_ENUM_FIELD_H__
|
||||
|
||||
+77
-77
@@ -1,77 +1,77 @@
|
||||
// Protocol Buffers - Google's data interchange format
|
||||
// Copyright 2008 Google Inc. All rights reserved.
|
||||
// http://code.google.com/p/protobuf/
|
||||
//
|
||||
// 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: kenton@google.com (Kenton Varda)
|
||||
// Based on original Protocol Buffers design by
|
||||
// Sanjay Ghemawat, Jeff Dean, and others.
|
||||
|
||||
#ifndef GOOGLE_PROTOBUF_COMPILER_JAVA_EXTENSION_H__
|
||||
#define GOOGLE_PROTOBUF_COMPILER_JAVA_EXTENSION_H__
|
||||
|
||||
#include <string>
|
||||
|
||||
#include <google/protobuf/stubs/common.h>
|
||||
|
||||
namespace google {
|
||||
namespace protobuf {
|
||||
class FieldDescriptor; // descriptor.h
|
||||
namespace io {
|
||||
class Printer; // printer.h
|
||||
}
|
||||
}
|
||||
|
||||
namespace protobuf {
|
||||
namespace compiler {
|
||||
namespace java {
|
||||
|
||||
// Generates code for an extension, which may be within the scope of some
|
||||
// message or may be at file scope. This is much simpler than FieldGenerator
|
||||
// since extensions are just simple identifiers with interesting types.
|
||||
class ExtensionGenerator {
|
||||
public:
|
||||
explicit ExtensionGenerator(const FieldDescriptor* descriptor);
|
||||
~ExtensionGenerator();
|
||||
|
||||
void Generate(io::Printer* printer);
|
||||
void GenerateInitializationCode(io::Printer* printer);
|
||||
void GenerateRegistrationCode(io::Printer* printer);
|
||||
|
||||
private:
|
||||
const FieldDescriptor* descriptor_;
|
||||
string scope_;
|
||||
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(ExtensionGenerator);
|
||||
};
|
||||
|
||||
} // namespace java
|
||||
} // namespace compiler
|
||||
} // namespace protobuf
|
||||
|
||||
} // namespace google
|
||||
#endif // GOOGLE_PROTOBUF_COMPILER_JAVA_MESSAGE_H__
|
||||
// Protocol Buffers - Google's data interchange format
|
||||
// Copyright 2008 Google Inc. All rights reserved.
|
||||
// http://code.google.com/p/protobuf/
|
||||
//
|
||||
// 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: kenton@google.com (Kenton Varda)
|
||||
// Based on original Protocol Buffers design by
|
||||
// Sanjay Ghemawat, Jeff Dean, and others.
|
||||
|
||||
#ifndef GOOGLE_PROTOBUF_COMPILER_JAVA_EXTENSION_H__
|
||||
#define GOOGLE_PROTOBUF_COMPILER_JAVA_EXTENSION_H__
|
||||
|
||||
#include <string>
|
||||
|
||||
#include <google/protobuf/stubs/common.h>
|
||||
|
||||
namespace google {
|
||||
namespace protobuf {
|
||||
class FieldDescriptor; // descriptor.h
|
||||
namespace io {
|
||||
class Printer; // printer.h
|
||||
}
|
||||
}
|
||||
|
||||
namespace protobuf {
|
||||
namespace compiler {
|
||||
namespace java {
|
||||
|
||||
// Generates code for an extension, which may be within the scope of some
|
||||
// message or may be at file scope. This is much simpler than FieldGenerator
|
||||
// since extensions are just simple identifiers with interesting types.
|
||||
class ExtensionGenerator {
|
||||
public:
|
||||
explicit ExtensionGenerator(const FieldDescriptor* descriptor);
|
||||
~ExtensionGenerator();
|
||||
|
||||
void Generate(io::Printer* printer);
|
||||
void GenerateInitializationCode(io::Printer* printer);
|
||||
void GenerateRegistrationCode(io::Printer* printer);
|
||||
|
||||
private:
|
||||
const FieldDescriptor* descriptor_;
|
||||
string scope_;
|
||||
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(ExtensionGenerator);
|
||||
};
|
||||
|
||||
} // namespace java
|
||||
} // namespace compiler
|
||||
} // namespace protobuf
|
||||
|
||||
} // namespace google
|
||||
#endif // GOOGLE_PROTOBUF_COMPILER_JAVA_MESSAGE_H__
|
||||
|
||||
+98
-98
@@ -1,98 +1,98 @@
|
||||
// Protocol Buffers - Google's data interchange format
|
||||
// Copyright 2008 Google Inc. All rights reserved.
|
||||
// http://code.google.com/p/protobuf/
|
||||
//
|
||||
// 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: kenton@google.com (Kenton Varda)
|
||||
// Based on original Protocol Buffers design by
|
||||
// Sanjay Ghemawat, Jeff Dean, and others.
|
||||
|
||||
#ifndef GOOGLE_PROTOBUF_COMPILER_JAVA_FIELD_H__
|
||||
#define GOOGLE_PROTOBUF_COMPILER_JAVA_FIELD_H__
|
||||
|
||||
#include <string>
|
||||
#include <google/protobuf/stubs/common.h>
|
||||
#include <google/protobuf/descriptor.h>
|
||||
|
||||
namespace google {
|
||||
namespace protobuf {
|
||||
namespace io {
|
||||
class Printer; // printer.h
|
||||
}
|
||||
}
|
||||
|
||||
namespace protobuf {
|
||||
namespace compiler {
|
||||
namespace java {
|
||||
|
||||
class FieldGenerator {
|
||||
public:
|
||||
FieldGenerator() {}
|
||||
virtual ~FieldGenerator();
|
||||
|
||||
virtual void GenerateMembers(io::Printer* printer) const = 0;
|
||||
virtual void GenerateBuilderMembers(io::Printer* printer) const = 0;
|
||||
virtual void GenerateInitializationCode(io::Printer* printer) const = 0;
|
||||
virtual void GenerateMergingCode(io::Printer* printer) const = 0;
|
||||
virtual void GenerateBuildingCode(io::Printer* printer) const = 0;
|
||||
virtual void GenerateParsingCode(io::Printer* printer) const = 0;
|
||||
virtual void GenerateParsingCodeFromPacked(io::Printer* printer) const;
|
||||
virtual void GenerateSerializationCode(io::Printer* printer) const = 0;
|
||||
virtual void GenerateSerializedSizeCode(io::Printer* printer) const = 0;
|
||||
|
||||
virtual string GetBoxedType() const = 0;
|
||||
|
||||
private:
|
||||
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(FieldGenerator);
|
||||
};
|
||||
|
||||
// Convenience class which constructs FieldGenerators for a Descriptor.
|
||||
class FieldGeneratorMap {
|
||||
public:
|
||||
explicit FieldGeneratorMap(const Descriptor* descriptor);
|
||||
~FieldGeneratorMap();
|
||||
|
||||
const FieldGenerator& get(const FieldDescriptor* field) const;
|
||||
const FieldGenerator& get_extension(int index) const;
|
||||
|
||||
private:
|
||||
const Descriptor* descriptor_;
|
||||
scoped_array<scoped_ptr<FieldGenerator> > field_generators_;
|
||||
scoped_array<scoped_ptr<FieldGenerator> > extension_generators_;
|
||||
|
||||
static FieldGenerator* MakeGenerator(const FieldDescriptor* field);
|
||||
|
||||
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(FieldGeneratorMap);
|
||||
};
|
||||
|
||||
} // namespace java
|
||||
} // namespace compiler
|
||||
} // namespace protobuf
|
||||
|
||||
} // namespace google
|
||||
#endif // GOOGLE_PROTOBUF_COMPILER_JAVA_FIELD_H__
|
||||
// Protocol Buffers - Google's data interchange format
|
||||
// Copyright 2008 Google Inc. All rights reserved.
|
||||
// http://code.google.com/p/protobuf/
|
||||
//
|
||||
// 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: kenton@google.com (Kenton Varda)
|
||||
// Based on original Protocol Buffers design by
|
||||
// Sanjay Ghemawat, Jeff Dean, and others.
|
||||
|
||||
#ifndef GOOGLE_PROTOBUF_COMPILER_JAVA_FIELD_H__
|
||||
#define GOOGLE_PROTOBUF_COMPILER_JAVA_FIELD_H__
|
||||
|
||||
#include <string>
|
||||
#include <google/protobuf/stubs/common.h>
|
||||
#include <google/protobuf/descriptor.h>
|
||||
|
||||
namespace google {
|
||||
namespace protobuf {
|
||||
namespace io {
|
||||
class Printer; // printer.h
|
||||
}
|
||||
}
|
||||
|
||||
namespace protobuf {
|
||||
namespace compiler {
|
||||
namespace java {
|
||||
|
||||
class FieldGenerator {
|
||||
public:
|
||||
FieldGenerator() {}
|
||||
virtual ~FieldGenerator();
|
||||
|
||||
virtual void GenerateMembers(io::Printer* printer) const = 0;
|
||||
virtual void GenerateBuilderMembers(io::Printer* printer) const = 0;
|
||||
virtual void GenerateInitializationCode(io::Printer* printer) const = 0;
|
||||
virtual void GenerateMergingCode(io::Printer* printer) const = 0;
|
||||
virtual void GenerateBuildingCode(io::Printer* printer) const = 0;
|
||||
virtual void GenerateParsingCode(io::Printer* printer) const = 0;
|
||||
virtual void GenerateParsingCodeFromPacked(io::Printer* printer) const;
|
||||
virtual void GenerateSerializationCode(io::Printer* printer) const = 0;
|
||||
virtual void GenerateSerializedSizeCode(io::Printer* printer) const = 0;
|
||||
|
||||
virtual string GetBoxedType() const = 0;
|
||||
|
||||
private:
|
||||
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(FieldGenerator);
|
||||
};
|
||||
|
||||
// Convenience class which constructs FieldGenerators for a Descriptor.
|
||||
class FieldGeneratorMap {
|
||||
public:
|
||||
explicit FieldGeneratorMap(const Descriptor* descriptor);
|
||||
~FieldGeneratorMap();
|
||||
|
||||
const FieldGenerator& get(const FieldDescriptor* field) const;
|
||||
const FieldGenerator& get_extension(int index) const;
|
||||
|
||||
private:
|
||||
const Descriptor* descriptor_;
|
||||
scoped_array<scoped_ptr<FieldGenerator> > field_generators_;
|
||||
scoped_array<scoped_ptr<FieldGenerator> > extension_generators_;
|
||||
|
||||
static FieldGenerator* MakeGenerator(const FieldDescriptor* field);
|
||||
|
||||
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(FieldGeneratorMap);
|
||||
};
|
||||
|
||||
} // namespace java
|
||||
} // namespace compiler
|
||||
} // namespace protobuf
|
||||
|
||||
} // namespace google
|
||||
#endif // GOOGLE_PROTOBUF_COMPILER_JAVA_FIELD_H__
|
||||
|
||||
+99
-99
@@ -1,99 +1,99 @@
|
||||
// Protocol Buffers - Google's data interchange format
|
||||
// Copyright 2008 Google Inc. All rights reserved.
|
||||
// http://code.google.com/p/protobuf/
|
||||
//
|
||||
// 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: kenton@google.com (Kenton Varda)
|
||||
// Based on original Protocol Buffers design by
|
||||
// Sanjay Ghemawat, Jeff Dean, and others.
|
||||
|
||||
#ifndef GOOGLE_PROTOBUF_COMPILER_JAVA_FILE_H__
|
||||
#define GOOGLE_PROTOBUF_COMPILER_JAVA_FILE_H__
|
||||
|
||||
#include <string>
|
||||
#include <vector>
|
||||
#include <google/protobuf/stubs/common.h>
|
||||
|
||||
namespace google {
|
||||
namespace protobuf {
|
||||
class FileDescriptor; // descriptor.h
|
||||
namespace io {
|
||||
class Printer; // printer.h
|
||||
}
|
||||
namespace compiler {
|
||||
class OutputDirectory; // code_generator.h
|
||||
}
|
||||
}
|
||||
|
||||
namespace protobuf {
|
||||
namespace compiler {
|
||||
namespace java {
|
||||
|
||||
class FileGenerator {
|
||||
public:
|
||||
explicit FileGenerator(const FileDescriptor* file);
|
||||
~FileGenerator();
|
||||
|
||||
// Checks for problems that would otherwise lead to cryptic compile errors.
|
||||
// Returns true if there are no problems, or writes an error description to
|
||||
// the given string and returns false otherwise.
|
||||
bool Validate(string* error);
|
||||
|
||||
void Generate(io::Printer* printer);
|
||||
|
||||
// If we aren't putting everything into one file, this will write all the
|
||||
// files other than the outer file (i.e. one for each message, enum, and
|
||||
// service type).
|
||||
void GenerateSiblings(const string& package_dir,
|
||||
OutputDirectory* output_directory,
|
||||
vector<string>* file_list);
|
||||
|
||||
const string& java_package() { return java_package_; }
|
||||
const string& classname() { return classname_; }
|
||||
|
||||
private:
|
||||
// Returns whether the dependency should be included in the output file.
|
||||
// Always returns true for opensource, but used internally at Google to help
|
||||
// improve compatibility with version 1 of protocol buffers.
|
||||
bool ShouldIncludeDependency(const FileDescriptor* descriptor);
|
||||
|
||||
const FileDescriptor* file_;
|
||||
string java_package_;
|
||||
string classname_;
|
||||
|
||||
void GenerateEmbeddedDescriptor(io::Printer* printer);
|
||||
|
||||
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(FileGenerator);
|
||||
};
|
||||
|
||||
} // namespace java
|
||||
} // namespace compiler
|
||||
} // namespace protobuf
|
||||
|
||||
} // namespace google
|
||||
#endif // GOOGLE_PROTOBUF_COMPILER_JAVA_FILE_H__
|
||||
// Protocol Buffers - Google's data interchange format
|
||||
// Copyright 2008 Google Inc. All rights reserved.
|
||||
// http://code.google.com/p/protobuf/
|
||||
//
|
||||
// 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: kenton@google.com (Kenton Varda)
|
||||
// Based on original Protocol Buffers design by
|
||||
// Sanjay Ghemawat, Jeff Dean, and others.
|
||||
|
||||
#ifndef GOOGLE_PROTOBUF_COMPILER_JAVA_FILE_H__
|
||||
#define GOOGLE_PROTOBUF_COMPILER_JAVA_FILE_H__
|
||||
|
||||
#include <string>
|
||||
#include <vector>
|
||||
#include <google/protobuf/stubs/common.h>
|
||||
|
||||
namespace google {
|
||||
namespace protobuf {
|
||||
class FileDescriptor; // descriptor.h
|
||||
namespace io {
|
||||
class Printer; // printer.h
|
||||
}
|
||||
namespace compiler {
|
||||
class OutputDirectory; // code_generator.h
|
||||
}
|
||||
}
|
||||
|
||||
namespace protobuf {
|
||||
namespace compiler {
|
||||
namespace java {
|
||||
|
||||
class FileGenerator {
|
||||
public:
|
||||
explicit FileGenerator(const FileDescriptor* file);
|
||||
~FileGenerator();
|
||||
|
||||
// Checks for problems that would otherwise lead to cryptic compile errors.
|
||||
// Returns true if there are no problems, or writes an error description to
|
||||
// the given string and returns false otherwise.
|
||||
bool Validate(string* error);
|
||||
|
||||
void Generate(io::Printer* printer);
|
||||
|
||||
// If we aren't putting everything into one file, this will write all the
|
||||
// files other than the outer file (i.e. one for each message, enum, and
|
||||
// service type).
|
||||
void GenerateSiblings(const string& package_dir,
|
||||
OutputDirectory* output_directory,
|
||||
vector<string>* file_list);
|
||||
|
||||
const string& java_package() { return java_package_; }
|
||||
const string& classname() { return classname_; }
|
||||
|
||||
private:
|
||||
// Returns whether the dependency should be included in the output file.
|
||||
// Always returns true for opensource, but used internally at Google to help
|
||||
// improve compatibility with version 1 of protocol buffers.
|
||||
bool ShouldIncludeDependency(const FileDescriptor* descriptor);
|
||||
|
||||
const FileDescriptor* file_;
|
||||
string java_package_;
|
||||
string classname_;
|
||||
|
||||
void GenerateEmbeddedDescriptor(io::Printer* printer);
|
||||
|
||||
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(FileGenerator);
|
||||
};
|
||||
|
||||
} // namespace java
|
||||
} // namespace compiler
|
||||
} // namespace protobuf
|
||||
|
||||
} // namespace google
|
||||
#endif // GOOGLE_PROTOBUF_COMPILER_JAVA_FILE_H__
|
||||
|
||||
+72
-72
@@ -1,72 +1,72 @@
|
||||
// Protocol Buffers - Google's data interchange format
|
||||
// Copyright 2008 Google Inc. All rights reserved.
|
||||
// http://code.google.com/p/protobuf/
|
||||
//
|
||||
// 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: kenton@google.com (Kenton Varda)
|
||||
// Based on original Protocol Buffers design by
|
||||
// Sanjay Ghemawat, Jeff Dean, and others.
|
||||
//
|
||||
// Generates Java code for a given .proto file.
|
||||
|
||||
#ifndef GOOGLE_PROTOBUF_COMPILER_JAVA_GENERATOR_H__
|
||||
#define GOOGLE_PROTOBUF_COMPILER_JAVA_GENERATOR_H__
|
||||
|
||||
#include <string>
|
||||
#include <google/protobuf/compiler/code_generator.h>
|
||||
|
||||
namespace google {
|
||||
namespace protobuf {
|
||||
namespace compiler {
|
||||
namespace java {
|
||||
|
||||
// CodeGenerator implementation which generates Java code. If you create your
|
||||
// own protocol compiler binary and you want it to support Java output, you
|
||||
// can do so by registering an instance of this CodeGenerator with the
|
||||
// CommandLineInterface in your main() function.
|
||||
class LIBPROTOC_EXPORT JavaGenerator : public CodeGenerator {
|
||||
public:
|
||||
JavaGenerator();
|
||||
~JavaGenerator();
|
||||
|
||||
// implements CodeGenerator ----------------------------------------
|
||||
bool Generate(const FileDescriptor* file,
|
||||
const string& parameter,
|
||||
OutputDirectory* output_directory,
|
||||
string* error) const;
|
||||
|
||||
private:
|
||||
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(JavaGenerator);
|
||||
};
|
||||
|
||||
} // namespace java
|
||||
} // namespace compiler
|
||||
} // namespace protobuf
|
||||
|
||||
} // namespace google
|
||||
#endif // GOOGLE_PROTOBUF_COMPILER_JAVA_GENERATOR_H__
|
||||
// Protocol Buffers - Google's data interchange format
|
||||
// Copyright 2008 Google Inc. All rights reserved.
|
||||
// http://code.google.com/p/protobuf/
|
||||
//
|
||||
// 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: kenton@google.com (Kenton Varda)
|
||||
// Based on original Protocol Buffers design by
|
||||
// Sanjay Ghemawat, Jeff Dean, and others.
|
||||
//
|
||||
// Generates Java code for a given .proto file.
|
||||
|
||||
#ifndef GOOGLE_PROTOBUF_COMPILER_JAVA_GENERATOR_H__
|
||||
#define GOOGLE_PROTOBUF_COMPILER_JAVA_GENERATOR_H__
|
||||
|
||||
#include <string>
|
||||
#include <google/protobuf/compiler/code_generator.h>
|
||||
|
||||
namespace google {
|
||||
namespace protobuf {
|
||||
namespace compiler {
|
||||
namespace java {
|
||||
|
||||
// CodeGenerator implementation which generates Java code. If you create your
|
||||
// own protocol compiler binary and you want it to support Java output, you
|
||||
// can do so by registering an instance of this CodeGenerator with the
|
||||
// CommandLineInterface in your main() function.
|
||||
class LIBPROTOC_EXPORT JavaGenerator : public CodeGenerator {
|
||||
public:
|
||||
JavaGenerator();
|
||||
~JavaGenerator();
|
||||
|
||||
// implements CodeGenerator ----------------------------------------
|
||||
bool Generate(const FileDescriptor* file,
|
||||
const string& parameter,
|
||||
OutputDirectory* output_directory,
|
||||
string* error) const;
|
||||
|
||||
private:
|
||||
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(JavaGenerator);
|
||||
};
|
||||
|
||||
} // namespace java
|
||||
} // namespace compiler
|
||||
} // namespace protobuf
|
||||
|
||||
} // namespace google
|
||||
#endif // GOOGLE_PROTOBUF_COMPILER_JAVA_GENERATOR_H__
|
||||
|
||||
+161
-161
@@ -1,161 +1,161 @@
|
||||
// Protocol Buffers - Google's data interchange format
|
||||
// Copyright 2008 Google Inc. All rights reserved.
|
||||
// http://code.google.com/p/protobuf/
|
||||
//
|
||||
// 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: kenton@google.com (Kenton Varda)
|
||||
// Based on original Protocol Buffers design by
|
||||
// Sanjay Ghemawat, Jeff Dean, and others.
|
||||
|
||||
#ifndef GOOGLE_PROTOBUF_COMPILER_JAVA_HELPERS_H__
|
||||
#define GOOGLE_PROTOBUF_COMPILER_JAVA_HELPERS_H__
|
||||
|
||||
#include <string>
|
||||
#include <google/protobuf/descriptor.pb.h>
|
||||
#include <google/protobuf/descriptor.h>
|
||||
|
||||
namespace google {
|
||||
namespace protobuf {
|
||||
namespace compiler {
|
||||
namespace java {
|
||||
|
||||
// Commonly-used separator comments. Thick is a line of '=', thin is a line
|
||||
// of '-'.
|
||||
extern const char kThickSeparator[];
|
||||
extern const char kThinSeparator[];
|
||||
|
||||
// Converts the field's name to camel-case, e.g. "foo_bar_baz" becomes
|
||||
// "fooBarBaz" or "FooBarBaz", respectively.
|
||||
string UnderscoresToCamelCase(const FieldDescriptor* field);
|
||||
string UnderscoresToCapitalizedCamelCase(const FieldDescriptor* field);
|
||||
|
||||
// Similar, but for method names. (Typically, this merely has the effect
|
||||
// of lower-casing the first letter of the name.)
|
||||
string UnderscoresToCamelCase(const MethodDescriptor* method);
|
||||
|
||||
// Strips ".proto" or ".protodevel" from the end of a filename.
|
||||
string StripProto(const string& filename);
|
||||
|
||||
// Gets the unqualified class name for the file. Each .proto file becomes a
|
||||
// single Java class, with all its contents nested in that class.
|
||||
string FileClassName(const FileDescriptor* file);
|
||||
|
||||
// Returns the file's Java package name.
|
||||
string FileJavaPackage(const FileDescriptor* file);
|
||||
|
||||
// Converts the given fully-qualified name in the proto namespace to its
|
||||
// fully-qualified name in the Java namespace, given that it is in the given
|
||||
// file.
|
||||
string ToJavaName(const string& full_name, const FileDescriptor* file);
|
||||
|
||||
// These return the fully-qualified class name corresponding to the given
|
||||
// descriptor.
|
||||
inline string ClassName(const Descriptor* descriptor) {
|
||||
return ToJavaName(descriptor->full_name(), descriptor->file());
|
||||
}
|
||||
inline string ClassName(const EnumDescriptor* descriptor) {
|
||||
return ToJavaName(descriptor->full_name(), descriptor->file());
|
||||
}
|
||||
inline string ClassName(const ServiceDescriptor* descriptor) {
|
||||
return ToJavaName(descriptor->full_name(), descriptor->file());
|
||||
}
|
||||
inline string ExtensionIdentifierName(const FieldDescriptor* descriptor) {
|
||||
return ToJavaName(descriptor->full_name(), descriptor->file());
|
||||
}
|
||||
string ClassName(const FileDescriptor* descriptor);
|
||||
|
||||
// Get the unqualified name that should be used for a field's field
|
||||
// number constant.
|
||||
string FieldConstantName(const FieldDescriptor *field);
|
||||
|
||||
// Returns the type of the FieldDescriptor.
|
||||
// This does nothing interesting for the open source release, but is used for
|
||||
// hacks that improve compatability with version 1 protocol buffers at Google.
|
||||
FieldDescriptor::Type GetType(const FieldDescriptor* field);
|
||||
|
||||
enum JavaType {
|
||||
JAVATYPE_INT,
|
||||
JAVATYPE_LONG,
|
||||
JAVATYPE_FLOAT,
|
||||
JAVATYPE_DOUBLE,
|
||||
JAVATYPE_BOOLEAN,
|
||||
JAVATYPE_STRING,
|
||||
JAVATYPE_BYTES,
|
||||
JAVATYPE_ENUM,
|
||||
JAVATYPE_MESSAGE
|
||||
};
|
||||
|
||||
JavaType GetJavaType(const FieldDescriptor* field);
|
||||
|
||||
// Get the fully-qualified class name for a boxed primitive type, e.g.
|
||||
// "java.lang.Integer" for JAVATYPE_INT. Returns NULL for enum and message
|
||||
// types.
|
||||
const char* BoxedPrimitiveTypeName(JavaType type);
|
||||
|
||||
string DefaultValue(const FieldDescriptor* field);
|
||||
|
||||
// Does this message class keep track of unknown fields?
|
||||
inline bool HasUnknownFields(const Descriptor* descriptor) {
|
||||
return descriptor->file()->options().optimize_for() !=
|
||||
FileOptions::LITE_RUNTIME;
|
||||
}
|
||||
|
||||
// Does this message class have generated parsing, serialization, and other
|
||||
// standard methods for which reflection-based fallback implementations exist?
|
||||
inline bool HasGeneratedMethods(const Descriptor* descriptor) {
|
||||
return descriptor->file()->options().optimize_for() !=
|
||||
FileOptions::CODE_SIZE;
|
||||
}
|
||||
|
||||
// Does this message class have descriptor and reflection methods?
|
||||
inline bool HasDescriptorMethods(const Descriptor* descriptor) {
|
||||
return descriptor->file()->options().optimize_for() !=
|
||||
FileOptions::LITE_RUNTIME;
|
||||
}
|
||||
inline bool HasDescriptorMethods(const EnumDescriptor* descriptor) {
|
||||
return descriptor->file()->options().optimize_for() !=
|
||||
FileOptions::LITE_RUNTIME;
|
||||
}
|
||||
inline bool HasDescriptorMethods(const FileDescriptor* descriptor) {
|
||||
return descriptor->options().optimize_for() !=
|
||||
FileOptions::LITE_RUNTIME;
|
||||
}
|
||||
|
||||
// Should we generate generic services for this file?
|
||||
inline bool HasGenericServices(const FileDescriptor *file) {
|
||||
return file->service_count() > 0 &&
|
||||
file->options().optimize_for() != FileOptions::LITE_RUNTIME &&
|
||||
file->options().java_generic_services();
|
||||
}
|
||||
|
||||
} // namespace java
|
||||
} // namespace compiler
|
||||
} // namespace protobuf
|
||||
|
||||
} // namespace google
|
||||
#endif // GOOGLE_PROTOBUF_COMPILER_JAVA_HELPERS_H__
|
||||
// Protocol Buffers - Google's data interchange format
|
||||
// Copyright 2008 Google Inc. All rights reserved.
|
||||
// http://code.google.com/p/protobuf/
|
||||
//
|
||||
// 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: kenton@google.com (Kenton Varda)
|
||||
// Based on original Protocol Buffers design by
|
||||
// Sanjay Ghemawat, Jeff Dean, and others.
|
||||
|
||||
#ifndef GOOGLE_PROTOBUF_COMPILER_JAVA_HELPERS_H__
|
||||
#define GOOGLE_PROTOBUF_COMPILER_JAVA_HELPERS_H__
|
||||
|
||||
#include <string>
|
||||
#include <google/protobuf/descriptor.pb.h>
|
||||
#include <google/protobuf/descriptor.h>
|
||||
|
||||
namespace google {
|
||||
namespace protobuf {
|
||||
namespace compiler {
|
||||
namespace java {
|
||||
|
||||
// Commonly-used separator comments. Thick is a line of '=', thin is a line
|
||||
// of '-'.
|
||||
extern const char kThickSeparator[];
|
||||
extern const char kThinSeparator[];
|
||||
|
||||
// Converts the field's name to camel-case, e.g. "foo_bar_baz" becomes
|
||||
// "fooBarBaz" or "FooBarBaz", respectively.
|
||||
string UnderscoresToCamelCase(const FieldDescriptor* field);
|
||||
string UnderscoresToCapitalizedCamelCase(const FieldDescriptor* field);
|
||||
|
||||
// Similar, but for method names. (Typically, this merely has the effect
|
||||
// of lower-casing the first letter of the name.)
|
||||
string UnderscoresToCamelCase(const MethodDescriptor* method);
|
||||
|
||||
// Strips ".proto" or ".protodevel" from the end of a filename.
|
||||
string StripProto(const string& filename);
|
||||
|
||||
// Gets the unqualified class name for the file. Each .proto file becomes a
|
||||
// single Java class, with all its contents nested in that class.
|
||||
string FileClassName(const FileDescriptor* file);
|
||||
|
||||
// Returns the file's Java package name.
|
||||
string FileJavaPackage(const FileDescriptor* file);
|
||||
|
||||
// Converts the given fully-qualified name in the proto namespace to its
|
||||
// fully-qualified name in the Java namespace, given that it is in the given
|
||||
// file.
|
||||
string ToJavaName(const string& full_name, const FileDescriptor* file);
|
||||
|
||||
// These return the fully-qualified class name corresponding to the given
|
||||
// descriptor.
|
||||
inline string ClassName(const Descriptor* descriptor) {
|
||||
return ToJavaName(descriptor->full_name(), descriptor->file());
|
||||
}
|
||||
inline string ClassName(const EnumDescriptor* descriptor) {
|
||||
return ToJavaName(descriptor->full_name(), descriptor->file());
|
||||
}
|
||||
inline string ClassName(const ServiceDescriptor* descriptor) {
|
||||
return ToJavaName(descriptor->full_name(), descriptor->file());
|
||||
}
|
||||
inline string ExtensionIdentifierName(const FieldDescriptor* descriptor) {
|
||||
return ToJavaName(descriptor->full_name(), descriptor->file());
|
||||
}
|
||||
string ClassName(const FileDescriptor* descriptor);
|
||||
|
||||
// Get the unqualified name that should be used for a field's field
|
||||
// number constant.
|
||||
string FieldConstantName(const FieldDescriptor *field);
|
||||
|
||||
// Returns the type of the FieldDescriptor.
|
||||
// This does nothing interesting for the open source release, but is used for
|
||||
// hacks that improve compatability with version 1 protocol buffers at Google.
|
||||
FieldDescriptor::Type GetType(const FieldDescriptor* field);
|
||||
|
||||
enum JavaType {
|
||||
JAVATYPE_INT,
|
||||
JAVATYPE_LONG,
|
||||
JAVATYPE_FLOAT,
|
||||
JAVATYPE_DOUBLE,
|
||||
JAVATYPE_BOOLEAN,
|
||||
JAVATYPE_STRING,
|
||||
JAVATYPE_BYTES,
|
||||
JAVATYPE_ENUM,
|
||||
JAVATYPE_MESSAGE
|
||||
};
|
||||
|
||||
JavaType GetJavaType(const FieldDescriptor* field);
|
||||
|
||||
// Get the fully-qualified class name for a boxed primitive type, e.g.
|
||||
// "java.lang.Integer" for JAVATYPE_INT. Returns NULL for enum and message
|
||||
// types.
|
||||
const char* BoxedPrimitiveTypeName(JavaType type);
|
||||
|
||||
string DefaultValue(const FieldDescriptor* field);
|
||||
|
||||
// Does this message class keep track of unknown fields?
|
||||
inline bool HasUnknownFields(const Descriptor* descriptor) {
|
||||
return descriptor->file()->options().optimize_for() !=
|
||||
FileOptions::LITE_RUNTIME;
|
||||
}
|
||||
|
||||
// Does this message class have generated parsing, serialization, and other
|
||||
// standard methods for which reflection-based fallback implementations exist?
|
||||
inline bool HasGeneratedMethods(const Descriptor* descriptor) {
|
||||
return descriptor->file()->options().optimize_for() !=
|
||||
FileOptions::CODE_SIZE;
|
||||
}
|
||||
|
||||
// Does this message class have descriptor and reflection methods?
|
||||
inline bool HasDescriptorMethods(const Descriptor* descriptor) {
|
||||
return descriptor->file()->options().optimize_for() !=
|
||||
FileOptions::LITE_RUNTIME;
|
||||
}
|
||||
inline bool HasDescriptorMethods(const EnumDescriptor* descriptor) {
|
||||
return descriptor->file()->options().optimize_for() !=
|
||||
FileOptions::LITE_RUNTIME;
|
||||
}
|
||||
inline bool HasDescriptorMethods(const FileDescriptor* descriptor) {
|
||||
return descriptor->options().optimize_for() !=
|
||||
FileOptions::LITE_RUNTIME;
|
||||
}
|
||||
|
||||
// Should we generate generic services for this file?
|
||||
inline bool HasGenericServices(const FileDescriptor *file) {
|
||||
return file->service_count() > 0 &&
|
||||
file->options().optimize_for() != FileOptions::LITE_RUNTIME &&
|
||||
file->options().java_generic_services();
|
||||
}
|
||||
|
||||
} // namespace java
|
||||
} // namespace compiler
|
||||
} // namespace protobuf
|
||||
|
||||
} // namespace google
|
||||
#endif // GOOGLE_PROTOBUF_COMPILER_JAVA_HELPERS_H__
|
||||
|
||||
+98
-98
@@ -1,98 +1,98 @@
|
||||
// Protocol Buffers - Google's data interchange format
|
||||
// Copyright 2008 Google Inc. All rights reserved.
|
||||
// http://code.google.com/p/protobuf/
|
||||
//
|
||||
// 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: kenton@google.com (Kenton Varda)
|
||||
// Based on original Protocol Buffers design by
|
||||
// Sanjay Ghemawat, Jeff Dean, and others.
|
||||
|
||||
#ifndef GOOGLE_PROTOBUF_COMPILER_JAVA_MESSAGE_H__
|
||||
#define GOOGLE_PROTOBUF_COMPILER_JAVA_MESSAGE_H__
|
||||
|
||||
#include <string>
|
||||
#include <google/protobuf/stubs/common.h>
|
||||
#include <google/protobuf/compiler/java/java_field.h>
|
||||
|
||||
namespace google {
|
||||
namespace protobuf {
|
||||
namespace io {
|
||||
class Printer; // printer.h
|
||||
}
|
||||
}
|
||||
|
||||
namespace protobuf {
|
||||
namespace compiler {
|
||||
namespace java {
|
||||
|
||||
class MessageGenerator {
|
||||
public:
|
||||
explicit MessageGenerator(const Descriptor* descriptor);
|
||||
~MessageGenerator();
|
||||
|
||||
// All static variables have to be declared at the top-level of the file
|
||||
// so that we can control initialization order, which is important for
|
||||
// DescriptorProto bootstrapping to work.
|
||||
void GenerateStaticVariables(io::Printer* printer);
|
||||
|
||||
// Output code which initializes the static variables generated by
|
||||
// GenerateStaticVariables().
|
||||
void GenerateStaticVariableInitializers(io::Printer* printer);
|
||||
|
||||
// Generate the class itself.
|
||||
void Generate(io::Printer* printer);
|
||||
|
||||
// Generate code to register all contained extensions with an
|
||||
// ExtensionRegistry.
|
||||
void GenerateExtensionRegistrationCode(io::Printer* printer);
|
||||
|
||||
private:
|
||||
void GenerateMessageSerializationMethods(io::Printer* printer);
|
||||
void GenerateParseFromMethods(io::Printer* printer);
|
||||
void GenerateSerializeOneField(io::Printer* printer,
|
||||
const FieldDescriptor* field);
|
||||
void GenerateSerializeOneExtensionRange(
|
||||
io::Printer* printer, const Descriptor::ExtensionRange* range);
|
||||
|
||||
void GenerateBuilder(io::Printer* printer);
|
||||
void GenerateCommonBuilderMethods(io::Printer* printer);
|
||||
void GenerateBuilderParsingMethods(io::Printer* printer);
|
||||
void GenerateIsInitialized(io::Printer* printer);
|
||||
|
||||
const Descriptor* descriptor_;
|
||||
FieldGeneratorMap field_generators_;
|
||||
|
||||
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(MessageGenerator);
|
||||
};
|
||||
|
||||
} // namespace java
|
||||
} // namespace compiler
|
||||
} // namespace protobuf
|
||||
|
||||
} // namespace google
|
||||
#endif // GOOGLE_PROTOBUF_COMPILER_JAVA_MESSAGE_H__
|
||||
// Protocol Buffers - Google's data interchange format
|
||||
// Copyright 2008 Google Inc. All rights reserved.
|
||||
// http://code.google.com/p/protobuf/
|
||||
//
|
||||
// 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: kenton@google.com (Kenton Varda)
|
||||
// Based on original Protocol Buffers design by
|
||||
// Sanjay Ghemawat, Jeff Dean, and others.
|
||||
|
||||
#ifndef GOOGLE_PROTOBUF_COMPILER_JAVA_MESSAGE_H__
|
||||
#define GOOGLE_PROTOBUF_COMPILER_JAVA_MESSAGE_H__
|
||||
|
||||
#include <string>
|
||||
#include <google/protobuf/stubs/common.h>
|
||||
#include <google/protobuf/compiler/java/java_field.h>
|
||||
|
||||
namespace google {
|
||||
namespace protobuf {
|
||||
namespace io {
|
||||
class Printer; // printer.h
|
||||
}
|
||||
}
|
||||
|
||||
namespace protobuf {
|
||||
namespace compiler {
|
||||
namespace java {
|
||||
|
||||
class MessageGenerator {
|
||||
public:
|
||||
explicit MessageGenerator(const Descriptor* descriptor);
|
||||
~MessageGenerator();
|
||||
|
||||
// All static variables have to be declared at the top-level of the file
|
||||
// so that we can control initialization order, which is important for
|
||||
// DescriptorProto bootstrapping to work.
|
||||
void GenerateStaticVariables(io::Printer* printer);
|
||||
|
||||
// Output code which initializes the static variables generated by
|
||||
// GenerateStaticVariables().
|
||||
void GenerateStaticVariableInitializers(io::Printer* printer);
|
||||
|
||||
// Generate the class itself.
|
||||
void Generate(io::Printer* printer);
|
||||
|
||||
// Generate code to register all contained extensions with an
|
||||
// ExtensionRegistry.
|
||||
void GenerateExtensionRegistrationCode(io::Printer* printer);
|
||||
|
||||
private:
|
||||
void GenerateMessageSerializationMethods(io::Printer* printer);
|
||||
void GenerateParseFromMethods(io::Printer* printer);
|
||||
void GenerateSerializeOneField(io::Printer* printer,
|
||||
const FieldDescriptor* field);
|
||||
void GenerateSerializeOneExtensionRange(
|
||||
io::Printer* printer, const Descriptor::ExtensionRange* range);
|
||||
|
||||
void GenerateBuilder(io::Printer* printer);
|
||||
void GenerateCommonBuilderMethods(io::Printer* printer);
|
||||
void GenerateBuilderParsingMethods(io::Printer* printer);
|
||||
void GenerateIsInitialized(io::Printer* printer);
|
||||
|
||||
const Descriptor* descriptor_;
|
||||
FieldGeneratorMap field_generators_;
|
||||
|
||||
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(MessageGenerator);
|
||||
};
|
||||
|
||||
} // namespace java
|
||||
} // namespace compiler
|
||||
} // namespace protobuf
|
||||
|
||||
} // namespace google
|
||||
#endif // GOOGLE_PROTOBUF_COMPILER_JAVA_MESSAGE_H__
|
||||
|
||||
+100
-100
@@ -1,100 +1,100 @@
|
||||
// Protocol Buffers - Google's data interchange format
|
||||
// Copyright 2008 Google Inc. All rights reserved.
|
||||
// http://code.google.com/p/protobuf/
|
||||
//
|
||||
// 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: kenton@google.com (Kenton Varda)
|
||||
// Based on original Protocol Buffers design by
|
||||
// Sanjay Ghemawat, Jeff Dean, and others.
|
||||
|
||||
#ifndef GOOGLE_PROTOBUF_COMPILER_JAVA_MESSAGE_FIELD_H__
|
||||
#define GOOGLE_PROTOBUF_COMPILER_JAVA_MESSAGE_FIELD_H__
|
||||
|
||||
#include <map>
|
||||
#include <string>
|
||||
#include <google/protobuf/compiler/java/java_field.h>
|
||||
|
||||
namespace google {
|
||||
namespace protobuf {
|
||||
namespace compiler {
|
||||
namespace java {
|
||||
|
||||
class MessageFieldGenerator : public FieldGenerator {
|
||||
public:
|
||||
explicit MessageFieldGenerator(const FieldDescriptor* descriptor);
|
||||
~MessageFieldGenerator();
|
||||
|
||||
// implements FieldGenerator ---------------------------------------
|
||||
void GenerateMembers(io::Printer* printer) const;
|
||||
void GenerateBuilderMembers(io::Printer* printer) const;
|
||||
void GenerateInitializationCode(io::Printer* printer) const;
|
||||
void GenerateMergingCode(io::Printer* printer) const;
|
||||
void GenerateBuildingCode(io::Printer* printer) const;
|
||||
void GenerateParsingCode(io::Printer* printer) const;
|
||||
void GenerateSerializationCode(io::Printer* printer) const;
|
||||
void GenerateSerializedSizeCode(io::Printer* printer) const;
|
||||
|
||||
string GetBoxedType() const;
|
||||
|
||||
private:
|
||||
const FieldDescriptor* descriptor_;
|
||||
map<string, string> variables_;
|
||||
|
||||
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(MessageFieldGenerator);
|
||||
};
|
||||
|
||||
class RepeatedMessageFieldGenerator : public FieldGenerator {
|
||||
public:
|
||||
explicit RepeatedMessageFieldGenerator(const FieldDescriptor* descriptor);
|
||||
~RepeatedMessageFieldGenerator();
|
||||
|
||||
// implements FieldGenerator ---------------------------------------
|
||||
void GenerateMembers(io::Printer* printer) const;
|
||||
void GenerateBuilderMembers(io::Printer* printer) const;
|
||||
void GenerateInitializationCode(io::Printer* printer) const;
|
||||
void GenerateMergingCode(io::Printer* printer) const;
|
||||
void GenerateBuildingCode(io::Printer* printer) const;
|
||||
void GenerateParsingCode(io::Printer* printer) const;
|
||||
void GenerateSerializationCode(io::Printer* printer) const;
|
||||
void GenerateSerializedSizeCode(io::Printer* printer) const;
|
||||
|
||||
string GetBoxedType() const;
|
||||
|
||||
private:
|
||||
const FieldDescriptor* descriptor_;
|
||||
map<string, string> variables_;
|
||||
|
||||
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(RepeatedMessageFieldGenerator);
|
||||
};
|
||||
|
||||
} // namespace java
|
||||
} // namespace compiler
|
||||
} // namespace protobuf
|
||||
|
||||
} // namespace google
|
||||
#endif // GOOGLE_PROTOBUF_COMPILER_JAVA_MESSAGE_FIELD_H__
|
||||
// Protocol Buffers - Google's data interchange format
|
||||
// Copyright 2008 Google Inc. All rights reserved.
|
||||
// http://code.google.com/p/protobuf/
|
||||
//
|
||||
// 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: kenton@google.com (Kenton Varda)
|
||||
// Based on original Protocol Buffers design by
|
||||
// Sanjay Ghemawat, Jeff Dean, and others.
|
||||
|
||||
#ifndef GOOGLE_PROTOBUF_COMPILER_JAVA_MESSAGE_FIELD_H__
|
||||
#define GOOGLE_PROTOBUF_COMPILER_JAVA_MESSAGE_FIELD_H__
|
||||
|
||||
#include <map>
|
||||
#include <string>
|
||||
#include <google/protobuf/compiler/java/java_field.h>
|
||||
|
||||
namespace google {
|
||||
namespace protobuf {
|
||||
namespace compiler {
|
||||
namespace java {
|
||||
|
||||
class MessageFieldGenerator : public FieldGenerator {
|
||||
public:
|
||||
explicit MessageFieldGenerator(const FieldDescriptor* descriptor);
|
||||
~MessageFieldGenerator();
|
||||
|
||||
// implements FieldGenerator ---------------------------------------
|
||||
void GenerateMembers(io::Printer* printer) const;
|
||||
void GenerateBuilderMembers(io::Printer* printer) const;
|
||||
void GenerateInitializationCode(io::Printer* printer) const;
|
||||
void GenerateMergingCode(io::Printer* printer) const;
|
||||
void GenerateBuildingCode(io::Printer* printer) const;
|
||||
void GenerateParsingCode(io::Printer* printer) const;
|
||||
void GenerateSerializationCode(io::Printer* printer) const;
|
||||
void GenerateSerializedSizeCode(io::Printer* printer) const;
|
||||
|
||||
string GetBoxedType() const;
|
||||
|
||||
private:
|
||||
const FieldDescriptor* descriptor_;
|
||||
map<string, string> variables_;
|
||||
|
||||
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(MessageFieldGenerator);
|
||||
};
|
||||
|
||||
class RepeatedMessageFieldGenerator : public FieldGenerator {
|
||||
public:
|
||||
explicit RepeatedMessageFieldGenerator(const FieldDescriptor* descriptor);
|
||||
~RepeatedMessageFieldGenerator();
|
||||
|
||||
// implements FieldGenerator ---------------------------------------
|
||||
void GenerateMembers(io::Printer* printer) const;
|
||||
void GenerateBuilderMembers(io::Printer* printer) const;
|
||||
void GenerateInitializationCode(io::Printer* printer) const;
|
||||
void GenerateMergingCode(io::Printer* printer) const;
|
||||
void GenerateBuildingCode(io::Printer* printer) const;
|
||||
void GenerateParsingCode(io::Printer* printer) const;
|
||||
void GenerateSerializationCode(io::Printer* printer) const;
|
||||
void GenerateSerializedSizeCode(io::Printer* printer) const;
|
||||
|
||||
string GetBoxedType() const;
|
||||
|
||||
private:
|
||||
const FieldDescriptor* descriptor_;
|
||||
map<string, string> variables_;
|
||||
|
||||
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(RepeatedMessageFieldGenerator);
|
||||
};
|
||||
|
||||
} // namespace java
|
||||
} // namespace compiler
|
||||
} // namespace protobuf
|
||||
|
||||
} // namespace google
|
||||
#endif // GOOGLE_PROTOBUF_COMPILER_JAVA_MESSAGE_FIELD_H__
|
||||
|
||||
+101
-101
@@ -1,101 +1,101 @@
|
||||
// Protocol Buffers - Google's data interchange format
|
||||
// Copyright 2008 Google Inc. All rights reserved.
|
||||
// http://code.google.com/p/protobuf/
|
||||
//
|
||||
// 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: kenton@google.com (Kenton Varda)
|
||||
// Based on original Protocol Buffers design by
|
||||
// Sanjay Ghemawat, Jeff Dean, and others.
|
||||
|
||||
#ifndef GOOGLE_PROTOBUF_COMPILER_JAVA_PRIMITIVE_FIELD_H__
|
||||
#define GOOGLE_PROTOBUF_COMPILER_JAVA_PRIMITIVE_FIELD_H__
|
||||
|
||||
#include <map>
|
||||
#include <string>
|
||||
#include <google/protobuf/compiler/java/java_field.h>
|
||||
|
||||
namespace google {
|
||||
namespace protobuf {
|
||||
namespace compiler {
|
||||
namespace java {
|
||||
|
||||
class PrimitiveFieldGenerator : public FieldGenerator {
|
||||
public:
|
||||
explicit PrimitiveFieldGenerator(const FieldDescriptor* descriptor);
|
||||
~PrimitiveFieldGenerator();
|
||||
|
||||
// implements FieldGenerator ---------------------------------------
|
||||
void GenerateMembers(io::Printer* printer) const;
|
||||
void GenerateBuilderMembers(io::Printer* printer) const;
|
||||
void GenerateInitializationCode(io::Printer* printer) const;
|
||||
void GenerateMergingCode(io::Printer* printer) const;
|
||||
void GenerateBuildingCode(io::Printer* printer) const;
|
||||
void GenerateParsingCode(io::Printer* printer) const;
|
||||
void GenerateSerializationCode(io::Printer* printer) const;
|
||||
void GenerateSerializedSizeCode(io::Printer* printer) const;
|
||||
|
||||
string GetBoxedType() const;
|
||||
|
||||
private:
|
||||
const FieldDescriptor* descriptor_;
|
||||
map<string, string> variables_;
|
||||
|
||||
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(PrimitiveFieldGenerator);
|
||||
};
|
||||
|
||||
class RepeatedPrimitiveFieldGenerator : public FieldGenerator {
|
||||
public:
|
||||
explicit RepeatedPrimitiveFieldGenerator(const FieldDescriptor* descriptor);
|
||||
~RepeatedPrimitiveFieldGenerator();
|
||||
|
||||
// implements FieldGenerator ---------------------------------------
|
||||
void GenerateMembers(io::Printer* printer) const;
|
||||
void GenerateBuilderMembers(io::Printer* printer) const;
|
||||
void GenerateInitializationCode(io::Printer* printer) const;
|
||||
void GenerateMergingCode(io::Printer* printer) const;
|
||||
void GenerateBuildingCode(io::Printer* printer) const;
|
||||
void GenerateParsingCode(io::Printer* printer) const;
|
||||
void GenerateParsingCodeFromPacked(io::Printer* printer) const;
|
||||
void GenerateSerializationCode(io::Printer* printer) const;
|
||||
void GenerateSerializedSizeCode(io::Printer* printer) const;
|
||||
|
||||
string GetBoxedType() const;
|
||||
|
||||
private:
|
||||
const FieldDescriptor* descriptor_;
|
||||
map<string, string> variables_;
|
||||
|
||||
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(RepeatedPrimitiveFieldGenerator);
|
||||
};
|
||||
|
||||
} // namespace java
|
||||
} // namespace compiler
|
||||
} // namespace protobuf
|
||||
|
||||
} // namespace google
|
||||
#endif // GOOGLE_PROTOBUF_COMPILER_JAVA_PRIMITIVE_FIELD_H__
|
||||
// Protocol Buffers - Google's data interchange format
|
||||
// Copyright 2008 Google Inc. All rights reserved.
|
||||
// http://code.google.com/p/protobuf/
|
||||
//
|
||||
// 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: kenton@google.com (Kenton Varda)
|
||||
// Based on original Protocol Buffers design by
|
||||
// Sanjay Ghemawat, Jeff Dean, and others.
|
||||
|
||||
#ifndef GOOGLE_PROTOBUF_COMPILER_JAVA_PRIMITIVE_FIELD_H__
|
||||
#define GOOGLE_PROTOBUF_COMPILER_JAVA_PRIMITIVE_FIELD_H__
|
||||
|
||||
#include <map>
|
||||
#include <string>
|
||||
#include <google/protobuf/compiler/java/java_field.h>
|
||||
|
||||
namespace google {
|
||||
namespace protobuf {
|
||||
namespace compiler {
|
||||
namespace java {
|
||||
|
||||
class PrimitiveFieldGenerator : public FieldGenerator {
|
||||
public:
|
||||
explicit PrimitiveFieldGenerator(const FieldDescriptor* descriptor);
|
||||
~PrimitiveFieldGenerator();
|
||||
|
||||
// implements FieldGenerator ---------------------------------------
|
||||
void GenerateMembers(io::Printer* printer) const;
|
||||
void GenerateBuilderMembers(io::Printer* printer) const;
|
||||
void GenerateInitializationCode(io::Printer* printer) const;
|
||||
void GenerateMergingCode(io::Printer* printer) const;
|
||||
void GenerateBuildingCode(io::Printer* printer) const;
|
||||
void GenerateParsingCode(io::Printer* printer) const;
|
||||
void GenerateSerializationCode(io::Printer* printer) const;
|
||||
void GenerateSerializedSizeCode(io::Printer* printer) const;
|
||||
|
||||
string GetBoxedType() const;
|
||||
|
||||
private:
|
||||
const FieldDescriptor* descriptor_;
|
||||
map<string, string> variables_;
|
||||
|
||||
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(PrimitiveFieldGenerator);
|
||||
};
|
||||
|
||||
class RepeatedPrimitiveFieldGenerator : public FieldGenerator {
|
||||
public:
|
||||
explicit RepeatedPrimitiveFieldGenerator(const FieldDescriptor* descriptor);
|
||||
~RepeatedPrimitiveFieldGenerator();
|
||||
|
||||
// implements FieldGenerator ---------------------------------------
|
||||
void GenerateMembers(io::Printer* printer) const;
|
||||
void GenerateBuilderMembers(io::Printer* printer) const;
|
||||
void GenerateInitializationCode(io::Printer* printer) const;
|
||||
void GenerateMergingCode(io::Printer* printer) const;
|
||||
void GenerateBuildingCode(io::Printer* printer) const;
|
||||
void GenerateParsingCode(io::Printer* printer) const;
|
||||
void GenerateParsingCodeFromPacked(io::Printer* printer) const;
|
||||
void GenerateSerializationCode(io::Printer* printer) const;
|
||||
void GenerateSerializedSizeCode(io::Printer* printer) const;
|
||||
|
||||
string GetBoxedType() const;
|
||||
|
||||
private:
|
||||
const FieldDescriptor* descriptor_;
|
||||
map<string, string> variables_;
|
||||
|
||||
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(RepeatedPrimitiveFieldGenerator);
|
||||
};
|
||||
|
||||
} // namespace java
|
||||
} // namespace compiler
|
||||
} // namespace protobuf
|
||||
|
||||
} // namespace google
|
||||
#endif // GOOGLE_PROTOBUF_COMPILER_JAVA_PRIMITIVE_FIELD_H__
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user