├── .gitignore ├── .travis.yml ├── LICENSE ├── Makefile ├── README.md ├── bigTest.cc ├── bigTest.py ├── gtest ├── CHANGES ├── CONTRIBUTORS ├── LICENSE ├── README ├── include │ └── gtest │ │ ├── gtest-death-test.h │ │ ├── gtest-message.h │ │ ├── gtest-param-test.h │ │ ├── gtest-param-test.h.pump │ │ ├── gtest-printers.h │ │ ├── gtest-spi.h │ │ ├── gtest-test-part.h │ │ ├── gtest-typed-test.h │ │ ├── gtest.h │ │ ├── gtest_pred_impl.h │ │ ├── gtest_prod.h │ │ └── internal │ │ ├── gtest-death-test-internal.h │ │ ├── gtest-filepath.h │ │ ├── gtest-internal.h │ │ ├── gtest-linked_ptr.h │ │ ├── gtest-param-util-generated.h │ │ ├── gtest-param-util-generated.h.pump │ │ ├── gtest-param-util.h │ │ ├── gtest-port.h │ │ ├── gtest-string.h │ │ ├── gtest-tuple.h │ │ ├── gtest-tuple.h.pump │ │ ├── gtest-type-util.h │ │ └── gtest-type-util.h.pump └── src │ ├── gtest-all.cc │ ├── gtest-death-test.cc │ ├── gtest-filepath.cc │ ├── gtest-internal-inl.h │ ├── gtest-port.cc │ ├── gtest-printers.cc │ ├── gtest-test-part.cc │ ├── gtest-typed-test.cc │ ├── gtest.cc │ └── gtest_main.cc ├── in.txt ├── iptree.c ├── iptree.h ├── out1 ├── out2 ├── test.c ├── test_data.json ├── test_data1.json └── test_iptree.cc /.gitignore: -------------------------------------------------------------------------------- 1 | *.o 2 | *.a 3 | *.so 4 | *.swp 5 | gtest_main.a 6 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: c 2 | os: linux 3 | sudo: required 4 | dist: trusty 5 | before_install: 6 | - sudo apt-get update -qq 7 | - sudo apt-get install -qq build-essential 8 | script: 9 | - make 10 | - "./test_gtest" 11 | compiler: clang 12 | notifications: 13 | email: 14 | - zmap-devel@umich.edu 15 | slack: 16 | secure: d/cFgYYNuVisTw+OijKf5tDe9RNsHS2lkgYmGXXOppMuMu1Hq966VCP04mLbdlYeeR1cpxgCzK7dpChommw9H7/KOI0EpdfJ4KHJ1nnimzW3TRQWNNbchkat5YezeSJH2J4nuXlbrRIk/oKEruimu8Bo0bYdH+NXbQSBLdYJL4y+1KlU6KgUI8KE6XZi19TTbpy538WsbZJ/8RgsbRztOsXsLhHA0EdspxuSAC1114kcbFDLQsThIRTg7dmCt0uQsbkiw8vkvpnSSoQzU+1vyTVlkTT6DJe6WRXPn689NJSQ+oIwrEJ8yunFSOYhaSypX2eHVkMmWIwkzetBKLpzWC24O59t8vnH8YaFjKFEEeHDIx+WcmHVERnA1epCERb4PJC2B83FuiikjZ8jt5MSvdZm81ypR3ozw7liiMEi5C35h0mRofI5Qfrw325KvC+bKOgZiHoceni7+OY3qJu6GpUFAaxvZcx/t0H9lWisTsmBOEidWnGX4STGa4uFNlne3IxHgRA7Yd5RXN38qIrY3xVMhlL2X0wMQFiXxfhnEPbMYdjwJjpwnCNKFiSbD+swkcqBGxRvkL8onFSa2ekebFQVZtgeiC8svJ2bHyl5ZnvdYyZmk6L+gLrz7VXlc+bTnKfZ5VNZhWRK6oovROzeib9sSeOitVKtyqG8t+3rkQ0= 17 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | IPTree Copyright 2017 Regents of the University of Michigan 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | CC := gcc 2 | CXX := g++ 3 | CFLAGS := -std=c99 -Wall -Wextra -fPIC 4 | CXXFLAGS := -std=c++11 -Wall -Wextra 5 | # wasn't working for me LDFLAGS := "" 6 | OBJS = iptree.o 7 | 8 | all: gtest test_gtest shared_lib static_lib test_standalone 9 | 10 | gtest: libgtest_main.a 11 | 12 | libgtest_main.a: gtest/src/*.h gtest/src/*.cc gtest/include/gtest/*.h gtest/include/gtest/internal/*h 13 | g++ $(CXXFLAGS) -Igtest -Igtest/include gtest/src/gtest-all.cc gtest/src/gtest_main.cc -c 14 | ar -rv $@ gtest-all.o gtest_main.o 15 | 16 | test_gtest: $(OBJS) gtest test_iptree.cc 17 | g++ $(CXXFLAGS) $(OBJS) -pthread -Igtest/include test_iptree.cc libgtest_main.a -o $@ 18 | 19 | shared_lib: $(OBJS) 20 | gcc $(CFLAGS) -shared $(LDFLAGS) $(OBJS) -o libiptree.so 21 | 22 | static_lib: $(OBJS) 23 | ar -rv libiptree.a $(OBJS) 24 | 25 | test_standalone: $(objs) 26 | gcc $(CFLAGS) -g test.c $(OBJS) -o $@ 27 | 28 | test_big: $(objs) 29 | g++ $(CXXFLAGS) -I jsoncpp -I jsoncpp/include -g bigTest.cc $(OBJS) -L jsoncpp/build/debug/src/lib_json -l jsoncpp -o $@ 30 | 31 | .PHONY: clean 32 | 33 | clean: 34 | rm -f *.o *.a *.so test_gtest test_standalone test_big 35 | 36 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # iptree 2 | 3 | A space-optimized binary tree for storing IP addresses 4 | -------------------------------------------------------------------------------- /bigTest.cc: -------------------------------------------------------------------------------- 1 | #include "iptree.h" 2 | #include 3 | #include 4 | #include 5 | 6 | #include "json/json.h" 7 | using namespace std; 8 | 9 | void buildTree(std::string file, iptree_node_t * root) { 10 | std::string line; 11 | std::ifstream test_data(file, std::ifstream::in); 12 | while (test_data) { 13 | std::getline(test_data, line); 14 | Json::Value res; 15 | Json::Reader reader; 16 | bool parsingSuccessful = reader.parse(line, res); 17 | if(!parsingSuccessful) { 18 | return; 19 | } 20 | string *prefix = new string(res["bgp_prefix"].asString()); 21 | iptree_insert_str(root, prefix->c_str(), 22 | const_cast(prefix->c_str())); 23 | } 24 | } 25 | 26 | void testTree(std::string file, iptree_node_t * root) { 27 | std::string line; 28 | std::ifstream in_data(file, std::ifstream::in); 29 | while (in_data) { 30 | std::getline(in_data, line); 31 | if(line.size() < 7) { 32 | continue; 33 | } 34 | std::cout << iptree_lookup_best_str(root, line.c_str()) << endl; 35 | } 36 | } 37 | 38 | int main() { 39 | iptree_node_t * root = iptree_create(); 40 | buildTree("test_data.json", root); 41 | testTree("in.txt", root); 42 | iptree_destroy(root); 43 | return 0; 44 | } 45 | -------------------------------------------------------------------------------- /bigTest.py: -------------------------------------------------------------------------------- 1 | import SubnetTree 2 | import json 3 | 4 | def populateTrees(file, s): 5 | with open(file) as f: 6 | for line in f: 7 | data = json.loads(line) 8 | s[str(data["bgp_prefix"])] = str(data["bgp_prefix"]) 9 | 10 | def lookupAndComp(s, ip): 11 | #val1 = s[ip] 12 | val2 = iptree.lookup_best(i, ip) 13 | #if val1 != val2: 14 | # print "Subnet tree says: " + val1 + " but iptree says: " + val2 15 | 16 | s = SubnetTree.SubnetTree() 17 | populateTrees("test_data.json", s) 18 | with open("in.txt") as inF: 19 | for line in inF: 20 | print s[line.rstrip()] 21 | -------------------------------------------------------------------------------- /gtest/CHANGES: -------------------------------------------------------------------------------- 1 | Changes for 1.7.0: 2 | 3 | * New feature: death tests are supported on OpenBSD and in iOS 4 | simulator now. 5 | * New feature: Google Test now implements a protocol to allow 6 | a test runner to detect that a test program has exited 7 | prematurely and report it as a failure (before it would be 8 | falsely reported as a success if the exit code is 0). 9 | * New feature: Test::RecordProperty() can now be used outside of the 10 | lifespan of a test method, in which case it will be attributed to 11 | the current test case or the test program in the XML report. 12 | * New feature (potentially breaking): --gtest_list_tests now prints 13 | the type parameters and value parameters for each test. 14 | * Improvement: char pointers and char arrays are now escaped properly 15 | in failure messages. 16 | * Improvement: failure summary in XML reports now includes file and 17 | line information. 18 | * Improvement: the XML element now has a timestamp attribute. 19 | * Improvement: When --gtest_filter is specified, XML report now doesn't 20 | contain information about tests that are filtered out. 21 | * Fixed the bug where long --gtest_filter flag values are truncated in 22 | death tests. 23 | * Potentially breaking change: RUN_ALL_TESTS() is now implemented as a 24 | function instead of a macro in order to work better with Clang. 25 | * Compatibility fixes with C++ 11 and various platforms. 26 | * Bug/warning fixes. 27 | 28 | Changes for 1.6.0: 29 | 30 | * New feature: ADD_FAILURE_AT() for reporting a test failure at the 31 | given source location -- useful for writing testing utilities. 32 | * New feature: the universal value printer is moved from Google Mock 33 | to Google Test. 34 | * New feature: type parameters and value parameters are reported in 35 | the XML report now. 36 | * A gtest_disable_pthreads CMake option. 37 | * Colored output works in GNU Screen sessions now. 38 | * Parameters of value-parameterized tests are now printed in the 39 | textual output. 40 | * Failures from ad hoc test assertions run before RUN_ALL_TESTS() are 41 | now correctly reported. 42 | * Arguments of ASSERT_XY and EXPECT_XY no longer need to support << to 43 | ostream. 44 | * More complete handling of exceptions. 45 | * GTEST_ASSERT_XY can be used instead of ASSERT_XY in case the latter 46 | name is already used by another library. 47 | * --gtest_catch_exceptions is now true by default, allowing a test 48 | program to continue after an exception is thrown. 49 | * Value-parameterized test fixtures can now derive from Test and 50 | WithParamInterface separately, easing conversion of legacy tests. 51 | * Death test messages are clearly marked to make them more 52 | distinguishable from other messages. 53 | * Compatibility fixes for Android, Google Native Client, MinGW, HP UX, 54 | PowerPC, Lucid autotools, libCStd, Sun C++, Borland C++ Builder (Code Gear), 55 | IBM XL C++ (Visual Age C++), and C++0x. 56 | * Bug fixes and implementation clean-ups. 57 | * Potentially incompatible changes: disables the harmful 'make install' 58 | command in autotools. 59 | 60 | Changes for 1.5.0: 61 | 62 | * New feature: assertions can be safely called in multiple threads 63 | where the pthreads library is available. 64 | * New feature: predicates used inside EXPECT_TRUE() and friends 65 | can now generate custom failure messages. 66 | * New feature: Google Test can now be compiled as a DLL. 67 | * New feature: fused source files are included. 68 | * New feature: prints help when encountering unrecognized Google Test flags. 69 | * Experimental feature: CMake build script (requires CMake 2.6.4+). 70 | * Experimental feature: the Pump script for meta programming. 71 | * double values streamed to an assertion are printed with enough precision 72 | to differentiate any two different values. 73 | * Google Test now works on Solaris and AIX. 74 | * Build and test script improvements. 75 | * Bug fixes and implementation clean-ups. 76 | 77 | Potentially breaking changes: 78 | 79 | * Stopped supporting VC++ 7.1 with exceptions disabled. 80 | * Dropped support for 'make install'. 81 | 82 | Changes for 1.4.0: 83 | 84 | * New feature: the event listener API 85 | * New feature: test shuffling 86 | * New feature: the XML report format is closer to junitreport and can 87 | be parsed by Hudson now. 88 | * New feature: when a test runs under Visual Studio, its failures are 89 | integrated in the IDE. 90 | * New feature: /MD(d) versions of VC++ projects. 91 | * New feature: elapsed time for the tests is printed by default. 92 | * New feature: comes with a TR1 tuple implementation such that Boost 93 | is no longer needed for Combine(). 94 | * New feature: EXPECT_DEATH_IF_SUPPORTED macro and friends. 95 | * New feature: the Xcode project can now produce static gtest 96 | libraries in addition to a framework. 97 | * Compatibility fixes for Solaris, Cygwin, minGW, Windows Mobile, 98 | Symbian, gcc, and C++Builder. 99 | * Bug fixes and implementation clean-ups. 100 | 101 | Changes for 1.3.0: 102 | 103 | * New feature: death tests on Windows, Cygwin, and Mac. 104 | * New feature: ability to use Google Test assertions in other testing 105 | frameworks. 106 | * New feature: ability to run disabled test via 107 | --gtest_also_run_disabled_tests. 108 | * New feature: the --help flag for printing the usage. 109 | * New feature: access to Google Test flag values in user code. 110 | * New feature: a script that packs Google Test into one .h and one 111 | .cc file for easy deployment. 112 | * New feature: support for distributing test functions to multiple 113 | machines (requires support from the test runner). 114 | * Bug fixes and implementation clean-ups. 115 | 116 | Changes for 1.2.1: 117 | 118 | * Compatibility fixes for Linux IA-64 and IBM z/OS. 119 | * Added support for using Boost and other TR1 implementations. 120 | * Changes to the build scripts to support upcoming release of Google C++ 121 | Mocking Framework. 122 | * Added Makefile to the distribution package. 123 | * Improved build instructions in README. 124 | 125 | Changes for 1.2.0: 126 | 127 | * New feature: value-parameterized tests. 128 | * New feature: the ASSERT/EXPECT_(NON)FATAL_FAILURE(_ON_ALL_THREADS) 129 | macros. 130 | * Changed the XML report format to match JUnit/Ant's. 131 | * Added tests to the Xcode project. 132 | * Added scons/SConscript for building with SCons. 133 | * Added src/gtest-all.cc for building Google Test from a single file. 134 | * Fixed compatibility with Solaris and z/OS. 135 | * Enabled running Python tests on systems with python 2.3 installed, 136 | e.g. Mac OS X 10.4. 137 | * Bug fixes. 138 | 139 | Changes for 1.1.0: 140 | 141 | * New feature: type-parameterized tests. 142 | * New feature: exception assertions. 143 | * New feature: printing elapsed time of tests. 144 | * Improved the robustness of death tests. 145 | * Added an Xcode project and samples. 146 | * Adjusted the output format on Windows to be understandable by Visual Studio. 147 | * Minor bug fixes. 148 | 149 | Changes for 1.0.1: 150 | 151 | * Added project files for Visual Studio 7.1. 152 | * Fixed issues with compiling on Mac OS X. 153 | * Fixed issues with compiling on Cygwin. 154 | 155 | Changes for 1.0.0: 156 | 157 | * Initial Open Source release of Google Test 158 | -------------------------------------------------------------------------------- /gtest/CONTRIBUTORS: -------------------------------------------------------------------------------- 1 | # This file contains a list of people who've made non-trivial 2 | # contribution to the Google C++ Testing Framework project. People 3 | # who commit code to the project are encouraged to add their names 4 | # here. Please keep the list sorted by first names. 5 | 6 | Ajay Joshi 7 | Balázs Dán 8 | Bharat Mediratta 9 | Chandler Carruth 10 | Chris Prince 11 | Chris Taylor 12 | Dan Egnor 13 | Eric Roman 14 | Hady Zalek 15 | Jeffrey Yasskin 16 | Jói Sigurðsson 17 | Keir Mierle 18 | Keith Ray 19 | Kenton Varda 20 | Manuel Klimek 21 | Markus Heule 22 | Mika Raento 23 | Miklós Fazekas 24 | Pasi Valminen 25 | Patrick Hanna 26 | Patrick Riley 27 | Peter Kaminski 28 | Preston Jackson 29 | Rainer Klaffenboeck 30 | Russ Cox 31 | Russ Rufer 32 | Sean Mcafee 33 | Sigurður Ásgeirsson 34 | Tracy Bialik 35 | Vadim Berman 36 | Vlad Losev 37 | Zhanyong Wan 38 | -------------------------------------------------------------------------------- /gtest/LICENSE: -------------------------------------------------------------------------------- 1 | Copyright 2008, Google Inc. 2 | All rights reserved. 3 | 4 | Redistribution and use in source and binary forms, with or without 5 | modification, are permitted provided that the following conditions are 6 | met: 7 | 8 | * Redistributions of source code must retain the above copyright 9 | notice, this list of conditions and the following disclaimer. 10 | * Redistributions in binary form must reproduce the above 11 | copyright notice, this list of conditions and the following disclaimer 12 | in the documentation and/or other materials provided with the 13 | distribution. 14 | * Neither the name of Google Inc. nor the names of its 15 | contributors may be used to endorse or promote products derived from 16 | this software without specific prior written permission. 17 | 18 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 19 | "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 20 | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 21 | A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 22 | OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 23 | SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 24 | LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 25 | DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 26 | THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 27 | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 28 | OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 29 | -------------------------------------------------------------------------------- /gtest/include/gtest/gtest-death-test.h: -------------------------------------------------------------------------------- 1 | // Copyright 2005, Google Inc. 2 | // All rights reserved. 3 | // 4 | // Redistribution and use in source and binary forms, with or without 5 | // modification, are permitted provided that the following conditions are 6 | // met: 7 | // 8 | // * Redistributions of source code must retain the above copyright 9 | // notice, this list of conditions and the following disclaimer. 10 | // * Redistributions in binary form must reproduce the above 11 | // copyright notice, this list of conditions and the following disclaimer 12 | // in the documentation and/or other materials provided with the 13 | // distribution. 14 | // * Neither the name of Google Inc. nor the names of its 15 | // contributors may be used to endorse or promote products derived from 16 | // this software without specific prior written permission. 17 | // 18 | // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 19 | // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 20 | // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 21 | // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 22 | // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 23 | // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 24 | // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 25 | // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 26 | // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 27 | // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 28 | // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 29 | // 30 | // Author: wan@google.com (Zhanyong Wan) 31 | // 32 | // The Google C++ Testing Framework (Google Test) 33 | // 34 | // This header file defines the public API for death tests. It is 35 | // #included by gtest.h so a user doesn't need to include this 36 | // directly. 37 | 38 | #ifndef GTEST_INCLUDE_GTEST_GTEST_DEATH_TEST_H_ 39 | #define GTEST_INCLUDE_GTEST_GTEST_DEATH_TEST_H_ 40 | 41 | #include "gtest/internal/gtest-death-test-internal.h" 42 | 43 | namespace testing { 44 | 45 | // This flag controls the style of death tests. Valid values are "threadsafe", 46 | // meaning that the death test child process will re-execute the test binary 47 | // from the start, running only a single death test, or "fast", 48 | // meaning that the child process will execute the test logic immediately 49 | // after forking. 50 | GTEST_DECLARE_string_(death_test_style); 51 | 52 | #if GTEST_HAS_DEATH_TEST 53 | 54 | namespace internal { 55 | 56 | // Returns a Boolean value indicating whether the caller is currently 57 | // executing in the context of the death test child process. Tools such as 58 | // Valgrind heap checkers may need this to modify their behavior in death 59 | // tests. IMPORTANT: This is an internal utility. Using it may break the 60 | // implementation of death tests. User code MUST NOT use it. 61 | GTEST_API_ bool InDeathTestChild(); 62 | 63 | } // namespace internal 64 | 65 | // The following macros are useful for writing death tests. 66 | 67 | // Here's what happens when an ASSERT_DEATH* or EXPECT_DEATH* is 68 | // executed: 69 | // 70 | // 1. It generates a warning if there is more than one active 71 | // thread. This is because it's safe to fork() or clone() only 72 | // when there is a single thread. 73 | // 74 | // 2. The parent process clone()s a sub-process and runs the death 75 | // test in it; the sub-process exits with code 0 at the end of the 76 | // death test, if it hasn't exited already. 77 | // 78 | // 3. The parent process waits for the sub-process to terminate. 79 | // 80 | // 4. The parent process checks the exit code and error message of 81 | // the sub-process. 82 | // 83 | // Examples: 84 | // 85 | // ASSERT_DEATH(server.SendMessage(56, "Hello"), "Invalid port number"); 86 | // for (int i = 0; i < 5; i++) { 87 | // EXPECT_DEATH(server.ProcessRequest(i), 88 | // "Invalid request .* in ProcessRequest()") 89 | // << "Failed to die on request " << i; 90 | // } 91 | // 92 | // ASSERT_EXIT(server.ExitNow(), ::testing::ExitedWithCode(0), "Exiting"); 93 | // 94 | // bool KilledBySIGHUP(int exit_code) { 95 | // return WIFSIGNALED(exit_code) && WTERMSIG(exit_code) == SIGHUP; 96 | // } 97 | // 98 | // ASSERT_EXIT(client.HangUpServer(), KilledBySIGHUP, "Hanging up!"); 99 | // 100 | // On the regular expressions used in death tests: 101 | // 102 | // On POSIX-compliant systems (*nix), we use the library, 103 | // which uses the POSIX extended regex syntax. 104 | // 105 | // On other platforms (e.g. Windows), we only support a simple regex 106 | // syntax implemented as part of Google Test. This limited 107 | // implementation should be enough most of the time when writing 108 | // death tests; though it lacks many features you can find in PCRE 109 | // or POSIX extended regex syntax. For example, we don't support 110 | // union ("x|y"), grouping ("(xy)"), brackets ("[xy]"), and 111 | // repetition count ("x{5,7}"), among others. 112 | // 113 | // Below is the syntax that we do support. We chose it to be a 114 | // subset of both PCRE and POSIX extended regex, so it's easy to 115 | // learn wherever you come from. In the following: 'A' denotes a 116 | // literal character, period (.), or a single \\ escape sequence; 117 | // 'x' and 'y' denote regular expressions; 'm' and 'n' are for 118 | // natural numbers. 119 | // 120 | // c matches any literal character c 121 | // \\d matches any decimal digit 122 | // \\D matches any character that's not a decimal digit 123 | // \\f matches \f 124 | // \\n matches \n 125 | // \\r matches \r 126 | // \\s matches any ASCII whitespace, including \n 127 | // \\S matches any character that's not a whitespace 128 | // \\t matches \t 129 | // \\v matches \v 130 | // \\w matches any letter, _, or decimal digit 131 | // \\W matches any character that \\w doesn't match 132 | // \\c matches any literal character c, which must be a punctuation 133 | // . matches any single character except \n 134 | // A? matches 0 or 1 occurrences of A 135 | // A* matches 0 or many occurrences of A 136 | // A+ matches 1 or many occurrences of A 137 | // ^ matches the beginning of a string (not that of each line) 138 | // $ matches the end of a string (not that of each line) 139 | // xy matches x followed by y 140 | // 141 | // If you accidentally use PCRE or POSIX extended regex features 142 | // not implemented by us, you will get a run-time failure. In that 143 | // case, please try to rewrite your regular expression within the 144 | // above syntax. 145 | // 146 | // This implementation is *not* meant to be as highly tuned or robust 147 | // as a compiled regex library, but should perform well enough for a 148 | // death test, which already incurs significant overhead by launching 149 | // a child process. 150 | // 151 | // Known caveats: 152 | // 153 | // A "threadsafe" style death test obtains the path to the test 154 | // program from argv[0] and re-executes it in the sub-process. For 155 | // simplicity, the current implementation doesn't search the PATH 156 | // when launching the sub-process. This means that the user must 157 | // invoke the test program via a path that contains at least one 158 | // path separator (e.g. path/to/foo_test and 159 | // /absolute/path/to/bar_test are fine, but foo_test is not). This 160 | // is rarely a problem as people usually don't put the test binary 161 | // directory in PATH. 162 | // 163 | // TODO(wan@google.com): make thread-safe death tests search the PATH. 164 | 165 | // Asserts that a given statement causes the program to exit, with an 166 | // integer exit status that satisfies predicate, and emitting error output 167 | // that matches regex. 168 | # define ASSERT_EXIT(statement, predicate, regex) \ 169 | GTEST_DEATH_TEST_(statement, predicate, regex, GTEST_FATAL_FAILURE_) 170 | 171 | // Like ASSERT_EXIT, but continues on to successive tests in the 172 | // test case, if any: 173 | # define EXPECT_EXIT(statement, predicate, regex) \ 174 | GTEST_DEATH_TEST_(statement, predicate, regex, GTEST_NONFATAL_FAILURE_) 175 | 176 | // Asserts that a given statement causes the program to exit, either by 177 | // explicitly exiting with a nonzero exit code or being killed by a 178 | // signal, and emitting error output that matches regex. 179 | # define ASSERT_DEATH(statement, regex) \ 180 | ASSERT_EXIT(statement, ::testing::internal::ExitedUnsuccessfully, regex) 181 | 182 | // Like ASSERT_DEATH, but continues on to successive tests in the 183 | // test case, if any: 184 | # define EXPECT_DEATH(statement, regex) \ 185 | EXPECT_EXIT(statement, ::testing::internal::ExitedUnsuccessfully, regex) 186 | 187 | // Two predicate classes that can be used in {ASSERT,EXPECT}_EXIT*: 188 | 189 | // Tests that an exit code describes a normal exit with a given exit code. 190 | class GTEST_API_ ExitedWithCode { 191 | public: 192 | explicit ExitedWithCode(int exit_code); 193 | bool operator()(int exit_status) const; 194 | private: 195 | // No implementation - assignment is unsupported. 196 | void operator=(const ExitedWithCode& other); 197 | 198 | const int exit_code_; 199 | }; 200 | 201 | # if !GTEST_OS_WINDOWS 202 | // Tests that an exit code describes an exit due to termination by a 203 | // given signal. 204 | class GTEST_API_ KilledBySignal { 205 | public: 206 | explicit KilledBySignal(int signum); 207 | bool operator()(int exit_status) const; 208 | private: 209 | const int signum_; 210 | }; 211 | # endif // !GTEST_OS_WINDOWS 212 | 213 | // EXPECT_DEBUG_DEATH asserts that the given statements die in debug mode. 214 | // The death testing framework causes this to have interesting semantics, 215 | // since the sideeffects of the call are only visible in opt mode, and not 216 | // in debug mode. 217 | // 218 | // In practice, this can be used to test functions that utilize the 219 | // LOG(DFATAL) macro using the following style: 220 | // 221 | // int DieInDebugOr12(int* sideeffect) { 222 | // if (sideeffect) { 223 | // *sideeffect = 12; 224 | // } 225 | // LOG(DFATAL) << "death"; 226 | // return 12; 227 | // } 228 | // 229 | // TEST(TestCase, TestDieOr12WorksInDgbAndOpt) { 230 | // int sideeffect = 0; 231 | // // Only asserts in dbg. 232 | // EXPECT_DEBUG_DEATH(DieInDebugOr12(&sideeffect), "death"); 233 | // 234 | // #ifdef NDEBUG 235 | // // opt-mode has sideeffect visible. 236 | // EXPECT_EQ(12, sideeffect); 237 | // #else 238 | // // dbg-mode no visible sideeffect. 239 | // EXPECT_EQ(0, sideeffect); 240 | // #endif 241 | // } 242 | // 243 | // This will assert that DieInDebugReturn12InOpt() crashes in debug 244 | // mode, usually due to a DCHECK or LOG(DFATAL), but returns the 245 | // appropriate fallback value (12 in this case) in opt mode. If you 246 | // need to test that a function has appropriate side-effects in opt 247 | // mode, include assertions against the side-effects. A general 248 | // pattern for this is: 249 | // 250 | // EXPECT_DEBUG_DEATH({ 251 | // // Side-effects here will have an effect after this statement in 252 | // // opt mode, but none in debug mode. 253 | // EXPECT_EQ(12, DieInDebugOr12(&sideeffect)); 254 | // }, "death"); 255 | // 256 | # ifdef NDEBUG 257 | 258 | # define EXPECT_DEBUG_DEATH(statement, regex) \ 259 | GTEST_EXECUTE_STATEMENT_(statement, regex) 260 | 261 | # define ASSERT_DEBUG_DEATH(statement, regex) \ 262 | GTEST_EXECUTE_STATEMENT_(statement, regex) 263 | 264 | # else 265 | 266 | # define EXPECT_DEBUG_DEATH(statement, regex) \ 267 | EXPECT_DEATH(statement, regex) 268 | 269 | # define ASSERT_DEBUG_DEATH(statement, regex) \ 270 | ASSERT_DEATH(statement, regex) 271 | 272 | # endif // NDEBUG for EXPECT_DEBUG_DEATH 273 | #endif // GTEST_HAS_DEATH_TEST 274 | 275 | // EXPECT_DEATH_IF_SUPPORTED(statement, regex) and 276 | // ASSERT_DEATH_IF_SUPPORTED(statement, regex) expand to real death tests if 277 | // death tests are supported; otherwise they just issue a warning. This is 278 | // useful when you are combining death test assertions with normal test 279 | // assertions in one test. 280 | #if GTEST_HAS_DEATH_TEST 281 | # define EXPECT_DEATH_IF_SUPPORTED(statement, regex) \ 282 | EXPECT_DEATH(statement, regex) 283 | # define ASSERT_DEATH_IF_SUPPORTED(statement, regex) \ 284 | ASSERT_DEATH(statement, regex) 285 | #else 286 | # define EXPECT_DEATH_IF_SUPPORTED(statement, regex) \ 287 | GTEST_UNSUPPORTED_DEATH_TEST_(statement, regex, ) 288 | # define ASSERT_DEATH_IF_SUPPORTED(statement, regex) \ 289 | GTEST_UNSUPPORTED_DEATH_TEST_(statement, regex, return) 290 | #endif 291 | 292 | } // namespace testing 293 | 294 | #endif // GTEST_INCLUDE_GTEST_GTEST_DEATH_TEST_H_ 295 | -------------------------------------------------------------------------------- /gtest/include/gtest/gtest-message.h: -------------------------------------------------------------------------------- 1 | // Copyright 2005, Google Inc. 2 | // All rights reserved. 3 | // 4 | // Redistribution and use in source and binary forms, with or without 5 | // modification, are permitted provided that the following conditions are 6 | // met: 7 | // 8 | // * Redistributions of source code must retain the above copyright 9 | // notice, this list of conditions and the following disclaimer. 10 | // * Redistributions in binary form must reproduce the above 11 | // copyright notice, this list of conditions and the following disclaimer 12 | // in the documentation and/or other materials provided with the 13 | // distribution. 14 | // * Neither the name of Google Inc. nor the names of its 15 | // contributors may be used to endorse or promote products derived from 16 | // this software without specific prior written permission. 17 | // 18 | // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 19 | // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 20 | // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 21 | // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 22 | // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 23 | // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 24 | // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 25 | // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 26 | // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 27 | // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 28 | // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 29 | // 30 | // Author: wan@google.com (Zhanyong Wan) 31 | // 32 | // The Google C++ Testing Framework (Google Test) 33 | // 34 | // This header file defines the Message class. 35 | // 36 | // IMPORTANT NOTE: Due to limitation of the C++ language, we have to 37 | // leave some internal implementation details in this header file. 38 | // They are clearly marked by comments like this: 39 | // 40 | // // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM. 41 | // 42 | // Such code is NOT meant to be used by a user directly, and is subject 43 | // to CHANGE WITHOUT NOTICE. Therefore DO NOT DEPEND ON IT in a user 44 | // program! 45 | 46 | #ifndef GTEST_INCLUDE_GTEST_GTEST_MESSAGE_H_ 47 | #define GTEST_INCLUDE_GTEST_GTEST_MESSAGE_H_ 48 | 49 | #include 50 | 51 | #include "gtest/internal/gtest-port.h" 52 | 53 | // Ensures that there is at least one operator<< in the global namespace. 54 | // See Message& operator<<(...) below for why. 55 | void operator<<(const testing::internal::Secret&, int); 56 | 57 | namespace testing { 58 | 59 | // The Message class works like an ostream repeater. 60 | // 61 | // Typical usage: 62 | // 63 | // 1. You stream a bunch of values to a Message object. 64 | // It will remember the text in a stringstream. 65 | // 2. Then you stream the Message object to an ostream. 66 | // This causes the text in the Message to be streamed 67 | // to the ostream. 68 | // 69 | // For example; 70 | // 71 | // testing::Message foo; 72 | // foo << 1 << " != " << 2; 73 | // std::cout << foo; 74 | // 75 | // will print "1 != 2". 76 | // 77 | // Message is not intended to be inherited from. In particular, its 78 | // destructor is not virtual. 79 | // 80 | // Note that stringstream behaves differently in gcc and in MSVC. You 81 | // can stream a NULL char pointer to it in the former, but not in the 82 | // latter (it causes an access violation if you do). The Message 83 | // class hides this difference by treating a NULL char pointer as 84 | // "(null)". 85 | class GTEST_API_ Message { 86 | private: 87 | // The type of basic IO manipulators (endl, ends, and flush) for 88 | // narrow streams. 89 | typedef std::ostream& (*BasicNarrowIoManip)(std::ostream&); 90 | 91 | public: 92 | // Constructs an empty Message. 93 | Message(); 94 | 95 | // Copy constructor. 96 | Message(const Message& msg) : ss_(new ::std::stringstream) { // NOLINT 97 | *ss_ << msg.GetString(); 98 | } 99 | 100 | // Constructs a Message from a C-string. 101 | explicit Message(const char* str) : ss_(new ::std::stringstream) { 102 | *ss_ << str; 103 | } 104 | 105 | #if GTEST_OS_SYMBIAN 106 | // Streams a value (either a pointer or not) to this object. 107 | template 108 | inline Message& operator <<(const T& value) { 109 | StreamHelper(typename internal::is_pointer::type(), value); 110 | return *this; 111 | } 112 | #else 113 | // Streams a non-pointer value to this object. 114 | template 115 | inline Message& operator <<(const T& val) { 116 | // Some libraries overload << for STL containers. These 117 | // overloads are defined in the global namespace instead of ::std. 118 | // 119 | // C++'s symbol lookup rule (i.e. Koenig lookup) says that these 120 | // overloads are visible in either the std namespace or the global 121 | // namespace, but not other namespaces, including the testing 122 | // namespace which Google Test's Message class is in. 123 | // 124 | // To allow STL containers (and other types that has a << operator 125 | // defined in the global namespace) to be used in Google Test 126 | // assertions, testing::Message must access the custom << operator 127 | // from the global namespace. With this using declaration, 128 | // overloads of << defined in the global namespace and those 129 | // visible via Koenig lookup are both exposed in this function. 130 | using ::operator <<; 131 | *ss_ << val; 132 | return *this; 133 | } 134 | 135 | // Streams a pointer value to this object. 136 | // 137 | // This function is an overload of the previous one. When you 138 | // stream a pointer to a Message, this definition will be used as it 139 | // is more specialized. (The C++ Standard, section 140 | // [temp.func.order].) If you stream a non-pointer, then the 141 | // previous definition will be used. 142 | // 143 | // The reason for this overload is that streaming a NULL pointer to 144 | // ostream is undefined behavior. Depending on the compiler, you 145 | // may get "0", "(nil)", "(null)", or an access violation. To 146 | // ensure consistent result across compilers, we always treat NULL 147 | // as "(null)". 148 | template 149 | inline Message& operator <<(T* const& pointer) { // NOLINT 150 | if (pointer == NULL) { 151 | *ss_ << "(null)"; 152 | } else { 153 | *ss_ << pointer; 154 | } 155 | return *this; 156 | } 157 | #endif // GTEST_OS_SYMBIAN 158 | 159 | // Since the basic IO manipulators are overloaded for both narrow 160 | // and wide streams, we have to provide this specialized definition 161 | // of operator <<, even though its body is the same as the 162 | // templatized version above. Without this definition, streaming 163 | // endl or other basic IO manipulators to Message will confuse the 164 | // compiler. 165 | Message& operator <<(BasicNarrowIoManip val) { 166 | *ss_ << val; 167 | return *this; 168 | } 169 | 170 | // Instead of 1/0, we want to see true/false for bool values. 171 | Message& operator <<(bool b) { 172 | return *this << (b ? "true" : "false"); 173 | } 174 | 175 | // These two overloads allow streaming a wide C string to a Message 176 | // using the UTF-8 encoding. 177 | Message& operator <<(const wchar_t* wide_c_str); 178 | Message& operator <<(wchar_t* wide_c_str); 179 | 180 | #if GTEST_HAS_STD_WSTRING 181 | // Converts the given wide string to a narrow string using the UTF-8 182 | // encoding, and streams the result to this Message object. 183 | Message& operator <<(const ::std::wstring& wstr); 184 | #endif // GTEST_HAS_STD_WSTRING 185 | 186 | #if GTEST_HAS_GLOBAL_WSTRING 187 | // Converts the given wide string to a narrow string using the UTF-8 188 | // encoding, and streams the result to this Message object. 189 | Message& operator <<(const ::wstring& wstr); 190 | #endif // GTEST_HAS_GLOBAL_WSTRING 191 | 192 | // Gets the text streamed to this object so far as an std::string. 193 | // Each '\0' character in the buffer is replaced with "\\0". 194 | // 195 | // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM. 196 | std::string GetString() const; 197 | 198 | private: 199 | 200 | #if GTEST_OS_SYMBIAN 201 | // These are needed as the Nokia Symbian Compiler cannot decide between 202 | // const T& and const T* in a function template. The Nokia compiler _can_ 203 | // decide between class template specializations for T and T*, so a 204 | // tr1::type_traits-like is_pointer works, and we can overload on that. 205 | template 206 | inline void StreamHelper(internal::true_type /*is_pointer*/, T* pointer) { 207 | if (pointer == NULL) { 208 | *ss_ << "(null)"; 209 | } else { 210 | *ss_ << pointer; 211 | } 212 | } 213 | template 214 | inline void StreamHelper(internal::false_type /*is_pointer*/, 215 | const T& value) { 216 | // See the comments in Message& operator <<(const T&) above for why 217 | // we need this using statement. 218 | using ::operator <<; 219 | *ss_ << value; 220 | } 221 | #endif // GTEST_OS_SYMBIAN 222 | 223 | // We'll hold the text streamed to this object here. 224 | const internal::scoped_ptr< ::std::stringstream> ss_; 225 | 226 | // We declare (but don't implement) this to prevent the compiler 227 | // from implementing the assignment operator. 228 | void operator=(const Message&); 229 | }; 230 | 231 | // Streams a Message to an ostream. 232 | inline std::ostream& operator <<(std::ostream& os, const Message& sb) { 233 | return os << sb.GetString(); 234 | } 235 | 236 | namespace internal { 237 | 238 | // Converts a streamable value to an std::string. A NULL pointer is 239 | // converted to "(null)". When the input value is a ::string, 240 | // ::std::string, ::wstring, or ::std::wstring object, each NUL 241 | // character in it is replaced with "\\0". 242 | template 243 | std::string StreamableToString(const T& streamable) { 244 | return (Message() << streamable).GetString(); 245 | } 246 | 247 | } // namespace internal 248 | } // namespace testing 249 | 250 | #endif // GTEST_INCLUDE_GTEST_GTEST_MESSAGE_H_ 251 | -------------------------------------------------------------------------------- /gtest/include/gtest/gtest-spi.h: -------------------------------------------------------------------------------- 1 | // Copyright 2007, Google Inc. 2 | // All rights reserved. 3 | // 4 | // Redistribution and use in source and binary forms, with or without 5 | // modification, are permitted provided that the following conditions are 6 | // met: 7 | // 8 | // * Redistributions of source code must retain the above copyright 9 | // notice, this list of conditions and the following disclaimer. 10 | // * Redistributions in binary form must reproduce the above 11 | // copyright notice, this list of conditions and the following disclaimer 12 | // in the documentation and/or other materials provided with the 13 | // distribution. 14 | // * Neither the name of Google Inc. nor the names of its 15 | // contributors may be used to endorse or promote products derived from 16 | // this software without specific prior written permission. 17 | // 18 | // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 19 | // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 20 | // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 21 | // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 22 | // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 23 | // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 24 | // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 25 | // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 26 | // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 27 | // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 28 | // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 29 | // 30 | // Author: wan@google.com (Zhanyong Wan) 31 | // 32 | // Utilities for testing Google Test itself and code that uses Google Test 33 | // (e.g. frameworks built on top of Google Test). 34 | 35 | #ifndef GTEST_INCLUDE_GTEST_GTEST_SPI_H_ 36 | #define GTEST_INCLUDE_GTEST_GTEST_SPI_H_ 37 | 38 | #include "gtest/gtest.h" 39 | 40 | namespace testing { 41 | 42 | // This helper class can be used to mock out Google Test failure reporting 43 | // so that we can test Google Test or code that builds on Google Test. 44 | // 45 | // An object of this class appends a TestPartResult object to the 46 | // TestPartResultArray object given in the constructor whenever a Google Test 47 | // failure is reported. It can either intercept only failures that are 48 | // generated in the same thread that created this object or it can intercept 49 | // all generated failures. The scope of this mock object can be controlled with 50 | // the second argument to the two arguments constructor. 51 | class GTEST_API_ ScopedFakeTestPartResultReporter 52 | : public TestPartResultReporterInterface { 53 | public: 54 | // The two possible mocking modes of this object. 55 | enum InterceptMode { 56 | INTERCEPT_ONLY_CURRENT_THREAD, // Intercepts only thread local failures. 57 | INTERCEPT_ALL_THREADS // Intercepts all failures. 58 | }; 59 | 60 | // The c'tor sets this object as the test part result reporter used 61 | // by Google Test. The 'result' parameter specifies where to report the 62 | // results. This reporter will only catch failures generated in the current 63 | // thread. DEPRECATED 64 | explicit ScopedFakeTestPartResultReporter(TestPartResultArray* result); 65 | 66 | // Same as above, but you can choose the interception scope of this object. 67 | ScopedFakeTestPartResultReporter(InterceptMode intercept_mode, 68 | TestPartResultArray* result); 69 | 70 | // The d'tor restores the previous test part result reporter. 71 | virtual ~ScopedFakeTestPartResultReporter(); 72 | 73 | // Appends the TestPartResult object to the TestPartResultArray 74 | // received in the constructor. 75 | // 76 | // This method is from the TestPartResultReporterInterface 77 | // interface. 78 | virtual void ReportTestPartResult(const TestPartResult& result); 79 | private: 80 | void Init(); 81 | 82 | const InterceptMode intercept_mode_; 83 | TestPartResultReporterInterface* old_reporter_; 84 | TestPartResultArray* const result_; 85 | 86 | GTEST_DISALLOW_COPY_AND_ASSIGN_(ScopedFakeTestPartResultReporter); 87 | }; 88 | 89 | namespace internal { 90 | 91 | // A helper class for implementing EXPECT_FATAL_FAILURE() and 92 | // EXPECT_NONFATAL_FAILURE(). Its destructor verifies that the given 93 | // TestPartResultArray contains exactly one failure that has the given 94 | // type and contains the given substring. If that's not the case, a 95 | // non-fatal failure will be generated. 96 | class GTEST_API_ SingleFailureChecker { 97 | public: 98 | // The constructor remembers the arguments. 99 | SingleFailureChecker(const TestPartResultArray* results, 100 | TestPartResult::Type type, 101 | const string& substr); 102 | ~SingleFailureChecker(); 103 | private: 104 | const TestPartResultArray* const results_; 105 | const TestPartResult::Type type_; 106 | const string substr_; 107 | 108 | GTEST_DISALLOW_COPY_AND_ASSIGN_(SingleFailureChecker); 109 | }; 110 | 111 | } // namespace internal 112 | 113 | } // namespace testing 114 | 115 | // A set of macros for testing Google Test assertions or code that's expected 116 | // to generate Google Test fatal failures. It verifies that the given 117 | // statement will cause exactly one fatal Google Test failure with 'substr' 118 | // being part of the failure message. 119 | // 120 | // There are two different versions of this macro. EXPECT_FATAL_FAILURE only 121 | // affects and considers failures generated in the current thread and 122 | // EXPECT_FATAL_FAILURE_ON_ALL_THREADS does the same but for all threads. 123 | // 124 | // The verification of the assertion is done correctly even when the statement 125 | // throws an exception or aborts the current function. 126 | // 127 | // Known restrictions: 128 | // - 'statement' cannot reference local non-static variables or 129 | // non-static members of the current object. 130 | // - 'statement' cannot return a value. 131 | // - You cannot stream a failure message to this macro. 132 | // 133 | // Note that even though the implementations of the following two 134 | // macros are much alike, we cannot refactor them to use a common 135 | // helper macro, due to some peculiarity in how the preprocessor 136 | // works. The AcceptsMacroThatExpandsToUnprotectedComma test in 137 | // gtest_unittest.cc will fail to compile if we do that. 138 | #define EXPECT_FATAL_FAILURE(statement, substr) \ 139 | do { \ 140 | class GTestExpectFatalFailureHelper {\ 141 | public:\ 142 | static void Execute() { statement; }\ 143 | };\ 144 | ::testing::TestPartResultArray gtest_failures;\ 145 | ::testing::internal::SingleFailureChecker gtest_checker(\ 146 | >est_failures, ::testing::TestPartResult::kFatalFailure, (substr));\ 147 | {\ 148 | ::testing::ScopedFakeTestPartResultReporter gtest_reporter(\ 149 | ::testing::ScopedFakeTestPartResultReporter:: \ 150 | INTERCEPT_ONLY_CURRENT_THREAD, >est_failures);\ 151 | GTestExpectFatalFailureHelper::Execute();\ 152 | }\ 153 | } while (::testing::internal::AlwaysFalse()) 154 | 155 | #define EXPECT_FATAL_FAILURE_ON_ALL_THREADS(statement, substr) \ 156 | do { \ 157 | class GTestExpectFatalFailureHelper {\ 158 | public:\ 159 | static void Execute() { statement; }\ 160 | };\ 161 | ::testing::TestPartResultArray gtest_failures;\ 162 | ::testing::internal::SingleFailureChecker gtest_checker(\ 163 | >est_failures, ::testing::TestPartResult::kFatalFailure, (substr));\ 164 | {\ 165 | ::testing::ScopedFakeTestPartResultReporter gtest_reporter(\ 166 | ::testing::ScopedFakeTestPartResultReporter:: \ 167 | INTERCEPT_ALL_THREADS, >est_failures);\ 168 | GTestExpectFatalFailureHelper::Execute();\ 169 | }\ 170 | } while (::testing::internal::AlwaysFalse()) 171 | 172 | // A macro for testing Google Test assertions or code that's expected to 173 | // generate Google Test non-fatal failures. It asserts that the given 174 | // statement will cause exactly one non-fatal Google Test failure with 'substr' 175 | // being part of the failure message. 176 | // 177 | // There are two different versions of this macro. EXPECT_NONFATAL_FAILURE only 178 | // affects and considers failures generated in the current thread and 179 | // EXPECT_NONFATAL_FAILURE_ON_ALL_THREADS does the same but for all threads. 180 | // 181 | // 'statement' is allowed to reference local variables and members of 182 | // the current object. 183 | // 184 | // The verification of the assertion is done correctly even when the statement 185 | // throws an exception or aborts the current function. 186 | // 187 | // Known restrictions: 188 | // - You cannot stream a failure message to this macro. 189 | // 190 | // Note that even though the implementations of the following two 191 | // macros are much alike, we cannot refactor them to use a common 192 | // helper macro, due to some peculiarity in how the preprocessor 193 | // works. If we do that, the code won't compile when the user gives 194 | // EXPECT_NONFATAL_FAILURE() a statement that contains a macro that 195 | // expands to code containing an unprotected comma. The 196 | // AcceptsMacroThatExpandsToUnprotectedComma test in gtest_unittest.cc 197 | // catches that. 198 | // 199 | // For the same reason, we have to write 200 | // if (::testing::internal::AlwaysTrue()) { statement; } 201 | // instead of 202 | // GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement) 203 | // to avoid an MSVC warning on unreachable code. 204 | #define EXPECT_NONFATAL_FAILURE(statement, substr) \ 205 | do {\ 206 | ::testing::TestPartResultArray gtest_failures;\ 207 | ::testing::internal::SingleFailureChecker gtest_checker(\ 208 | >est_failures, ::testing::TestPartResult::kNonFatalFailure, \ 209 | (substr));\ 210 | {\ 211 | ::testing::ScopedFakeTestPartResultReporter gtest_reporter(\ 212 | ::testing::ScopedFakeTestPartResultReporter:: \ 213 | INTERCEPT_ONLY_CURRENT_THREAD, >est_failures);\ 214 | if (::testing::internal::AlwaysTrue()) { statement; }\ 215 | }\ 216 | } while (::testing::internal::AlwaysFalse()) 217 | 218 | #define EXPECT_NONFATAL_FAILURE_ON_ALL_THREADS(statement, substr) \ 219 | do {\ 220 | ::testing::TestPartResultArray gtest_failures;\ 221 | ::testing::internal::SingleFailureChecker gtest_checker(\ 222 | >est_failures, ::testing::TestPartResult::kNonFatalFailure, \ 223 | (substr));\ 224 | {\ 225 | ::testing::ScopedFakeTestPartResultReporter gtest_reporter(\ 226 | ::testing::ScopedFakeTestPartResultReporter::INTERCEPT_ALL_THREADS, \ 227 | >est_failures);\ 228 | if (::testing::internal::AlwaysTrue()) { statement; }\ 229 | }\ 230 | } while (::testing::internal::AlwaysFalse()) 231 | 232 | #endif // GTEST_INCLUDE_GTEST_GTEST_SPI_H_ 233 | -------------------------------------------------------------------------------- /gtest/include/gtest/gtest-test-part.h: -------------------------------------------------------------------------------- 1 | // Copyright 2008, Google Inc. 2 | // All rights reserved. 3 | // 4 | // Redistribution and use in source and binary forms, with or without 5 | // modification, are permitted provided that the following conditions are 6 | // met: 7 | // 8 | // * Redistributions of source code must retain the above copyright 9 | // notice, this list of conditions and the following disclaimer. 10 | // * Redistributions in binary form must reproduce the above 11 | // copyright notice, this list of conditions and the following disclaimer 12 | // in the documentation and/or other materials provided with the 13 | // distribution. 14 | // * Neither the name of Google Inc. nor the names of its 15 | // contributors may be used to endorse or promote products derived from 16 | // this software without specific prior written permission. 17 | // 18 | // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 19 | // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 20 | // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 21 | // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 22 | // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 23 | // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 24 | // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 25 | // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 26 | // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 27 | // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 28 | // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 29 | // 30 | // Author: mheule@google.com (Markus Heule) 31 | // 32 | 33 | #ifndef GTEST_INCLUDE_GTEST_GTEST_TEST_PART_H_ 34 | #define GTEST_INCLUDE_GTEST_GTEST_TEST_PART_H_ 35 | 36 | #include 37 | #include 38 | #include "gtest/internal/gtest-internal.h" 39 | #include "gtest/internal/gtest-string.h" 40 | 41 | namespace testing { 42 | 43 | // A copyable object representing the result of a test part (i.e. an 44 | // assertion or an explicit FAIL(), ADD_FAILURE(), or SUCCESS()). 45 | // 46 | // Don't inherit from TestPartResult as its destructor is not virtual. 47 | class GTEST_API_ TestPartResult { 48 | public: 49 | // The possible outcomes of a test part (i.e. an assertion or an 50 | // explicit SUCCEED(), FAIL(), or ADD_FAILURE()). 51 | enum Type { 52 | kSuccess, // Succeeded. 53 | kNonFatalFailure, // Failed but the test can continue. 54 | kFatalFailure // Failed and the test should be terminated. 55 | }; 56 | 57 | // C'tor. TestPartResult does NOT have a default constructor. 58 | // Always use this constructor (with parameters) to create a 59 | // TestPartResult object. 60 | TestPartResult(Type a_type, 61 | const char* a_file_name, 62 | int a_line_number, 63 | const char* a_message) 64 | : type_(a_type), 65 | file_name_(a_file_name == NULL ? "" : a_file_name), 66 | line_number_(a_line_number), 67 | summary_(ExtractSummary(a_message)), 68 | message_(a_message) { 69 | } 70 | 71 | // Gets the outcome of the test part. 72 | Type type() const { return type_; } 73 | 74 | // Gets the name of the source file where the test part took place, or 75 | // NULL if it's unknown. 76 | const char* file_name() const { 77 | return file_name_.empty() ? NULL : file_name_.c_str(); 78 | } 79 | 80 | // Gets the line in the source file where the test part took place, 81 | // or -1 if it's unknown. 82 | int line_number() const { return line_number_; } 83 | 84 | // Gets the summary of the failure message. 85 | const char* summary() const { return summary_.c_str(); } 86 | 87 | // Gets the message associated with the test part. 88 | const char* message() const { return message_.c_str(); } 89 | 90 | // Returns true iff the test part passed. 91 | bool passed() const { return type_ == kSuccess; } 92 | 93 | // Returns true iff the test part failed. 94 | bool failed() const { return type_ != kSuccess; } 95 | 96 | // Returns true iff the test part non-fatally failed. 97 | bool nonfatally_failed() const { return type_ == kNonFatalFailure; } 98 | 99 | // Returns true iff the test part fatally failed. 100 | bool fatally_failed() const { return type_ == kFatalFailure; } 101 | 102 | private: 103 | Type type_; 104 | 105 | // Gets the summary of the failure message by omitting the stack 106 | // trace in it. 107 | static std::string ExtractSummary(const char* message); 108 | 109 | // The name of the source file where the test part took place, or 110 | // "" if the source file is unknown. 111 | std::string file_name_; 112 | // The line in the source file where the test part took place, or -1 113 | // if the line number is unknown. 114 | int line_number_; 115 | std::string summary_; // The test failure summary. 116 | std::string message_; // The test failure message. 117 | }; 118 | 119 | // Prints a TestPartResult object. 120 | std::ostream& operator<<(std::ostream& os, const TestPartResult& result); 121 | 122 | // An array of TestPartResult objects. 123 | // 124 | // Don't inherit from TestPartResultArray as its destructor is not 125 | // virtual. 126 | class GTEST_API_ TestPartResultArray { 127 | public: 128 | TestPartResultArray() {} 129 | 130 | // Appends the given TestPartResult to the array. 131 | void Append(const TestPartResult& result); 132 | 133 | // Returns the TestPartResult at the given index (0-based). 134 | const TestPartResult& GetTestPartResult(int index) const; 135 | 136 | // Returns the number of TestPartResult objects in the array. 137 | int size() const; 138 | 139 | private: 140 | std::vector array_; 141 | 142 | GTEST_DISALLOW_COPY_AND_ASSIGN_(TestPartResultArray); 143 | }; 144 | 145 | // This interface knows how to report a test part result. 146 | class TestPartResultReporterInterface { 147 | public: 148 | virtual ~TestPartResultReporterInterface() {} 149 | 150 | virtual void ReportTestPartResult(const TestPartResult& result) = 0; 151 | }; 152 | 153 | namespace internal { 154 | 155 | // This helper class is used by {ASSERT|EXPECT}_NO_FATAL_FAILURE to check if a 156 | // statement generates new fatal failures. To do so it registers itself as the 157 | // current test part result reporter. Besides checking if fatal failures were 158 | // reported, it only delegates the reporting to the former result reporter. 159 | // The original result reporter is restored in the destructor. 160 | // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM. 161 | class GTEST_API_ HasNewFatalFailureHelper 162 | : public TestPartResultReporterInterface { 163 | public: 164 | HasNewFatalFailureHelper(); 165 | virtual ~HasNewFatalFailureHelper(); 166 | virtual void ReportTestPartResult(const TestPartResult& result); 167 | bool has_new_fatal_failure() const { return has_new_fatal_failure_; } 168 | private: 169 | bool has_new_fatal_failure_; 170 | TestPartResultReporterInterface* original_reporter_; 171 | 172 | GTEST_DISALLOW_COPY_AND_ASSIGN_(HasNewFatalFailureHelper); 173 | }; 174 | 175 | } // namespace internal 176 | 177 | } // namespace testing 178 | 179 | #endif // GTEST_INCLUDE_GTEST_GTEST_TEST_PART_H_ 180 | -------------------------------------------------------------------------------- /gtest/include/gtest/gtest-typed-test.h: -------------------------------------------------------------------------------- 1 | // Copyright 2008 Google Inc. 2 | // All Rights Reserved. 3 | // 4 | // Redistribution and use in source and binary forms, with or without 5 | // modification, are permitted provided that the following conditions are 6 | // met: 7 | // 8 | // * Redistributions of source code must retain the above copyright 9 | // notice, this list of conditions and the following disclaimer. 10 | // * Redistributions in binary form must reproduce the above 11 | // copyright notice, this list of conditions and the following disclaimer 12 | // in the documentation and/or other materials provided with the 13 | // distribution. 14 | // * Neither the name of Google Inc. nor the names of its 15 | // contributors may be used to endorse or promote products derived from 16 | // this software without specific prior written permission. 17 | // 18 | // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 19 | // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 20 | // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 21 | // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 22 | // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 23 | // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 24 | // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 25 | // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 26 | // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 27 | // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 28 | // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 29 | // 30 | // Author: wan@google.com (Zhanyong Wan) 31 | 32 | #ifndef GTEST_INCLUDE_GTEST_GTEST_TYPED_TEST_H_ 33 | #define GTEST_INCLUDE_GTEST_GTEST_TYPED_TEST_H_ 34 | 35 | // This header implements typed tests and type-parameterized tests. 36 | 37 | // Typed (aka type-driven) tests repeat the same test for types in a 38 | // list. You must know which types you want to test with when writing 39 | // typed tests. Here's how you do it: 40 | 41 | #if 0 42 | 43 | // First, define a fixture class template. It should be parameterized 44 | // by a type. Remember to derive it from testing::Test. 45 | template 46 | class FooTest : public testing::Test { 47 | public: 48 | ... 49 | typedef std::list List; 50 | static T shared_; 51 | T value_; 52 | }; 53 | 54 | // Next, associate a list of types with the test case, which will be 55 | // repeated for each type in the list. The typedef is necessary for 56 | // the macro to parse correctly. 57 | typedef testing::Types MyTypes; 58 | TYPED_TEST_CASE(FooTest, MyTypes); 59 | 60 | // If the type list contains only one type, you can write that type 61 | // directly without Types<...>: 62 | // TYPED_TEST_CASE(FooTest, int); 63 | 64 | // Then, use TYPED_TEST() instead of TEST_F() to define as many typed 65 | // tests for this test case as you want. 66 | TYPED_TEST(FooTest, DoesBlah) { 67 | // Inside a test, refer to TypeParam to get the type parameter. 68 | // Since we are inside a derived class template, C++ requires use to 69 | // visit the members of FooTest via 'this'. 70 | TypeParam n = this->value_; 71 | 72 | // To visit static members of the fixture, add the TestFixture:: 73 | // prefix. 74 | n += TestFixture::shared_; 75 | 76 | // To refer to typedefs in the fixture, add the "typename 77 | // TestFixture::" prefix. 78 | typename TestFixture::List values; 79 | values.push_back(n); 80 | ... 81 | } 82 | 83 | TYPED_TEST(FooTest, HasPropertyA) { ... } 84 | 85 | #endif // 0 86 | 87 | // Type-parameterized tests are abstract test patterns parameterized 88 | // by a type. Compared with typed tests, type-parameterized tests 89 | // allow you to define the test pattern without knowing what the type 90 | // parameters are. The defined pattern can be instantiated with 91 | // different types any number of times, in any number of translation 92 | // units. 93 | // 94 | // If you are designing an interface or concept, you can define a 95 | // suite of type-parameterized tests to verify properties that any 96 | // valid implementation of the interface/concept should have. Then, 97 | // each implementation can easily instantiate the test suite to verify 98 | // that it conforms to the requirements, without having to write 99 | // similar tests repeatedly. Here's an example: 100 | 101 | #if 0 102 | 103 | // First, define a fixture class template. It should be parameterized 104 | // by a type. Remember to derive it from testing::Test. 105 | template 106 | class FooTest : public testing::Test { 107 | ... 108 | }; 109 | 110 | // Next, declare that you will define a type-parameterized test case 111 | // (the _P suffix is for "parameterized" or "pattern", whichever you 112 | // prefer): 113 | TYPED_TEST_CASE_P(FooTest); 114 | 115 | // Then, use TYPED_TEST_P() to define as many type-parameterized tests 116 | // for this type-parameterized test case as you want. 117 | TYPED_TEST_P(FooTest, DoesBlah) { 118 | // Inside a test, refer to TypeParam to get the type parameter. 119 | TypeParam n = 0; 120 | ... 121 | } 122 | 123 | TYPED_TEST_P(FooTest, HasPropertyA) { ... } 124 | 125 | // Now the tricky part: you need to register all test patterns before 126 | // you can instantiate them. The first argument of the macro is the 127 | // test case name; the rest are the names of the tests in this test 128 | // case. 129 | REGISTER_TYPED_TEST_CASE_P(FooTest, 130 | DoesBlah, HasPropertyA); 131 | 132 | // Finally, you are free to instantiate the pattern with the types you 133 | // want. If you put the above code in a header file, you can #include 134 | // it in multiple C++ source files and instantiate it multiple times. 135 | // 136 | // To distinguish different instances of the pattern, the first 137 | // argument to the INSTANTIATE_* macro is a prefix that will be added 138 | // to the actual test case name. Remember to pick unique prefixes for 139 | // different instances. 140 | typedef testing::Types MyTypes; 141 | INSTANTIATE_TYPED_TEST_CASE_P(My, FooTest, MyTypes); 142 | 143 | // If the type list contains only one type, you can write that type 144 | // directly without Types<...>: 145 | // INSTANTIATE_TYPED_TEST_CASE_P(My, FooTest, int); 146 | 147 | #endif // 0 148 | 149 | #include "gtest/internal/gtest-port.h" 150 | #include "gtest/internal/gtest-type-util.h" 151 | 152 | // Implements typed tests. 153 | 154 | #if GTEST_HAS_TYPED_TEST 155 | 156 | // INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE. 157 | // 158 | // Expands to the name of the typedef for the type parameters of the 159 | // given test case. 160 | # define GTEST_TYPE_PARAMS_(TestCaseName) gtest_type_params_##TestCaseName##_ 161 | 162 | // The 'Types' template argument below must have spaces around it 163 | // since some compilers may choke on '>>' when passing a template 164 | // instance (e.g. Types) 165 | # define TYPED_TEST_CASE(CaseName, Types) \ 166 | typedef ::testing::internal::TypeList< Types >::type \ 167 | GTEST_TYPE_PARAMS_(CaseName) 168 | 169 | # define TYPED_TEST(CaseName, TestName) \ 170 | template \ 171 | class GTEST_TEST_CLASS_NAME_(CaseName, TestName) \ 172 | : public CaseName { \ 173 | private: \ 174 | typedef CaseName TestFixture; \ 175 | typedef gtest_TypeParam_ TypeParam; \ 176 | virtual void TestBody(); \ 177 | }; \ 178 | bool gtest_##CaseName##_##TestName##_registered_ GTEST_ATTRIBUTE_UNUSED_ = \ 179 | ::testing::internal::TypeParameterizedTest< \ 180 | CaseName, \ 181 | ::testing::internal::TemplateSel< \ 182 | GTEST_TEST_CLASS_NAME_(CaseName, TestName)>, \ 183 | GTEST_TYPE_PARAMS_(CaseName)>::Register(\ 184 | "", #CaseName, #TestName, 0); \ 185 | template \ 186 | void GTEST_TEST_CLASS_NAME_(CaseName, TestName)::TestBody() 187 | 188 | #endif // GTEST_HAS_TYPED_TEST 189 | 190 | // Implements type-parameterized tests. 191 | 192 | #if GTEST_HAS_TYPED_TEST_P 193 | 194 | // INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE. 195 | // 196 | // Expands to the namespace name that the type-parameterized tests for 197 | // the given type-parameterized test case are defined in. The exact 198 | // name of the namespace is subject to change without notice. 199 | # define GTEST_CASE_NAMESPACE_(TestCaseName) \ 200 | gtest_case_##TestCaseName##_ 201 | 202 | // INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE. 203 | // 204 | // Expands to the name of the variable used to remember the names of 205 | // the defined tests in the given test case. 206 | # define GTEST_TYPED_TEST_CASE_P_STATE_(TestCaseName) \ 207 | gtest_typed_test_case_p_state_##TestCaseName##_ 208 | 209 | // INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE DIRECTLY. 210 | // 211 | // Expands to the name of the variable used to remember the names of 212 | // the registered tests in the given test case. 213 | # define GTEST_REGISTERED_TEST_NAMES_(TestCaseName) \ 214 | gtest_registered_test_names_##TestCaseName##_ 215 | 216 | // The variables defined in the type-parameterized test macros are 217 | // static as typically these macros are used in a .h file that can be 218 | // #included in multiple translation units linked together. 219 | # define TYPED_TEST_CASE_P(CaseName) \ 220 | static ::testing::internal::TypedTestCasePState \ 221 | GTEST_TYPED_TEST_CASE_P_STATE_(CaseName) 222 | 223 | # define TYPED_TEST_P(CaseName, TestName) \ 224 | namespace GTEST_CASE_NAMESPACE_(CaseName) { \ 225 | template \ 226 | class TestName : public CaseName { \ 227 | private: \ 228 | typedef CaseName TestFixture; \ 229 | typedef gtest_TypeParam_ TypeParam; \ 230 | virtual void TestBody(); \ 231 | }; \ 232 | static bool gtest_##TestName##_defined_ GTEST_ATTRIBUTE_UNUSED_ = \ 233 | GTEST_TYPED_TEST_CASE_P_STATE_(CaseName).AddTestName(\ 234 | __FILE__, __LINE__, #CaseName, #TestName); \ 235 | } \ 236 | template \ 237 | void GTEST_CASE_NAMESPACE_(CaseName)::TestName::TestBody() 238 | 239 | # define REGISTER_TYPED_TEST_CASE_P(CaseName, ...) \ 240 | namespace GTEST_CASE_NAMESPACE_(CaseName) { \ 241 | typedef ::testing::internal::Templates<__VA_ARGS__>::type gtest_AllTests_; \ 242 | } \ 243 | static const char* const GTEST_REGISTERED_TEST_NAMES_(CaseName) = \ 244 | GTEST_TYPED_TEST_CASE_P_STATE_(CaseName).VerifyRegisteredTestNames(\ 245 | __FILE__, __LINE__, #__VA_ARGS__) 246 | 247 | // The 'Types' template argument below must have spaces around it 248 | // since some compilers may choke on '>>' when passing a template 249 | // instance (e.g. Types) 250 | # define INSTANTIATE_TYPED_TEST_CASE_P(Prefix, CaseName, Types) \ 251 | bool gtest_##Prefix##_##CaseName GTEST_ATTRIBUTE_UNUSED_ = \ 252 | ::testing::internal::TypeParameterizedTestCase::type>::Register(\ 255 | #Prefix, #CaseName, GTEST_REGISTERED_TEST_NAMES_(CaseName)) 256 | 257 | #endif // GTEST_HAS_TYPED_TEST_P 258 | 259 | #endif // GTEST_INCLUDE_GTEST_GTEST_TYPED_TEST_H_ 260 | -------------------------------------------------------------------------------- /gtest/include/gtest/gtest_prod.h: -------------------------------------------------------------------------------- 1 | // Copyright 2006, Google Inc. 2 | // All rights reserved. 3 | // 4 | // Redistribution and use in source and binary forms, with or without 5 | // modification, are permitted provided that the following conditions are 6 | // met: 7 | // 8 | // * Redistributions of source code must retain the above copyright 9 | // notice, this list of conditions and the following disclaimer. 10 | // * Redistributions in binary form must reproduce the above 11 | // copyright notice, this list of conditions and the following disclaimer 12 | // in the documentation and/or other materials provided with the 13 | // distribution. 14 | // * Neither the name of Google Inc. nor the names of its 15 | // contributors may be used to endorse or promote products derived from 16 | // this software without specific prior written permission. 17 | // 18 | // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 19 | // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 20 | // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 21 | // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 22 | // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 23 | // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 24 | // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 25 | // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 26 | // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 27 | // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 28 | // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 29 | // 30 | // Author: wan@google.com (Zhanyong Wan) 31 | // 32 | // Google C++ Testing Framework definitions useful in production code. 33 | 34 | #ifndef GTEST_INCLUDE_GTEST_GTEST_PROD_H_ 35 | #define GTEST_INCLUDE_GTEST_GTEST_PROD_H_ 36 | 37 | // When you need to test the private or protected members of a class, 38 | // use the FRIEND_TEST macro to declare your tests as friends of the 39 | // class. For example: 40 | // 41 | // class MyClass { 42 | // private: 43 | // void MyMethod(); 44 | // FRIEND_TEST(MyClassTest, MyMethod); 45 | // }; 46 | // 47 | // class MyClassTest : public testing::Test { 48 | // // ... 49 | // }; 50 | // 51 | // TEST_F(MyClassTest, MyMethod) { 52 | // // Can call MyClass::MyMethod() here. 53 | // } 54 | 55 | #define FRIEND_TEST(test_case_name, test_name)\ 56 | friend class test_case_name##_##test_name##_Test 57 | 58 | #endif // GTEST_INCLUDE_GTEST_GTEST_PROD_H_ 59 | -------------------------------------------------------------------------------- /gtest/include/gtest/internal/gtest-death-test-internal.h: -------------------------------------------------------------------------------- 1 | // Copyright 2005, Google Inc. 2 | // All rights reserved. 3 | // 4 | // Redistribution and use in source and binary forms, with or without 5 | // modification, are permitted provided that the following conditions are 6 | // met: 7 | // 8 | // * Redistributions of source code must retain the above copyright 9 | // notice, this list of conditions and the following disclaimer. 10 | // * Redistributions in binary form must reproduce the above 11 | // copyright notice, this list of conditions and the following disclaimer 12 | // in the documentation and/or other materials provided with the 13 | // distribution. 14 | // * Neither the name of Google Inc. nor the names of its 15 | // contributors may be used to endorse or promote products derived from 16 | // this software without specific prior written permission. 17 | // 18 | // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 19 | // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 20 | // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 21 | // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 22 | // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 23 | // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 24 | // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 25 | // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 26 | // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 27 | // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 28 | // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 29 | // 30 | // Authors: wan@google.com (Zhanyong Wan), eefacm@gmail.com (Sean Mcafee) 31 | // 32 | // The Google C++ Testing Framework (Google Test) 33 | // 34 | // This header file defines internal utilities needed for implementing 35 | // death tests. They are subject to change without notice. 36 | 37 | #ifndef GTEST_INCLUDE_GTEST_INTERNAL_GTEST_DEATH_TEST_INTERNAL_H_ 38 | #define GTEST_INCLUDE_GTEST_INTERNAL_GTEST_DEATH_TEST_INTERNAL_H_ 39 | 40 | #include "gtest/internal/gtest-internal.h" 41 | 42 | #include 43 | 44 | namespace testing { 45 | namespace internal { 46 | 47 | GTEST_DECLARE_string_(internal_run_death_test); 48 | 49 | // Names of the flags (needed for parsing Google Test flags). 50 | const char kDeathTestStyleFlag[] = "death_test_style"; 51 | const char kDeathTestUseFork[] = "death_test_use_fork"; 52 | const char kInternalRunDeathTestFlag[] = "internal_run_death_test"; 53 | 54 | #if GTEST_HAS_DEATH_TEST 55 | 56 | // DeathTest is a class that hides much of the complexity of the 57 | // GTEST_DEATH_TEST_ macro. It is abstract; its static Create method 58 | // returns a concrete class that depends on the prevailing death test 59 | // style, as defined by the --gtest_death_test_style and/or 60 | // --gtest_internal_run_death_test flags. 61 | 62 | // In describing the results of death tests, these terms are used with 63 | // the corresponding definitions: 64 | // 65 | // exit status: The integer exit information in the format specified 66 | // by wait(2) 67 | // exit code: The integer code passed to exit(3), _exit(2), or 68 | // returned from main() 69 | class GTEST_API_ DeathTest { 70 | public: 71 | // Create returns false if there was an error determining the 72 | // appropriate action to take for the current death test; for example, 73 | // if the gtest_death_test_style flag is set to an invalid value. 74 | // The LastMessage method will return a more detailed message in that 75 | // case. Otherwise, the DeathTest pointer pointed to by the "test" 76 | // argument is set. If the death test should be skipped, the pointer 77 | // is set to NULL; otherwise, it is set to the address of a new concrete 78 | // DeathTest object that controls the execution of the current test. 79 | static bool Create(const char* statement, const RE* regex, 80 | const char* file, int line, DeathTest** test); 81 | DeathTest(); 82 | virtual ~DeathTest() { } 83 | 84 | // A helper class that aborts a death test when it's deleted. 85 | class ReturnSentinel { 86 | public: 87 | explicit ReturnSentinel(DeathTest* test) : test_(test) { } 88 | ~ReturnSentinel() { test_->Abort(TEST_ENCOUNTERED_RETURN_STATEMENT); } 89 | private: 90 | DeathTest* const test_; 91 | GTEST_DISALLOW_COPY_AND_ASSIGN_(ReturnSentinel); 92 | } GTEST_ATTRIBUTE_UNUSED_; 93 | 94 | // An enumeration of possible roles that may be taken when a death 95 | // test is encountered. EXECUTE means that the death test logic should 96 | // be executed immediately. OVERSEE means that the program should prepare 97 | // the appropriate environment for a child process to execute the death 98 | // test, then wait for it to complete. 99 | enum TestRole { OVERSEE_TEST, EXECUTE_TEST }; 100 | 101 | // An enumeration of the three reasons that a test might be aborted. 102 | enum AbortReason { 103 | TEST_ENCOUNTERED_RETURN_STATEMENT, 104 | TEST_THREW_EXCEPTION, 105 | TEST_DID_NOT_DIE 106 | }; 107 | 108 | // Assumes one of the above roles. 109 | virtual TestRole AssumeRole() = 0; 110 | 111 | // Waits for the death test to finish and returns its status. 112 | virtual int Wait() = 0; 113 | 114 | // Returns true if the death test passed; that is, the test process 115 | // exited during the test, its exit status matches a user-supplied 116 | // predicate, and its stderr output matches a user-supplied regular 117 | // expression. 118 | // The user-supplied predicate may be a macro expression rather 119 | // than a function pointer or functor, or else Wait and Passed could 120 | // be combined. 121 | virtual bool Passed(bool exit_status_ok) = 0; 122 | 123 | // Signals that the death test did not die as expected. 124 | virtual void Abort(AbortReason reason) = 0; 125 | 126 | // Returns a human-readable outcome message regarding the outcome of 127 | // the last death test. 128 | static const char* LastMessage(); 129 | 130 | static void set_last_death_test_message(const std::string& message); 131 | 132 | private: 133 | // A string containing a description of the outcome of the last death test. 134 | static std::string last_death_test_message_; 135 | 136 | GTEST_DISALLOW_COPY_AND_ASSIGN_(DeathTest); 137 | }; 138 | 139 | // Factory interface for death tests. May be mocked out for testing. 140 | class DeathTestFactory { 141 | public: 142 | virtual ~DeathTestFactory() { } 143 | virtual bool Create(const char* statement, const RE* regex, 144 | const char* file, int line, DeathTest** test) = 0; 145 | }; 146 | 147 | // A concrete DeathTestFactory implementation for normal use. 148 | class DefaultDeathTestFactory : public DeathTestFactory { 149 | public: 150 | virtual bool Create(const char* statement, const RE* regex, 151 | const char* file, int line, DeathTest** test); 152 | }; 153 | 154 | // Returns true if exit_status describes a process that was terminated 155 | // by a signal, or exited normally with a nonzero exit code. 156 | GTEST_API_ bool ExitedUnsuccessfully(int exit_status); 157 | 158 | // Traps C++ exceptions escaping statement and reports them as test 159 | // failures. Note that trapping SEH exceptions is not implemented here. 160 | # if GTEST_HAS_EXCEPTIONS 161 | # define GTEST_EXECUTE_DEATH_TEST_STATEMENT_(statement, death_test) \ 162 | try { \ 163 | GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement); \ 164 | } catch (const ::std::exception& gtest_exception) { \ 165 | fprintf(\ 166 | stderr, \ 167 | "\n%s: Caught std::exception-derived exception escaping the " \ 168 | "death test statement. Exception message: %s\n", \ 169 | ::testing::internal::FormatFileLocation(__FILE__, __LINE__).c_str(), \ 170 | gtest_exception.what()); \ 171 | fflush(stderr); \ 172 | death_test->Abort(::testing::internal::DeathTest::TEST_THREW_EXCEPTION); \ 173 | } catch (...) { \ 174 | death_test->Abort(::testing::internal::DeathTest::TEST_THREW_EXCEPTION); \ 175 | } 176 | 177 | # else 178 | # define GTEST_EXECUTE_DEATH_TEST_STATEMENT_(statement, death_test) \ 179 | GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement) 180 | 181 | # endif 182 | 183 | // This macro is for implementing ASSERT_DEATH*, EXPECT_DEATH*, 184 | // ASSERT_EXIT*, and EXPECT_EXIT*. 185 | # define GTEST_DEATH_TEST_(statement, predicate, regex, fail) \ 186 | GTEST_AMBIGUOUS_ELSE_BLOCKER_ \ 187 | if (::testing::internal::AlwaysTrue()) { \ 188 | const ::testing::internal::RE& gtest_regex = (regex); \ 189 | ::testing::internal::DeathTest* gtest_dt; \ 190 | if (!::testing::internal::DeathTest::Create(#statement, >est_regex, \ 191 | __FILE__, __LINE__, >est_dt)) { \ 192 | goto GTEST_CONCAT_TOKEN_(gtest_label_, __LINE__); \ 193 | } \ 194 | if (gtest_dt != NULL) { \ 195 | ::testing::internal::scoped_ptr< ::testing::internal::DeathTest> \ 196 | gtest_dt_ptr(gtest_dt); \ 197 | switch (gtest_dt->AssumeRole()) { \ 198 | case ::testing::internal::DeathTest::OVERSEE_TEST: \ 199 | if (!gtest_dt->Passed(predicate(gtest_dt->Wait()))) { \ 200 | goto GTEST_CONCAT_TOKEN_(gtest_label_, __LINE__); \ 201 | } \ 202 | break; \ 203 | case ::testing::internal::DeathTest::EXECUTE_TEST: { \ 204 | ::testing::internal::DeathTest::ReturnSentinel \ 205 | gtest_sentinel(gtest_dt); \ 206 | GTEST_EXECUTE_DEATH_TEST_STATEMENT_(statement, gtest_dt); \ 207 | gtest_dt->Abort(::testing::internal::DeathTest::TEST_DID_NOT_DIE); \ 208 | break; \ 209 | } \ 210 | default: \ 211 | break; \ 212 | } \ 213 | } \ 214 | } else \ 215 | GTEST_CONCAT_TOKEN_(gtest_label_, __LINE__): \ 216 | fail(::testing::internal::DeathTest::LastMessage()) 217 | // The symbol "fail" here expands to something into which a message 218 | // can be streamed. 219 | 220 | // This macro is for implementing ASSERT/EXPECT_DEBUG_DEATH when compiled in 221 | // NDEBUG mode. In this case we need the statements to be executed, the regex is 222 | // ignored, and the macro must accept a streamed message even though the message 223 | // is never printed. 224 | # define GTEST_EXECUTE_STATEMENT_(statement, regex) \ 225 | GTEST_AMBIGUOUS_ELSE_BLOCKER_ \ 226 | if (::testing::internal::AlwaysTrue()) { \ 227 | GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement); \ 228 | } else \ 229 | ::testing::Message() 230 | 231 | // A class representing the parsed contents of the 232 | // --gtest_internal_run_death_test flag, as it existed when 233 | // RUN_ALL_TESTS was called. 234 | class InternalRunDeathTestFlag { 235 | public: 236 | InternalRunDeathTestFlag(const std::string& a_file, 237 | int a_line, 238 | int an_index, 239 | int a_write_fd) 240 | : file_(a_file), line_(a_line), index_(an_index), 241 | write_fd_(a_write_fd) {} 242 | 243 | ~InternalRunDeathTestFlag() { 244 | if (write_fd_ >= 0) 245 | posix::Close(write_fd_); 246 | } 247 | 248 | const std::string& file() const { return file_; } 249 | int line() const { return line_; } 250 | int index() const { return index_; } 251 | int write_fd() const { return write_fd_; } 252 | 253 | private: 254 | std::string file_; 255 | int line_; 256 | int index_; 257 | int write_fd_; 258 | 259 | GTEST_DISALLOW_COPY_AND_ASSIGN_(InternalRunDeathTestFlag); 260 | }; 261 | 262 | // Returns a newly created InternalRunDeathTestFlag object with fields 263 | // initialized from the GTEST_FLAG(internal_run_death_test) flag if 264 | // the flag is specified; otherwise returns NULL. 265 | InternalRunDeathTestFlag* ParseInternalRunDeathTestFlag(); 266 | 267 | #else // GTEST_HAS_DEATH_TEST 268 | 269 | // This macro is used for implementing macros such as 270 | // EXPECT_DEATH_IF_SUPPORTED and ASSERT_DEATH_IF_SUPPORTED on systems where 271 | // death tests are not supported. Those macros must compile on such systems 272 | // iff EXPECT_DEATH and ASSERT_DEATH compile with the same parameters on 273 | // systems that support death tests. This allows one to write such a macro 274 | // on a system that does not support death tests and be sure that it will 275 | // compile on a death-test supporting system. 276 | // 277 | // Parameters: 278 | // statement - A statement that a macro such as EXPECT_DEATH would test 279 | // for program termination. This macro has to make sure this 280 | // statement is compiled but not executed, to ensure that 281 | // EXPECT_DEATH_IF_SUPPORTED compiles with a certain 282 | // parameter iff EXPECT_DEATH compiles with it. 283 | // regex - A regex that a macro such as EXPECT_DEATH would use to test 284 | // the output of statement. This parameter has to be 285 | // compiled but not evaluated by this macro, to ensure that 286 | // this macro only accepts expressions that a macro such as 287 | // EXPECT_DEATH would accept. 288 | // terminator - Must be an empty statement for EXPECT_DEATH_IF_SUPPORTED 289 | // and a return statement for ASSERT_DEATH_IF_SUPPORTED. 290 | // This ensures that ASSERT_DEATH_IF_SUPPORTED will not 291 | // compile inside functions where ASSERT_DEATH doesn't 292 | // compile. 293 | // 294 | // The branch that has an always false condition is used to ensure that 295 | // statement and regex are compiled (and thus syntactically correct) but 296 | // never executed. The unreachable code macro protects the terminator 297 | // statement from generating an 'unreachable code' warning in case 298 | // statement unconditionally returns or throws. The Message constructor at 299 | // the end allows the syntax of streaming additional messages into the 300 | // macro, for compilational compatibility with EXPECT_DEATH/ASSERT_DEATH. 301 | # define GTEST_UNSUPPORTED_DEATH_TEST_(statement, regex, terminator) \ 302 | GTEST_AMBIGUOUS_ELSE_BLOCKER_ \ 303 | if (::testing::internal::AlwaysTrue()) { \ 304 | GTEST_LOG_(WARNING) \ 305 | << "Death tests are not supported on this platform.\n" \ 306 | << "Statement '" #statement "' cannot be verified."; \ 307 | } else if (::testing::internal::AlwaysFalse()) { \ 308 | ::testing::internal::RE::PartialMatch(".*", (regex)); \ 309 | GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement); \ 310 | terminator; \ 311 | } else \ 312 | ::testing::Message() 313 | 314 | #endif // GTEST_HAS_DEATH_TEST 315 | 316 | } // namespace internal 317 | } // namespace testing 318 | 319 | #endif // GTEST_INCLUDE_GTEST_INTERNAL_GTEST_DEATH_TEST_INTERNAL_H_ 320 | -------------------------------------------------------------------------------- /gtest/include/gtest/internal/gtest-filepath.h: -------------------------------------------------------------------------------- 1 | // Copyright 2008, Google Inc. 2 | // All rights reserved. 3 | // 4 | // Redistribution and use in source and binary forms, with or without 5 | // modification, are permitted provided that the following conditions are 6 | // met: 7 | // 8 | // * Redistributions of source code must retain the above copyright 9 | // notice, this list of conditions and the following disclaimer. 10 | // * Redistributions in binary form must reproduce the above 11 | // copyright notice, this list of conditions and the following disclaimer 12 | // in the documentation and/or other materials provided with the 13 | // distribution. 14 | // * Neither the name of Google Inc. nor the names of its 15 | // contributors may be used to endorse or promote products derived from 16 | // this software without specific prior written permission. 17 | // 18 | // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 19 | // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 20 | // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 21 | // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 22 | // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 23 | // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 24 | // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 25 | // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 26 | // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 27 | // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 28 | // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 29 | // 30 | // Author: keith.ray@gmail.com (Keith Ray) 31 | // 32 | // Google Test filepath utilities 33 | // 34 | // This header file declares classes and functions used internally by 35 | // Google Test. They are subject to change without notice. 36 | // 37 | // This file is #included in . 38 | // Do not include this header file separately! 39 | 40 | #ifndef GTEST_INCLUDE_GTEST_INTERNAL_GTEST_FILEPATH_H_ 41 | #define GTEST_INCLUDE_GTEST_INTERNAL_GTEST_FILEPATH_H_ 42 | 43 | #include "gtest/internal/gtest-string.h" 44 | 45 | namespace testing { 46 | namespace internal { 47 | 48 | // FilePath - a class for file and directory pathname manipulation which 49 | // handles platform-specific conventions (like the pathname separator). 50 | // Used for helper functions for naming files in a directory for xml output. 51 | // Except for Set methods, all methods are const or static, which provides an 52 | // "immutable value object" -- useful for peace of mind. 53 | // A FilePath with a value ending in a path separator ("like/this/") represents 54 | // a directory, otherwise it is assumed to represent a file. In either case, 55 | // it may or may not represent an actual file or directory in the file system. 56 | // Names are NOT checked for syntax correctness -- no checking for illegal 57 | // characters, malformed paths, etc. 58 | 59 | class GTEST_API_ FilePath { 60 | public: 61 | FilePath() : pathname_("") { } 62 | FilePath(const FilePath& rhs) : pathname_(rhs.pathname_) { } 63 | 64 | explicit FilePath(const std::string& pathname) : pathname_(pathname) { 65 | Normalize(); 66 | } 67 | 68 | FilePath& operator=(const FilePath& rhs) { 69 | Set(rhs); 70 | return *this; 71 | } 72 | 73 | void Set(const FilePath& rhs) { 74 | pathname_ = rhs.pathname_; 75 | } 76 | 77 | const std::string& string() const { return pathname_; } 78 | const char* c_str() const { return pathname_.c_str(); } 79 | 80 | // Returns the current working directory, or "" if unsuccessful. 81 | static FilePath GetCurrentDir(); 82 | 83 | // Given directory = "dir", base_name = "test", number = 0, 84 | // extension = "xml", returns "dir/test.xml". If number is greater 85 | // than zero (e.g., 12), returns "dir/test_12.xml". 86 | // On Windows platform, uses \ as the separator rather than /. 87 | static FilePath MakeFileName(const FilePath& directory, 88 | const FilePath& base_name, 89 | int number, 90 | const char* extension); 91 | 92 | // Given directory = "dir", relative_path = "test.xml", 93 | // returns "dir/test.xml". 94 | // On Windows, uses \ as the separator rather than /. 95 | static FilePath ConcatPaths(const FilePath& directory, 96 | const FilePath& relative_path); 97 | 98 | // Returns a pathname for a file that does not currently exist. The pathname 99 | // will be directory/base_name.extension or 100 | // directory/base_name_.extension if directory/base_name.extension 101 | // already exists. The number will be incremented until a pathname is found 102 | // that does not already exist. 103 | // Examples: 'dir/foo_test.xml' or 'dir/foo_test_1.xml'. 104 | // There could be a race condition if two or more processes are calling this 105 | // function at the same time -- they could both pick the same filename. 106 | static FilePath GenerateUniqueFileName(const FilePath& directory, 107 | const FilePath& base_name, 108 | const char* extension); 109 | 110 | // Returns true iff the path is "". 111 | bool IsEmpty() const { return pathname_.empty(); } 112 | 113 | // If input name has a trailing separator character, removes it and returns 114 | // the name, otherwise return the name string unmodified. 115 | // On Windows platform, uses \ as the separator, other platforms use /. 116 | FilePath RemoveTrailingPathSeparator() const; 117 | 118 | // Returns a copy of the FilePath with the directory part removed. 119 | // Example: FilePath("path/to/file").RemoveDirectoryName() returns 120 | // FilePath("file"). If there is no directory part ("just_a_file"), it returns 121 | // the FilePath unmodified. If there is no file part ("just_a_dir/") it 122 | // returns an empty FilePath (""). 123 | // On Windows platform, '\' is the path separator, otherwise it is '/'. 124 | FilePath RemoveDirectoryName() const; 125 | 126 | // RemoveFileName returns the directory path with the filename removed. 127 | // Example: FilePath("path/to/file").RemoveFileName() returns "path/to/". 128 | // If the FilePath is "a_file" or "/a_file", RemoveFileName returns 129 | // FilePath("./") or, on Windows, FilePath(".\\"). If the filepath does 130 | // not have a file, like "just/a/dir/", it returns the FilePath unmodified. 131 | // On Windows platform, '\' is the path separator, otherwise it is '/'. 132 | FilePath RemoveFileName() const; 133 | 134 | // Returns a copy of the FilePath with the case-insensitive extension removed. 135 | // Example: FilePath("dir/file.exe").RemoveExtension("EXE") returns 136 | // FilePath("dir/file"). If a case-insensitive extension is not 137 | // found, returns a copy of the original FilePath. 138 | FilePath RemoveExtension(const char* extension) const; 139 | 140 | // Creates directories so that path exists. Returns true if successful or if 141 | // the directories already exist; returns false if unable to create 142 | // directories for any reason. Will also return false if the FilePath does 143 | // not represent a directory (that is, it doesn't end with a path separator). 144 | bool CreateDirectoriesRecursively() const; 145 | 146 | // Create the directory so that path exists. Returns true if successful or 147 | // if the directory already exists; returns false if unable to create the 148 | // directory for any reason, including if the parent directory does not 149 | // exist. Not named "CreateDirectory" because that's a macro on Windows. 150 | bool CreateFolder() const; 151 | 152 | // Returns true if FilePath describes something in the file-system, 153 | // either a file, directory, or whatever, and that something exists. 154 | bool FileOrDirectoryExists() const; 155 | 156 | // Returns true if pathname describes a directory in the file-system 157 | // that exists. 158 | bool DirectoryExists() const; 159 | 160 | // Returns true if FilePath ends with a path separator, which indicates that 161 | // it is intended to represent a directory. Returns false otherwise. 162 | // This does NOT check that a directory (or file) actually exists. 163 | bool IsDirectory() const; 164 | 165 | // Returns true if pathname describes a root directory. (Windows has one 166 | // root directory per disk drive.) 167 | bool IsRootDirectory() const; 168 | 169 | // Returns true if pathname describes an absolute path. 170 | bool IsAbsolutePath() const; 171 | 172 | private: 173 | // Replaces multiple consecutive separators with a single separator. 174 | // For example, "bar///foo" becomes "bar/foo". Does not eliminate other 175 | // redundancies that might be in a pathname involving "." or "..". 176 | // 177 | // A pathname with multiple consecutive separators may occur either through 178 | // user error or as a result of some scripts or APIs that generate a pathname 179 | // with a trailing separator. On other platforms the same API or script 180 | // may NOT generate a pathname with a trailing "/". Then elsewhere that 181 | // pathname may have another "/" and pathname components added to it, 182 | // without checking for the separator already being there. 183 | // The script language and operating system may allow paths like "foo//bar" 184 | // but some of the functions in FilePath will not handle that correctly. In 185 | // particular, RemoveTrailingPathSeparator() only removes one separator, and 186 | // it is called in CreateDirectoriesRecursively() assuming that it will change 187 | // a pathname from directory syntax (trailing separator) to filename syntax. 188 | // 189 | // On Windows this method also replaces the alternate path separator '/' with 190 | // the primary path separator '\\', so that for example "bar\\/\\foo" becomes 191 | // "bar\\foo". 192 | 193 | void Normalize(); 194 | 195 | // Returns a pointer to the last occurence of a valid path separator in 196 | // the FilePath. On Windows, for example, both '/' and '\' are valid path 197 | // separators. Returns NULL if no path separator was found. 198 | const char* FindLastPathSeparator() const; 199 | 200 | std::string pathname_; 201 | }; // class FilePath 202 | 203 | } // namespace internal 204 | } // namespace testing 205 | 206 | #endif // GTEST_INCLUDE_GTEST_INTERNAL_GTEST_FILEPATH_H_ 207 | -------------------------------------------------------------------------------- /gtest/include/gtest/internal/gtest-linked_ptr.h: -------------------------------------------------------------------------------- 1 | // Copyright 2003 Google Inc. 2 | // All rights reserved. 3 | // 4 | // Redistribution and use in source and binary forms, with or without 5 | // modification, are permitted provided that the following conditions are 6 | // met: 7 | // 8 | // * Redistributions of source code must retain the above copyright 9 | // notice, this list of conditions and the following disclaimer. 10 | // * Redistributions in binary form must reproduce the above 11 | // copyright notice, this list of conditions and the following disclaimer 12 | // in the documentation and/or other materials provided with the 13 | // distribution. 14 | // * Neither the name of Google Inc. nor the names of its 15 | // contributors may be used to endorse or promote products derived from 16 | // this software without specific prior written permission. 17 | // 18 | // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 19 | // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 20 | // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 21 | // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 22 | // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 23 | // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 24 | // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 25 | // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 26 | // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 27 | // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 28 | // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 29 | // 30 | // Authors: Dan Egnor (egnor@google.com) 31 | // 32 | // A "smart" pointer type with reference tracking. Every pointer to a 33 | // particular object is kept on a circular linked list. When the last pointer 34 | // to an object is destroyed or reassigned, the object is deleted. 35 | // 36 | // Used properly, this deletes the object when the last reference goes away. 37 | // There are several caveats: 38 | // - Like all reference counting schemes, cycles lead to leaks. 39 | // - Each smart pointer is actually two pointers (8 bytes instead of 4). 40 | // - Every time a pointer is assigned, the entire list of pointers to that 41 | // object is traversed. This class is therefore NOT SUITABLE when there 42 | // will often be more than two or three pointers to a particular object. 43 | // - References are only tracked as long as linked_ptr<> objects are copied. 44 | // If a linked_ptr<> is converted to a raw pointer and back, BAD THINGS 45 | // will happen (double deletion). 46 | // 47 | // A good use of this class is storing object references in STL containers. 48 | // You can safely put linked_ptr<> in a vector<>. 49 | // Other uses may not be as good. 50 | // 51 | // Note: If you use an incomplete type with linked_ptr<>, the class 52 | // *containing* linked_ptr<> must have a constructor and destructor (even 53 | // if they do nothing!). 54 | // 55 | // Bill Gibbons suggested we use something like this. 56 | // 57 | // Thread Safety: 58 | // Unlike other linked_ptr implementations, in this implementation 59 | // a linked_ptr object is thread-safe in the sense that: 60 | // - it's safe to copy linked_ptr objects concurrently, 61 | // - it's safe to copy *from* a linked_ptr and read its underlying 62 | // raw pointer (e.g. via get()) concurrently, and 63 | // - it's safe to write to two linked_ptrs that point to the same 64 | // shared object concurrently. 65 | // TODO(wan@google.com): rename this to safe_linked_ptr to avoid 66 | // confusion with normal linked_ptr. 67 | 68 | #ifndef GTEST_INCLUDE_GTEST_INTERNAL_GTEST_LINKED_PTR_H_ 69 | #define GTEST_INCLUDE_GTEST_INTERNAL_GTEST_LINKED_PTR_H_ 70 | 71 | #include 72 | #include 73 | 74 | #include "gtest/internal/gtest-port.h" 75 | 76 | namespace testing { 77 | namespace internal { 78 | 79 | // Protects copying of all linked_ptr objects. 80 | GTEST_API_ GTEST_DECLARE_STATIC_MUTEX_(g_linked_ptr_mutex); 81 | 82 | // This is used internally by all instances of linked_ptr<>. It needs to be 83 | // a non-template class because different types of linked_ptr<> can refer to 84 | // the same object (linked_ptr(obj) vs linked_ptr(obj)). 85 | // So, it needs to be possible for different types of linked_ptr to participate 86 | // in the same circular linked list, so we need a single class type here. 87 | // 88 | // DO NOT USE THIS CLASS DIRECTLY YOURSELF. Use linked_ptr. 89 | class linked_ptr_internal { 90 | public: 91 | // Create a new circle that includes only this instance. 92 | void join_new() { 93 | next_ = this; 94 | } 95 | 96 | // Many linked_ptr operations may change p.link_ for some linked_ptr 97 | // variable p in the same circle as this object. Therefore we need 98 | // to prevent two such operations from occurring concurrently. 99 | // 100 | // Note that different types of linked_ptr objects can coexist in a 101 | // circle (e.g. linked_ptr, linked_ptr, and 102 | // linked_ptr). Therefore we must use a single mutex to 103 | // protect all linked_ptr objects. This can create serious 104 | // contention in production code, but is acceptable in a testing 105 | // framework. 106 | 107 | // Join an existing circle. 108 | void join(linked_ptr_internal const* ptr) 109 | GTEST_LOCK_EXCLUDED_(g_linked_ptr_mutex) { 110 | MutexLock lock(&g_linked_ptr_mutex); 111 | 112 | linked_ptr_internal const* p = ptr; 113 | while (p->next_ != ptr) p = p->next_; 114 | p->next_ = this; 115 | next_ = ptr; 116 | } 117 | 118 | // Leave whatever circle we're part of. Returns true if we were the 119 | // last member of the circle. Once this is done, you can join() another. 120 | bool depart() 121 | GTEST_LOCK_EXCLUDED_(g_linked_ptr_mutex) { 122 | MutexLock lock(&g_linked_ptr_mutex); 123 | 124 | if (next_ == this) return true; 125 | linked_ptr_internal const* p = next_; 126 | while (p->next_ != this) p = p->next_; 127 | p->next_ = next_; 128 | return false; 129 | } 130 | 131 | private: 132 | mutable linked_ptr_internal const* next_; 133 | }; 134 | 135 | template 136 | class linked_ptr { 137 | public: 138 | typedef T element_type; 139 | 140 | // Take over ownership of a raw pointer. This should happen as soon as 141 | // possible after the object is created. 142 | explicit linked_ptr(T* ptr = NULL) { capture(ptr); } 143 | ~linked_ptr() { depart(); } 144 | 145 | // Copy an existing linked_ptr<>, adding ourselves to the list of references. 146 | template linked_ptr(linked_ptr const& ptr) { copy(&ptr); } 147 | linked_ptr(linked_ptr const& ptr) { // NOLINT 148 | assert(&ptr != this); 149 | copy(&ptr); 150 | } 151 | 152 | // Assignment releases the old value and acquires the new. 153 | template linked_ptr& operator=(linked_ptr const& ptr) { 154 | depart(); 155 | copy(&ptr); 156 | return *this; 157 | } 158 | 159 | linked_ptr& operator=(linked_ptr const& ptr) { 160 | if (&ptr != this) { 161 | depart(); 162 | copy(&ptr); 163 | } 164 | return *this; 165 | } 166 | 167 | // Smart pointer members. 168 | void reset(T* ptr = NULL) { 169 | depart(); 170 | capture(ptr); 171 | } 172 | T* get() const { return value_; } 173 | T* operator->() const { return value_; } 174 | T& operator*() const { return *value_; } 175 | 176 | bool operator==(T* p) const { return value_ == p; } 177 | bool operator!=(T* p) const { return value_ != p; } 178 | template 179 | bool operator==(linked_ptr const& ptr) const { 180 | return value_ == ptr.get(); 181 | } 182 | template 183 | bool operator!=(linked_ptr const& ptr) const { 184 | return value_ != ptr.get(); 185 | } 186 | 187 | private: 188 | template 189 | friend class linked_ptr; 190 | 191 | T* value_; 192 | linked_ptr_internal link_; 193 | 194 | void depart() { 195 | if (link_.depart()) delete value_; 196 | } 197 | 198 | void capture(T* ptr) { 199 | value_ = ptr; 200 | link_.join_new(); 201 | } 202 | 203 | template void copy(linked_ptr const* ptr) { 204 | value_ = ptr->get(); 205 | if (value_) 206 | link_.join(&ptr->link_); 207 | else 208 | link_.join_new(); 209 | } 210 | }; 211 | 212 | template inline 213 | bool operator==(T* ptr, const linked_ptr& x) { 214 | return ptr == x.get(); 215 | } 216 | 217 | template inline 218 | bool operator!=(T* ptr, const linked_ptr& x) { 219 | return ptr != x.get(); 220 | } 221 | 222 | // A function to convert T* into linked_ptr 223 | // Doing e.g. make_linked_ptr(new FooBarBaz(arg)) is a shorter notation 224 | // for linked_ptr >(new FooBarBaz(arg)) 225 | template 226 | linked_ptr make_linked_ptr(T* ptr) { 227 | return linked_ptr(ptr); 228 | } 229 | 230 | } // namespace internal 231 | } // namespace testing 232 | 233 | #endif // GTEST_INCLUDE_GTEST_INTERNAL_GTEST_LINKED_PTR_H_ 234 | -------------------------------------------------------------------------------- /gtest/include/gtest/internal/gtest-param-util-generated.h.pump: -------------------------------------------------------------------------------- 1 | $$ -*- mode: c++; -*- 2 | $var n = 50 $$ Maximum length of Values arguments we want to support. 3 | $var maxtuple = 10 $$ Maximum number of Combine arguments we want to support. 4 | // Copyright 2008 Google Inc. 5 | // All Rights Reserved. 6 | // 7 | // Redistribution and use in source and binary forms, with or without 8 | // modification, are permitted provided that the following conditions are 9 | // met: 10 | // 11 | // * Redistributions of source code must retain the above copyright 12 | // notice, this list of conditions and the following disclaimer. 13 | // * Redistributions in binary form must reproduce the above 14 | // copyright notice, this list of conditions and the following disclaimer 15 | // in the documentation and/or other materials provided with the 16 | // distribution. 17 | // * Neither the name of Google Inc. nor the names of its 18 | // contributors may be used to endorse or promote products derived from 19 | // this software without specific prior written permission. 20 | // 21 | // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 22 | // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 23 | // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 24 | // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 25 | // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 26 | // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 27 | // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 28 | // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 29 | // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 30 | // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 31 | // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 32 | // 33 | // Author: vladl@google.com (Vlad Losev) 34 | 35 | // Type and function utilities for implementing parameterized tests. 36 | // This file is generated by a SCRIPT. DO NOT EDIT BY HAND! 37 | // 38 | // Currently Google Test supports at most $n arguments in Values, 39 | // and at most $maxtuple arguments in Combine. Please contact 40 | // googletestframework@googlegroups.com if you need more. 41 | // Please note that the number of arguments to Combine is limited 42 | // by the maximum arity of the implementation of tr1::tuple which is 43 | // currently set at $maxtuple. 44 | 45 | #ifndef GTEST_INCLUDE_GTEST_INTERNAL_GTEST_PARAM_UTIL_GENERATED_H_ 46 | #define GTEST_INCLUDE_GTEST_INTERNAL_GTEST_PARAM_UTIL_GENERATED_H_ 47 | 48 | // scripts/fuse_gtest.py depends on gtest's own header being #included 49 | // *unconditionally*. Therefore these #includes cannot be moved 50 | // inside #if GTEST_HAS_PARAM_TEST. 51 | #include "gtest/internal/gtest-param-util.h" 52 | #include "gtest/internal/gtest-port.h" 53 | 54 | #if GTEST_HAS_PARAM_TEST 55 | 56 | namespace testing { 57 | 58 | // Forward declarations of ValuesIn(), which is implemented in 59 | // include/gtest/gtest-param-test.h. 60 | template 61 | internal::ParamGenerator< 62 | typename ::testing::internal::IteratorTraits::value_type> 63 | ValuesIn(ForwardIterator begin, ForwardIterator end); 64 | 65 | template 66 | internal::ParamGenerator ValuesIn(const T (&array)[N]); 67 | 68 | template 69 | internal::ParamGenerator ValuesIn( 70 | const Container& container); 71 | 72 | namespace internal { 73 | 74 | // Used in the Values() function to provide polymorphic capabilities. 75 | template 76 | class ValueArray1 { 77 | public: 78 | explicit ValueArray1(T1 v1) : v1_(v1) {} 79 | 80 | template 81 | operator ParamGenerator() const { return ValuesIn(&v1_, &v1_ + 1); } 82 | 83 | private: 84 | // No implementation - assignment is unsupported. 85 | void operator=(const ValueArray1& other); 86 | 87 | const T1 v1_; 88 | }; 89 | 90 | $range i 2..n 91 | $for i [[ 92 | $range j 1..i 93 | 94 | template <$for j, [[typename T$j]]> 95 | class ValueArray$i { 96 | public: 97 | ValueArray$i($for j, [[T$j v$j]]) : $for j, [[v$(j)_(v$j)]] {} 98 | 99 | template 100 | operator ParamGenerator() const { 101 | const T array[] = {$for j, [[static_cast(v$(j)_)]]}; 102 | return ValuesIn(array); 103 | } 104 | 105 | private: 106 | // No implementation - assignment is unsupported. 107 | void operator=(const ValueArray$i& other); 108 | 109 | $for j [[ 110 | 111 | const T$j v$(j)_; 112 | ]] 113 | 114 | }; 115 | 116 | ]] 117 | 118 | # if GTEST_HAS_COMBINE 119 | // INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE. 120 | // 121 | // Generates values from the Cartesian product of values produced 122 | // by the argument generators. 123 | // 124 | $range i 2..maxtuple 125 | $for i [[ 126 | $range j 1..i 127 | $range k 2..i 128 | 129 | template <$for j, [[typename T$j]]> 130 | class CartesianProductGenerator$i 131 | : public ParamGeneratorInterface< ::std::tr1::tuple<$for j, [[T$j]]> > { 132 | public: 133 | typedef ::std::tr1::tuple<$for j, [[T$j]]> ParamType; 134 | 135 | CartesianProductGenerator$i($for j, [[const ParamGenerator& g$j]]) 136 | : $for j, [[g$(j)_(g$j)]] {} 137 | virtual ~CartesianProductGenerator$i() {} 138 | 139 | virtual ParamIteratorInterface* Begin() const { 140 | return new Iterator(this, $for j, [[g$(j)_, g$(j)_.begin()]]); 141 | } 142 | virtual ParamIteratorInterface* End() const { 143 | return new Iterator(this, $for j, [[g$(j)_, g$(j)_.end()]]); 144 | } 145 | 146 | private: 147 | class Iterator : public ParamIteratorInterface { 148 | public: 149 | Iterator(const ParamGeneratorInterface* base, $for j, [[ 150 | 151 | const ParamGenerator& g$j, 152 | const typename ParamGenerator::iterator& current$(j)]]) 153 | : base_(base), 154 | $for j, [[ 155 | 156 | begin$(j)_(g$j.begin()), end$(j)_(g$j.end()), current$(j)_(current$j) 157 | ]] { 158 | ComputeCurrentValue(); 159 | } 160 | virtual ~Iterator() {} 161 | 162 | virtual const ParamGeneratorInterface* BaseGenerator() const { 163 | return base_; 164 | } 165 | // Advance should not be called on beyond-of-range iterators 166 | // so no component iterators must be beyond end of range, either. 167 | virtual void Advance() { 168 | assert(!AtEnd()); 169 | ++current$(i)_; 170 | 171 | $for k [[ 172 | if (current$(i+2-k)_ == end$(i+2-k)_) { 173 | current$(i+2-k)_ = begin$(i+2-k)_; 174 | ++current$(i+2-k-1)_; 175 | } 176 | 177 | ]] 178 | ComputeCurrentValue(); 179 | } 180 | virtual ParamIteratorInterface* Clone() const { 181 | return new Iterator(*this); 182 | } 183 | virtual const ParamType* Current() const { return ¤t_value_; } 184 | virtual bool Equals(const ParamIteratorInterface& other) const { 185 | // Having the same base generator guarantees that the other 186 | // iterator is of the same type and we can downcast. 187 | GTEST_CHECK_(BaseGenerator() == other.BaseGenerator()) 188 | << "The program attempted to compare iterators " 189 | << "from different generators." << std::endl; 190 | const Iterator* typed_other = 191 | CheckedDowncastToActualType(&other); 192 | // We must report iterators equal if they both point beyond their 193 | // respective ranges. That can happen in a variety of fashions, 194 | // so we have to consult AtEnd(). 195 | return (AtEnd() && typed_other->AtEnd()) || 196 | ($for j && [[ 197 | 198 | current$(j)_ == typed_other->current$(j)_ 199 | ]]); 200 | } 201 | 202 | private: 203 | Iterator(const Iterator& other) 204 | : base_(other.base_), $for j, [[ 205 | 206 | begin$(j)_(other.begin$(j)_), 207 | end$(j)_(other.end$(j)_), 208 | current$(j)_(other.current$(j)_) 209 | ]] { 210 | ComputeCurrentValue(); 211 | } 212 | 213 | void ComputeCurrentValue() { 214 | if (!AtEnd()) 215 | current_value_ = ParamType($for j, [[*current$(j)_]]); 216 | } 217 | bool AtEnd() const { 218 | // We must report iterator past the end of the range when either of the 219 | // component iterators has reached the end of its range. 220 | return 221 | $for j || [[ 222 | 223 | current$(j)_ == end$(j)_ 224 | ]]; 225 | } 226 | 227 | // No implementation - assignment is unsupported. 228 | void operator=(const Iterator& other); 229 | 230 | const ParamGeneratorInterface* const base_; 231 | // begin[i]_ and end[i]_ define the i-th range that Iterator traverses. 232 | // current[i]_ is the actual traversing iterator. 233 | $for j [[ 234 | 235 | const typename ParamGenerator::iterator begin$(j)_; 236 | const typename ParamGenerator::iterator end$(j)_; 237 | typename ParamGenerator::iterator current$(j)_; 238 | ]] 239 | 240 | ParamType current_value_; 241 | }; // class CartesianProductGenerator$i::Iterator 242 | 243 | // No implementation - assignment is unsupported. 244 | void operator=(const CartesianProductGenerator$i& other); 245 | 246 | 247 | $for j [[ 248 | const ParamGenerator g$(j)_; 249 | 250 | ]] 251 | }; // class CartesianProductGenerator$i 252 | 253 | 254 | ]] 255 | 256 | // INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE. 257 | // 258 | // Helper classes providing Combine() with polymorphic features. They allow 259 | // casting CartesianProductGeneratorN to ParamGenerator if T is 260 | // convertible to U. 261 | // 262 | $range i 2..maxtuple 263 | $for i [[ 264 | $range j 1..i 265 | 266 | template <$for j, [[class Generator$j]]> 267 | class CartesianProductHolder$i { 268 | public: 269 | CartesianProductHolder$i($for j, [[const Generator$j& g$j]]) 270 | : $for j, [[g$(j)_(g$j)]] {} 271 | template <$for j, [[typename T$j]]> 272 | operator ParamGenerator< ::std::tr1::tuple<$for j, [[T$j]]> >() const { 273 | return ParamGenerator< ::std::tr1::tuple<$for j, [[T$j]]> >( 274 | new CartesianProductGenerator$i<$for j, [[T$j]]>( 275 | $for j,[[ 276 | 277 | static_cast >(g$(j)_) 278 | ]])); 279 | } 280 | 281 | private: 282 | // No implementation - assignment is unsupported. 283 | void operator=(const CartesianProductHolder$i& other); 284 | 285 | 286 | $for j [[ 287 | const Generator$j g$(j)_; 288 | 289 | ]] 290 | }; // class CartesianProductHolder$i 291 | 292 | ]] 293 | 294 | # endif // GTEST_HAS_COMBINE 295 | 296 | } // namespace internal 297 | } // namespace testing 298 | 299 | #endif // GTEST_HAS_PARAM_TEST 300 | 301 | #endif // GTEST_INCLUDE_GTEST_INTERNAL_GTEST_PARAM_UTIL_GENERATED_H_ 302 | -------------------------------------------------------------------------------- /gtest/include/gtest/internal/gtest-string.h: -------------------------------------------------------------------------------- 1 | // Copyright 2005, Google Inc. 2 | // All rights reserved. 3 | // 4 | // Redistribution and use in source and binary forms, with or without 5 | // modification, are permitted provided that the following conditions are 6 | // met: 7 | // 8 | // * Redistributions of source code must retain the above copyright 9 | // notice, this list of conditions and the following disclaimer. 10 | // * Redistributions in binary form must reproduce the above 11 | // copyright notice, this list of conditions and the following disclaimer 12 | // in the documentation and/or other materials provided with the 13 | // distribution. 14 | // * Neither the name of Google Inc. nor the names of its 15 | // contributors may be used to endorse or promote products derived from 16 | // this software without specific prior written permission. 17 | // 18 | // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 19 | // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 20 | // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 21 | // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 22 | // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 23 | // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 24 | // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 25 | // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 26 | // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 27 | // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 28 | // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 29 | // 30 | // Authors: wan@google.com (Zhanyong Wan), eefacm@gmail.com (Sean Mcafee) 31 | // 32 | // The Google C++ Testing Framework (Google Test) 33 | // 34 | // This header file declares the String class and functions used internally by 35 | // Google Test. They are subject to change without notice. They should not used 36 | // by code external to Google Test. 37 | // 38 | // This header file is #included by . 39 | // It should not be #included by other files. 40 | 41 | #ifndef GTEST_INCLUDE_GTEST_INTERNAL_GTEST_STRING_H_ 42 | #define GTEST_INCLUDE_GTEST_INTERNAL_GTEST_STRING_H_ 43 | 44 | #ifdef __BORLANDC__ 45 | // string.h is not guaranteed to provide strcpy on C++ Builder. 46 | # include 47 | #endif 48 | 49 | #include 50 | #include 51 | 52 | #include "gtest/internal/gtest-port.h" 53 | 54 | namespace testing { 55 | namespace internal { 56 | 57 | // String - an abstract class holding static string utilities. 58 | class GTEST_API_ String { 59 | public: 60 | // Static utility methods 61 | 62 | // Clones a 0-terminated C string, allocating memory using new. The 63 | // caller is responsible for deleting the return value using 64 | // delete[]. Returns the cloned string, or NULL if the input is 65 | // NULL. 66 | // 67 | // This is different from strdup() in string.h, which allocates 68 | // memory using malloc(). 69 | static const char* CloneCString(const char* c_str); 70 | 71 | #if GTEST_OS_WINDOWS_MOBILE 72 | // Windows CE does not have the 'ANSI' versions of Win32 APIs. To be 73 | // able to pass strings to Win32 APIs on CE we need to convert them 74 | // to 'Unicode', UTF-16. 75 | 76 | // Creates a UTF-16 wide string from the given ANSI string, allocating 77 | // memory using new. The caller is responsible for deleting the return 78 | // value using delete[]. Returns the wide string, or NULL if the 79 | // input is NULL. 80 | // 81 | // The wide string is created using the ANSI codepage (CP_ACP) to 82 | // match the behaviour of the ANSI versions of Win32 calls and the 83 | // C runtime. 84 | static LPCWSTR AnsiToUtf16(const char* c_str); 85 | 86 | // Creates an ANSI string from the given wide string, allocating 87 | // memory using new. The caller is responsible for deleting the return 88 | // value using delete[]. Returns the ANSI string, or NULL if the 89 | // input is NULL. 90 | // 91 | // The returned string is created using the ANSI codepage (CP_ACP) to 92 | // match the behaviour of the ANSI versions of Win32 calls and the 93 | // C runtime. 94 | static const char* Utf16ToAnsi(LPCWSTR utf16_str); 95 | #endif 96 | 97 | // Compares two C strings. Returns true iff they have the same content. 98 | // 99 | // Unlike strcmp(), this function can handle NULL argument(s). A 100 | // NULL C string is considered different to any non-NULL C string, 101 | // including the empty string. 102 | static bool CStringEquals(const char* lhs, const char* rhs); 103 | 104 | // Converts a wide C string to a String using the UTF-8 encoding. 105 | // NULL will be converted to "(null)". If an error occurred during 106 | // the conversion, "(failed to convert from wide string)" is 107 | // returned. 108 | static std::string ShowWideCString(const wchar_t* wide_c_str); 109 | 110 | // Compares two wide C strings. Returns true iff they have the same 111 | // content. 112 | // 113 | // Unlike wcscmp(), this function can handle NULL argument(s). A 114 | // NULL C string is considered different to any non-NULL C string, 115 | // including the empty string. 116 | static bool WideCStringEquals(const wchar_t* lhs, const wchar_t* rhs); 117 | 118 | // Compares two C strings, ignoring case. Returns true iff they 119 | // have the same content. 120 | // 121 | // Unlike strcasecmp(), this function can handle NULL argument(s). 122 | // A NULL C string is considered different to any non-NULL C string, 123 | // including the empty string. 124 | static bool CaseInsensitiveCStringEquals(const char* lhs, 125 | const char* rhs); 126 | 127 | // Compares two wide C strings, ignoring case. Returns true iff they 128 | // have the same content. 129 | // 130 | // Unlike wcscasecmp(), this function can handle NULL argument(s). 131 | // A NULL C string is considered different to any non-NULL wide C string, 132 | // including the empty string. 133 | // NB: The implementations on different platforms slightly differ. 134 | // On windows, this method uses _wcsicmp which compares according to LC_CTYPE 135 | // environment variable. On GNU platform this method uses wcscasecmp 136 | // which compares according to LC_CTYPE category of the current locale. 137 | // On MacOS X, it uses towlower, which also uses LC_CTYPE category of the 138 | // current locale. 139 | static bool CaseInsensitiveWideCStringEquals(const wchar_t* lhs, 140 | const wchar_t* rhs); 141 | 142 | // Returns true iff the given string ends with the given suffix, ignoring 143 | // case. Any string is considered to end with an empty suffix. 144 | static bool EndsWithCaseInsensitive( 145 | const std::string& str, const std::string& suffix); 146 | 147 | // Formats an int value as "%02d". 148 | static std::string FormatIntWidth2(int value); // "%02d" for width == 2 149 | 150 | // Formats an int value as "%X". 151 | static std::string FormatHexInt(int value); 152 | 153 | // Formats a byte as "%02X". 154 | static std::string FormatByte(unsigned char value); 155 | 156 | private: 157 | String(); // Not meant to be instantiated. 158 | }; // class String 159 | 160 | // Gets the content of the stringstream's buffer as an std::string. Each '\0' 161 | // character in the buffer is replaced with "\\0". 162 | GTEST_API_ std::string StringStreamToString(::std::stringstream* stream); 163 | 164 | } // namespace internal 165 | } // namespace testing 166 | 167 | #endif // GTEST_INCLUDE_GTEST_INTERNAL_GTEST_STRING_H_ 168 | -------------------------------------------------------------------------------- /gtest/include/gtest/internal/gtest-tuple.h.pump: -------------------------------------------------------------------------------- 1 | $$ -*- mode: c++; -*- 2 | $var n = 10 $$ Maximum number of tuple fields we want to support. 3 | $$ This meta comment fixes auto-indentation in Emacs. }} 4 | // Copyright 2009 Google Inc. 5 | // All Rights Reserved. 6 | // 7 | // Redistribution and use in source and binary forms, with or without 8 | // modification, are permitted provided that the following conditions are 9 | // met: 10 | // 11 | // * Redistributions of source code must retain the above copyright 12 | // notice, this list of conditions and the following disclaimer. 13 | // * Redistributions in binary form must reproduce the above 14 | // copyright notice, this list of conditions and the following disclaimer 15 | // in the documentation and/or other materials provided with the 16 | // distribution. 17 | // * Neither the name of Google Inc. nor the names of its 18 | // contributors may be used to endorse or promote products derived from 19 | // this software without specific prior written permission. 20 | // 21 | // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 22 | // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 23 | // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 24 | // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 25 | // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 26 | // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 27 | // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 28 | // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 29 | // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 30 | // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 31 | // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 32 | // 33 | // Author: wan@google.com (Zhanyong Wan) 34 | 35 | // Implements a subset of TR1 tuple needed by Google Test and Google Mock. 36 | 37 | #ifndef GTEST_INCLUDE_GTEST_INTERNAL_GTEST_TUPLE_H_ 38 | #define GTEST_INCLUDE_GTEST_INTERNAL_GTEST_TUPLE_H_ 39 | 40 | #include // For ::std::pair. 41 | 42 | // The compiler used in Symbian has a bug that prevents us from declaring the 43 | // tuple template as a friend (it complains that tuple is redefined). This 44 | // hack bypasses the bug by declaring the members that should otherwise be 45 | // private as public. 46 | // Sun Studio versions < 12 also have the above bug. 47 | #if defined(__SYMBIAN32__) || (defined(__SUNPRO_CC) && __SUNPRO_CC < 0x590) 48 | # define GTEST_DECLARE_TUPLE_AS_FRIEND_ public: 49 | #else 50 | # define GTEST_DECLARE_TUPLE_AS_FRIEND_ \ 51 | template friend class tuple; \ 52 | private: 53 | #endif 54 | 55 | 56 | $range i 0..n-1 57 | $range j 0..n 58 | $range k 1..n 59 | // GTEST_n_TUPLE_(T) is the type of an n-tuple. 60 | #define GTEST_0_TUPLE_(T) tuple<> 61 | 62 | $for k [[ 63 | $range m 0..k-1 64 | $range m2 k..n-1 65 | #define GTEST_$(k)_TUPLE_(T) tuple<$for m, [[T##$m]]$for m2 [[, void]]> 66 | 67 | ]] 68 | 69 | // GTEST_n_TYPENAMES_(T) declares a list of n typenames. 70 | 71 | $for j [[ 72 | $range m 0..j-1 73 | #define GTEST_$(j)_TYPENAMES_(T) $for m, [[typename T##$m]] 74 | 75 | 76 | ]] 77 | 78 | // In theory, defining stuff in the ::std namespace is undefined 79 | // behavior. We can do this as we are playing the role of a standard 80 | // library vendor. 81 | namespace std { 82 | namespace tr1 { 83 | 84 | template <$for i, [[typename T$i = void]]> 85 | class tuple; 86 | 87 | // Anything in namespace gtest_internal is Google Test's INTERNAL 88 | // IMPLEMENTATION DETAIL and MUST NOT BE USED DIRECTLY in user code. 89 | namespace gtest_internal { 90 | 91 | // ByRef::type is T if T is a reference; otherwise it's const T&. 92 | template 93 | struct ByRef { typedef const T& type; }; // NOLINT 94 | template 95 | struct ByRef { typedef T& type; }; // NOLINT 96 | 97 | // A handy wrapper for ByRef. 98 | #define GTEST_BY_REF_(T) typename ::std::tr1::gtest_internal::ByRef::type 99 | 100 | // AddRef::type is T if T is a reference; otherwise it's T&. This 101 | // is the same as tr1::add_reference::type. 102 | template 103 | struct AddRef { typedef T& type; }; // NOLINT 104 | template 105 | struct AddRef { typedef T& type; }; // NOLINT 106 | 107 | // A handy wrapper for AddRef. 108 | #define GTEST_ADD_REF_(T) typename ::std::tr1::gtest_internal::AddRef::type 109 | 110 | // A helper for implementing get(). 111 | template class Get; 112 | 113 | // A helper for implementing tuple_element. kIndexValid is true 114 | // iff k < the number of fields in tuple type T. 115 | template 116 | struct TupleElement; 117 | 118 | 119 | $for i [[ 120 | template 121 | struct TupleElement { 122 | typedef T$i type; 123 | }; 124 | 125 | 126 | ]] 127 | } // namespace gtest_internal 128 | 129 | template <> 130 | class tuple<> { 131 | public: 132 | tuple() {} 133 | tuple(const tuple& /* t */) {} 134 | tuple& operator=(const tuple& /* t */) { return *this; } 135 | }; 136 | 137 | 138 | $for k [[ 139 | $range m 0..k-1 140 | template 141 | class $if k < n [[GTEST_$(k)_TUPLE_(T)]] $else [[tuple]] { 142 | public: 143 | template friend class gtest_internal::Get; 144 | 145 | tuple() : $for m, [[f$(m)_()]] {} 146 | 147 | explicit tuple($for m, [[GTEST_BY_REF_(T$m) f$m]]) : [[]] 148 | $for m, [[f$(m)_(f$m)]] {} 149 | 150 | tuple(const tuple& t) : $for m, [[f$(m)_(t.f$(m)_)]] {} 151 | 152 | template 153 | tuple(const GTEST_$(k)_TUPLE_(U)& t) : $for m, [[f$(m)_(t.f$(m)_)]] {} 154 | 155 | $if k == 2 [[ 156 | template 157 | tuple(const ::std::pair& p) : f0_(p.first), f1_(p.second) {} 158 | 159 | ]] 160 | 161 | tuple& operator=(const tuple& t) { return CopyFrom(t); } 162 | 163 | template 164 | tuple& operator=(const GTEST_$(k)_TUPLE_(U)& t) { 165 | return CopyFrom(t); 166 | } 167 | 168 | $if k == 2 [[ 169 | template 170 | tuple& operator=(const ::std::pair& p) { 171 | f0_ = p.first; 172 | f1_ = p.second; 173 | return *this; 174 | } 175 | 176 | ]] 177 | 178 | GTEST_DECLARE_TUPLE_AS_FRIEND_ 179 | 180 | template 181 | tuple& CopyFrom(const GTEST_$(k)_TUPLE_(U)& t) { 182 | 183 | $for m [[ 184 | f$(m)_ = t.f$(m)_; 185 | 186 | ]] 187 | return *this; 188 | } 189 | 190 | 191 | $for m [[ 192 | T$m f$(m)_; 193 | 194 | ]] 195 | }; 196 | 197 | 198 | ]] 199 | // 6.1.3.2 Tuple creation functions. 200 | 201 | // Known limitations: we don't support passing an 202 | // std::tr1::reference_wrapper to make_tuple(). And we don't 203 | // implement tie(). 204 | 205 | inline tuple<> make_tuple() { return tuple<>(); } 206 | 207 | $for k [[ 208 | $range m 0..k-1 209 | 210 | template 211 | inline GTEST_$(k)_TUPLE_(T) make_tuple($for m, [[const T$m& f$m]]) { 212 | return GTEST_$(k)_TUPLE_(T)($for m, [[f$m]]); 213 | } 214 | 215 | ]] 216 | 217 | // 6.1.3.3 Tuple helper classes. 218 | 219 | template struct tuple_size; 220 | 221 | 222 | $for j [[ 223 | template 224 | struct tuple_size { 225 | static const int value = $j; 226 | }; 227 | 228 | 229 | ]] 230 | template 231 | struct tuple_element { 232 | typedef typename gtest_internal::TupleElement< 233 | k < (tuple_size::value), k, Tuple>::type type; 234 | }; 235 | 236 | #define GTEST_TUPLE_ELEMENT_(k, Tuple) typename tuple_element::type 237 | 238 | // 6.1.3.4 Element access. 239 | 240 | namespace gtest_internal { 241 | 242 | 243 | $for i [[ 244 | template <> 245 | class Get<$i> { 246 | public: 247 | template 248 | static GTEST_ADD_REF_(GTEST_TUPLE_ELEMENT_($i, Tuple)) 249 | Field(Tuple& t) { return t.f$(i)_; } // NOLINT 250 | 251 | template 252 | static GTEST_BY_REF_(GTEST_TUPLE_ELEMENT_($i, Tuple)) 253 | ConstField(const Tuple& t) { return t.f$(i)_; } 254 | }; 255 | 256 | 257 | ]] 258 | } // namespace gtest_internal 259 | 260 | template 261 | GTEST_ADD_REF_(GTEST_TUPLE_ELEMENT_(k, GTEST_$(n)_TUPLE_(T))) 262 | get(GTEST_$(n)_TUPLE_(T)& t) { 263 | return gtest_internal::Get::Field(t); 264 | } 265 | 266 | template 267 | GTEST_BY_REF_(GTEST_TUPLE_ELEMENT_(k, GTEST_$(n)_TUPLE_(T))) 268 | get(const GTEST_$(n)_TUPLE_(T)& t) { 269 | return gtest_internal::Get::ConstField(t); 270 | } 271 | 272 | // 6.1.3.5 Relational operators 273 | 274 | // We only implement == and !=, as we don't have a need for the rest yet. 275 | 276 | namespace gtest_internal { 277 | 278 | // SameSizeTuplePrefixComparator::Eq(t1, t2) returns true if the 279 | // first k fields of t1 equals the first k fields of t2. 280 | // SameSizeTuplePrefixComparator(k1, k2) would be a compiler error if 281 | // k1 != k2. 282 | template 283 | struct SameSizeTuplePrefixComparator; 284 | 285 | template <> 286 | struct SameSizeTuplePrefixComparator<0, 0> { 287 | template 288 | static bool Eq(const Tuple1& /* t1 */, const Tuple2& /* t2 */) { 289 | return true; 290 | } 291 | }; 292 | 293 | template 294 | struct SameSizeTuplePrefixComparator { 295 | template 296 | static bool Eq(const Tuple1& t1, const Tuple2& t2) { 297 | return SameSizeTuplePrefixComparator::Eq(t1, t2) && 298 | ::std::tr1::get(t1) == ::std::tr1::get(t2); 299 | } 300 | }; 301 | 302 | } // namespace gtest_internal 303 | 304 | template 305 | inline bool operator==(const GTEST_$(n)_TUPLE_(T)& t, 306 | const GTEST_$(n)_TUPLE_(U)& u) { 307 | return gtest_internal::SameSizeTuplePrefixComparator< 308 | tuple_size::value, 309 | tuple_size::value>::Eq(t, u); 310 | } 311 | 312 | template 313 | inline bool operator!=(const GTEST_$(n)_TUPLE_(T)& t, 314 | const GTEST_$(n)_TUPLE_(U)& u) { return !(t == u); } 315 | 316 | // 6.1.4 Pairs. 317 | // Unimplemented. 318 | 319 | } // namespace tr1 320 | } // namespace std 321 | 322 | 323 | $for j [[ 324 | #undef GTEST_$(j)_TUPLE_ 325 | 326 | ]] 327 | 328 | 329 | $for j [[ 330 | #undef GTEST_$(j)_TYPENAMES_ 331 | 332 | ]] 333 | 334 | #undef GTEST_DECLARE_TUPLE_AS_FRIEND_ 335 | #undef GTEST_BY_REF_ 336 | #undef GTEST_ADD_REF_ 337 | #undef GTEST_TUPLE_ELEMENT_ 338 | 339 | #endif // GTEST_INCLUDE_GTEST_INTERNAL_GTEST_TUPLE_H_ 340 | -------------------------------------------------------------------------------- /gtest/include/gtest/internal/gtest-type-util.h.pump: -------------------------------------------------------------------------------- 1 | $$ -*- mode: c++; -*- 2 | $var n = 50 $$ Maximum length of type lists we want to support. 3 | // Copyright 2008 Google Inc. 4 | // All Rights Reserved. 5 | // 6 | // Redistribution and use in source and binary forms, with or without 7 | // modification, are permitted provided that the following conditions are 8 | // met: 9 | // 10 | // * Redistributions of source code must retain the above copyright 11 | // notice, this list of conditions and the following disclaimer. 12 | // * Redistributions in binary form must reproduce the above 13 | // copyright notice, this list of conditions and the following disclaimer 14 | // in the documentation and/or other materials provided with the 15 | // distribution. 16 | // * Neither the name of Google Inc. nor the names of its 17 | // contributors may be used to endorse or promote products derived from 18 | // this software without specific prior written permission. 19 | // 20 | // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 21 | // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 22 | // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 23 | // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 24 | // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 25 | // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 26 | // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 27 | // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 28 | // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 29 | // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 30 | // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 31 | // 32 | // Author: wan@google.com (Zhanyong Wan) 33 | 34 | // Type utilities needed for implementing typed and type-parameterized 35 | // tests. This file is generated by a SCRIPT. DO NOT EDIT BY HAND! 36 | // 37 | // Currently we support at most $n types in a list, and at most $n 38 | // type-parameterized tests in one type-parameterized test case. 39 | // Please contact googletestframework@googlegroups.com if you need 40 | // more. 41 | 42 | #ifndef GTEST_INCLUDE_GTEST_INTERNAL_GTEST_TYPE_UTIL_H_ 43 | #define GTEST_INCLUDE_GTEST_INTERNAL_GTEST_TYPE_UTIL_H_ 44 | 45 | #include "gtest/internal/gtest-port.h" 46 | 47 | // #ifdef __GNUC__ is too general here. It is possible to use gcc without using 48 | // libstdc++ (which is where cxxabi.h comes from). 49 | # if GTEST_HAS_CXXABI_H_ 50 | # include 51 | # elif defined(__HP_aCC) 52 | # include 53 | # endif // GTEST_HASH_CXXABI_H_ 54 | 55 | namespace testing { 56 | namespace internal { 57 | 58 | // GetTypeName() returns a human-readable name of type T. 59 | // NB: This function is also used in Google Mock, so don't move it inside of 60 | // the typed-test-only section below. 61 | template 62 | std::string GetTypeName() { 63 | # if GTEST_HAS_RTTI 64 | 65 | const char* const name = typeid(T).name(); 66 | # if GTEST_HAS_CXXABI_H_ || defined(__HP_aCC) 67 | int status = 0; 68 | // gcc's implementation of typeid(T).name() mangles the type name, 69 | // so we have to demangle it. 70 | # if GTEST_HAS_CXXABI_H_ 71 | using abi::__cxa_demangle; 72 | # endif // GTEST_HAS_CXXABI_H_ 73 | char* const readable_name = __cxa_demangle(name, 0, 0, &status); 74 | const std::string name_str(status == 0 ? readable_name : name); 75 | free(readable_name); 76 | return name_str; 77 | # else 78 | return name; 79 | # endif // GTEST_HAS_CXXABI_H_ || __HP_aCC 80 | 81 | # else 82 | 83 | return ""; 84 | 85 | # endif // GTEST_HAS_RTTI 86 | } 87 | 88 | #if GTEST_HAS_TYPED_TEST || GTEST_HAS_TYPED_TEST_P 89 | 90 | // AssertyTypeEq::type is defined iff T1 and T2 are the same 91 | // type. This can be used as a compile-time assertion to ensure that 92 | // two types are equal. 93 | 94 | template 95 | struct AssertTypeEq; 96 | 97 | template 98 | struct AssertTypeEq { 99 | typedef bool type; 100 | }; 101 | 102 | // A unique type used as the default value for the arguments of class 103 | // template Types. This allows us to simulate variadic templates 104 | // (e.g. Types, Type, and etc), which C++ doesn't 105 | // support directly. 106 | struct None {}; 107 | 108 | // The following family of struct and struct templates are used to 109 | // represent type lists. In particular, TypesN 110 | // represents a type list with N types (T1, T2, ..., and TN) in it. 111 | // Except for Types0, every struct in the family has two member types: 112 | // Head for the first type in the list, and Tail for the rest of the 113 | // list. 114 | 115 | // The empty type list. 116 | struct Types0 {}; 117 | 118 | // Type lists of length 1, 2, 3, and so on. 119 | 120 | template 121 | struct Types1 { 122 | typedef T1 Head; 123 | typedef Types0 Tail; 124 | }; 125 | 126 | $range i 2..n 127 | 128 | $for i [[ 129 | $range j 1..i 130 | $range k 2..i 131 | template <$for j, [[typename T$j]]> 132 | struct Types$i { 133 | typedef T1 Head; 134 | typedef Types$(i-1)<$for k, [[T$k]]> Tail; 135 | }; 136 | 137 | 138 | ]] 139 | 140 | } // namespace internal 141 | 142 | // We don't want to require the users to write TypesN<...> directly, 143 | // as that would require them to count the length. Types<...> is much 144 | // easier to write, but generates horrible messages when there is a 145 | // compiler error, as gcc insists on printing out each template 146 | // argument, even if it has the default value (this means Types 147 | // will appear as Types in the compiler 148 | // errors). 149 | // 150 | // Our solution is to combine the best part of the two approaches: a 151 | // user would write Types, and Google Test will translate 152 | // that to TypesN internally to make error messages 153 | // readable. The translation is done by the 'type' member of the 154 | // Types template. 155 | 156 | $range i 1..n 157 | template <$for i, [[typename T$i = internal::None]]> 158 | struct Types { 159 | typedef internal::Types$n<$for i, [[T$i]]> type; 160 | }; 161 | 162 | template <> 163 | struct Types<$for i, [[internal::None]]> { 164 | typedef internal::Types0 type; 165 | }; 166 | 167 | $range i 1..n-1 168 | $for i [[ 169 | $range j 1..i 170 | $range k i+1..n 171 | template <$for j, [[typename T$j]]> 172 | struct Types<$for j, [[T$j]]$for k[[, internal::None]]> { 173 | typedef internal::Types$i<$for j, [[T$j]]> type; 174 | }; 175 | 176 | ]] 177 | 178 | namespace internal { 179 | 180 | # define GTEST_TEMPLATE_ template class 181 | 182 | // The template "selector" struct TemplateSel is used to 183 | // represent Tmpl, which must be a class template with one type 184 | // parameter, as a type. TemplateSel::Bind::type is defined 185 | // as the type Tmpl. This allows us to actually instantiate the 186 | // template "selected" by TemplateSel. 187 | // 188 | // This trick is necessary for simulating typedef for class templates, 189 | // which C++ doesn't support directly. 190 | template 191 | struct TemplateSel { 192 | template 193 | struct Bind { 194 | typedef Tmpl type; 195 | }; 196 | }; 197 | 198 | # define GTEST_BIND_(TmplSel, T) \ 199 | TmplSel::template Bind::type 200 | 201 | // A unique struct template used as the default value for the 202 | // arguments of class template Templates. This allows us to simulate 203 | // variadic templates (e.g. Templates, Templates, 204 | // and etc), which C++ doesn't support directly. 205 | template 206 | struct NoneT {}; 207 | 208 | // The following family of struct and struct templates are used to 209 | // represent template lists. In particular, TemplatesN represents a list of N templates (T1, T2, ..., and TN). Except 211 | // for Templates0, every struct in the family has two member types: 212 | // Head for the selector of the first template in the list, and Tail 213 | // for the rest of the list. 214 | 215 | // The empty template list. 216 | struct Templates0 {}; 217 | 218 | // Template lists of length 1, 2, 3, and so on. 219 | 220 | template 221 | struct Templates1 { 222 | typedef TemplateSel Head; 223 | typedef Templates0 Tail; 224 | }; 225 | 226 | $range i 2..n 227 | 228 | $for i [[ 229 | $range j 1..i 230 | $range k 2..i 231 | template <$for j, [[GTEST_TEMPLATE_ T$j]]> 232 | struct Templates$i { 233 | typedef TemplateSel Head; 234 | typedef Templates$(i-1)<$for k, [[T$k]]> Tail; 235 | }; 236 | 237 | 238 | ]] 239 | 240 | // We don't want to require the users to write TemplatesN<...> directly, 241 | // as that would require them to count the length. Templates<...> is much 242 | // easier to write, but generates horrible messages when there is a 243 | // compiler error, as gcc insists on printing out each template 244 | // argument, even if it has the default value (this means Templates 245 | // will appear as Templates in the compiler 246 | // errors). 247 | // 248 | // Our solution is to combine the best part of the two approaches: a 249 | // user would write Templates, and Google Test will translate 250 | // that to TemplatesN internally to make error messages 251 | // readable. The translation is done by the 'type' member of the 252 | // Templates template. 253 | 254 | $range i 1..n 255 | template <$for i, [[GTEST_TEMPLATE_ T$i = NoneT]]> 256 | struct Templates { 257 | typedef Templates$n<$for i, [[T$i]]> type; 258 | }; 259 | 260 | template <> 261 | struct Templates<$for i, [[NoneT]]> { 262 | typedef Templates0 type; 263 | }; 264 | 265 | $range i 1..n-1 266 | $for i [[ 267 | $range j 1..i 268 | $range k i+1..n 269 | template <$for j, [[GTEST_TEMPLATE_ T$j]]> 270 | struct Templates<$for j, [[T$j]]$for k[[, NoneT]]> { 271 | typedef Templates$i<$for j, [[T$j]]> type; 272 | }; 273 | 274 | ]] 275 | 276 | // The TypeList template makes it possible to use either a single type 277 | // or a Types<...> list in TYPED_TEST_CASE() and 278 | // INSTANTIATE_TYPED_TEST_CASE_P(). 279 | 280 | template 281 | struct TypeList { 282 | typedef Types1 type; 283 | }; 284 | 285 | 286 | $range i 1..n 287 | template <$for i, [[typename T$i]]> 288 | struct TypeList > { 289 | typedef typename Types<$for i, [[T$i]]>::type type; 290 | }; 291 | 292 | #endif // GTEST_HAS_TYPED_TEST || GTEST_HAS_TYPED_TEST_P 293 | 294 | } // namespace internal 295 | } // namespace testing 296 | 297 | #endif // GTEST_INCLUDE_GTEST_INTERNAL_GTEST_TYPE_UTIL_H_ 298 | -------------------------------------------------------------------------------- /gtest/src/gtest-all.cc: -------------------------------------------------------------------------------- 1 | // Copyright 2008, Google Inc. 2 | // All rights reserved. 3 | // 4 | // Redistribution and use in source and binary forms, with or without 5 | // modification, are permitted provided that the following conditions are 6 | // met: 7 | // 8 | // * Redistributions of source code must retain the above copyright 9 | // notice, this list of conditions and the following disclaimer. 10 | // * Redistributions in binary form must reproduce the above 11 | // copyright notice, this list of conditions and the following disclaimer 12 | // in the documentation and/or other materials provided with the 13 | // distribution. 14 | // * Neither the name of Google Inc. nor the names of its 15 | // contributors may be used to endorse or promote products derived from 16 | // this software without specific prior written permission. 17 | // 18 | // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 19 | // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 20 | // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 21 | // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 22 | // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 23 | // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 24 | // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 25 | // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 26 | // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 27 | // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 28 | // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 29 | // 30 | // Author: mheule@google.com (Markus Heule) 31 | // 32 | // Google C++ Testing Framework (Google Test) 33 | // 34 | // Sometimes it's desirable to build Google Test by compiling a single file. 35 | // This file serves this purpose. 36 | 37 | // This line ensures that gtest.h can be compiled on its own, even 38 | // when it's fused. 39 | #include "gtest/gtest.h" 40 | 41 | // The following lines pull in the real gtest *.cc files. 42 | #include "src/gtest.cc" 43 | #include "src/gtest-death-test.cc" 44 | #include "src/gtest-filepath.cc" 45 | #include "src/gtest-port.cc" 46 | #include "src/gtest-printers.cc" 47 | #include "src/gtest-test-part.cc" 48 | #include "src/gtest-typed-test.cc" 49 | -------------------------------------------------------------------------------- /gtest/src/gtest-filepath.cc: -------------------------------------------------------------------------------- 1 | // Copyright 2008, Google Inc. 2 | // All rights reserved. 3 | // 4 | // Redistribution and use in source and binary forms, with or without 5 | // modification, are permitted provided that the following conditions are 6 | // met: 7 | // 8 | // * Redistributions of source code must retain the above copyright 9 | // notice, this list of conditions and the following disclaimer. 10 | // * Redistributions in binary form must reproduce the above 11 | // copyright notice, this list of conditions and the following disclaimer 12 | // in the documentation and/or other materials provided with the 13 | // distribution. 14 | // * Neither the name of Google Inc. nor the names of its 15 | // contributors may be used to endorse or promote products derived from 16 | // this software without specific prior written permission. 17 | // 18 | // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 19 | // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 20 | // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 21 | // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 22 | // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 23 | // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 24 | // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 25 | // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 26 | // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 27 | // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 28 | // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 29 | // 30 | // Authors: keith.ray@gmail.com (Keith Ray) 31 | 32 | #include "gtest/gtest-message.h" 33 | #include "gtest/internal/gtest-filepath.h" 34 | #include "gtest/internal/gtest-port.h" 35 | 36 | #include 37 | 38 | #if GTEST_OS_WINDOWS_MOBILE 39 | # include 40 | #elif GTEST_OS_WINDOWS 41 | # include 42 | # include 43 | #elif GTEST_OS_SYMBIAN 44 | // Symbian OpenC has PATH_MAX in sys/syslimits.h 45 | # include 46 | #else 47 | # include 48 | # include // Some Linux distributions define PATH_MAX here. 49 | #endif // GTEST_OS_WINDOWS_MOBILE 50 | 51 | #if GTEST_OS_WINDOWS 52 | # define GTEST_PATH_MAX_ _MAX_PATH 53 | #elif defined(PATH_MAX) 54 | # define GTEST_PATH_MAX_ PATH_MAX 55 | #elif defined(_XOPEN_PATH_MAX) 56 | # define GTEST_PATH_MAX_ _XOPEN_PATH_MAX 57 | #else 58 | # define GTEST_PATH_MAX_ _POSIX_PATH_MAX 59 | #endif // GTEST_OS_WINDOWS 60 | 61 | #include "gtest/internal/gtest-string.h" 62 | 63 | namespace testing { 64 | namespace internal { 65 | 66 | #if GTEST_OS_WINDOWS 67 | // On Windows, '\\' is the standard path separator, but many tools and the 68 | // Windows API also accept '/' as an alternate path separator. Unless otherwise 69 | // noted, a file path can contain either kind of path separators, or a mixture 70 | // of them. 71 | const char kPathSeparator = '\\'; 72 | const char kAlternatePathSeparator = '/'; 73 | const char kPathSeparatorString[] = "\\"; 74 | const char kAlternatePathSeparatorString[] = "/"; 75 | # if GTEST_OS_WINDOWS_MOBILE 76 | // Windows CE doesn't have a current directory. You should not use 77 | // the current directory in tests on Windows CE, but this at least 78 | // provides a reasonable fallback. 79 | const char kCurrentDirectoryString[] = "\\"; 80 | // Windows CE doesn't define INVALID_FILE_ATTRIBUTES 81 | const DWORD kInvalidFileAttributes = 0xffffffff; 82 | # else 83 | const char kCurrentDirectoryString[] = ".\\"; 84 | # endif // GTEST_OS_WINDOWS_MOBILE 85 | #else 86 | const char kPathSeparator = '/'; 87 | const char kPathSeparatorString[] = "/"; 88 | const char kCurrentDirectoryString[] = "./"; 89 | #endif // GTEST_OS_WINDOWS 90 | 91 | // Returns whether the given character is a valid path separator. 92 | static bool IsPathSeparator(char c) { 93 | #if GTEST_HAS_ALT_PATH_SEP_ 94 | return (c == kPathSeparator) || (c == kAlternatePathSeparator); 95 | #else 96 | return c == kPathSeparator; 97 | #endif 98 | } 99 | 100 | // Returns the current working directory, or "" if unsuccessful. 101 | FilePath FilePath::GetCurrentDir() { 102 | #if GTEST_OS_WINDOWS_MOBILE 103 | // Windows CE doesn't have a current directory, so we just return 104 | // something reasonable. 105 | return FilePath(kCurrentDirectoryString); 106 | #elif GTEST_OS_WINDOWS 107 | char cwd[GTEST_PATH_MAX_ + 1] = { '\0' }; 108 | return FilePath(_getcwd(cwd, sizeof(cwd)) == NULL ? "" : cwd); 109 | #else 110 | char cwd[GTEST_PATH_MAX_ + 1] = { '\0' }; 111 | return FilePath(getcwd(cwd, sizeof(cwd)) == NULL ? "" : cwd); 112 | #endif // GTEST_OS_WINDOWS_MOBILE 113 | } 114 | 115 | // Returns a copy of the FilePath with the case-insensitive extension removed. 116 | // Example: FilePath("dir/file.exe").RemoveExtension("EXE") returns 117 | // FilePath("dir/file"). If a case-insensitive extension is not 118 | // found, returns a copy of the original FilePath. 119 | FilePath FilePath::RemoveExtension(const char* extension) const { 120 | const std::string dot_extension = std::string(".") + extension; 121 | if (String::EndsWithCaseInsensitive(pathname_, dot_extension)) { 122 | return FilePath(pathname_.substr( 123 | 0, pathname_.length() - dot_extension.length())); 124 | } 125 | return *this; 126 | } 127 | 128 | // Returns a pointer to the last occurence of a valid path separator in 129 | // the FilePath. On Windows, for example, both '/' and '\' are valid path 130 | // separators. Returns NULL if no path separator was found. 131 | const char* FilePath::FindLastPathSeparator() const { 132 | const char* const last_sep = strrchr(c_str(), kPathSeparator); 133 | #if GTEST_HAS_ALT_PATH_SEP_ 134 | const char* const last_alt_sep = strrchr(c_str(), kAlternatePathSeparator); 135 | // Comparing two pointers of which only one is NULL is undefined. 136 | if (last_alt_sep != NULL && 137 | (last_sep == NULL || last_alt_sep > last_sep)) { 138 | return last_alt_sep; 139 | } 140 | #endif 141 | return last_sep; 142 | } 143 | 144 | // Returns a copy of the FilePath with the directory part removed. 145 | // Example: FilePath("path/to/file").RemoveDirectoryName() returns 146 | // FilePath("file"). If there is no directory part ("just_a_file"), it returns 147 | // the FilePath unmodified. If there is no file part ("just_a_dir/") it 148 | // returns an empty FilePath (""). 149 | // On Windows platform, '\' is the path separator, otherwise it is '/'. 150 | FilePath FilePath::RemoveDirectoryName() const { 151 | const char* const last_sep = FindLastPathSeparator(); 152 | return last_sep ? FilePath(last_sep + 1) : *this; 153 | } 154 | 155 | // RemoveFileName returns the directory path with the filename removed. 156 | // Example: FilePath("path/to/file").RemoveFileName() returns "path/to/". 157 | // If the FilePath is "a_file" or "/a_file", RemoveFileName returns 158 | // FilePath("./") or, on Windows, FilePath(".\\"). If the filepath does 159 | // not have a file, like "just/a/dir/", it returns the FilePath unmodified. 160 | // On Windows platform, '\' is the path separator, otherwise it is '/'. 161 | FilePath FilePath::RemoveFileName() const { 162 | const char* const last_sep = FindLastPathSeparator(); 163 | std::string dir; 164 | if (last_sep) { 165 | dir = std::string(c_str(), last_sep + 1 - c_str()); 166 | } else { 167 | dir = kCurrentDirectoryString; 168 | } 169 | return FilePath(dir); 170 | } 171 | 172 | // Helper functions for naming files in a directory for xml output. 173 | 174 | // Given directory = "dir", base_name = "test", number = 0, 175 | // extension = "xml", returns "dir/test.xml". If number is greater 176 | // than zero (e.g., 12), returns "dir/test_12.xml". 177 | // On Windows platform, uses \ as the separator rather than /. 178 | FilePath FilePath::MakeFileName(const FilePath& directory, 179 | const FilePath& base_name, 180 | int number, 181 | const char* extension) { 182 | std::string file; 183 | if (number == 0) { 184 | file = base_name.string() + "." + extension; 185 | } else { 186 | file = base_name.string() + "_" + StreamableToString(number) 187 | + "." + extension; 188 | } 189 | return ConcatPaths(directory, FilePath(file)); 190 | } 191 | 192 | // Given directory = "dir", relative_path = "test.xml", returns "dir/test.xml". 193 | // On Windows, uses \ as the separator rather than /. 194 | FilePath FilePath::ConcatPaths(const FilePath& directory, 195 | const FilePath& relative_path) { 196 | if (directory.IsEmpty()) 197 | return relative_path; 198 | const FilePath dir(directory.RemoveTrailingPathSeparator()); 199 | return FilePath(dir.string() + kPathSeparator + relative_path.string()); 200 | } 201 | 202 | // Returns true if pathname describes something findable in the file-system, 203 | // either a file, directory, or whatever. 204 | bool FilePath::FileOrDirectoryExists() const { 205 | #if GTEST_OS_WINDOWS_MOBILE 206 | LPCWSTR unicode = String::AnsiToUtf16(pathname_.c_str()); 207 | const DWORD attributes = GetFileAttributes(unicode); 208 | delete [] unicode; 209 | return attributes != kInvalidFileAttributes; 210 | #else 211 | posix::StatStruct file_stat; 212 | return posix::Stat(pathname_.c_str(), &file_stat) == 0; 213 | #endif // GTEST_OS_WINDOWS_MOBILE 214 | } 215 | 216 | // Returns true if pathname describes a directory in the file-system 217 | // that exists. 218 | bool FilePath::DirectoryExists() const { 219 | bool result = false; 220 | #if GTEST_OS_WINDOWS 221 | // Don't strip off trailing separator if path is a root directory on 222 | // Windows (like "C:\\"). 223 | const FilePath& path(IsRootDirectory() ? *this : 224 | RemoveTrailingPathSeparator()); 225 | #else 226 | const FilePath& path(*this); 227 | #endif 228 | 229 | #if GTEST_OS_WINDOWS_MOBILE 230 | LPCWSTR unicode = String::AnsiToUtf16(path.c_str()); 231 | const DWORD attributes = GetFileAttributes(unicode); 232 | delete [] unicode; 233 | if ((attributes != kInvalidFileAttributes) && 234 | (attributes & FILE_ATTRIBUTE_DIRECTORY)) { 235 | result = true; 236 | } 237 | #else 238 | posix::StatStruct file_stat; 239 | result = posix::Stat(path.c_str(), &file_stat) == 0 && 240 | posix::IsDir(file_stat); 241 | #endif // GTEST_OS_WINDOWS_MOBILE 242 | 243 | return result; 244 | } 245 | 246 | // Returns true if pathname describes a root directory. (Windows has one 247 | // root directory per disk drive.) 248 | bool FilePath::IsRootDirectory() const { 249 | #if GTEST_OS_WINDOWS 250 | // TODO(wan@google.com): on Windows a network share like 251 | // \\server\share can be a root directory, although it cannot be the 252 | // current directory. Handle this properly. 253 | return pathname_.length() == 3 && IsAbsolutePath(); 254 | #else 255 | return pathname_.length() == 1 && IsPathSeparator(pathname_.c_str()[0]); 256 | #endif 257 | } 258 | 259 | // Returns true if pathname describes an absolute path. 260 | bool FilePath::IsAbsolutePath() const { 261 | const char* const name = pathname_.c_str(); 262 | #if GTEST_OS_WINDOWS 263 | return pathname_.length() >= 3 && 264 | ((name[0] >= 'a' && name[0] <= 'z') || 265 | (name[0] >= 'A' && name[0] <= 'Z')) && 266 | name[1] == ':' && 267 | IsPathSeparator(name[2]); 268 | #else 269 | return IsPathSeparator(name[0]); 270 | #endif 271 | } 272 | 273 | // Returns a pathname for a file that does not currently exist. The pathname 274 | // will be directory/base_name.extension or 275 | // directory/base_name_.extension if directory/base_name.extension 276 | // already exists. The number will be incremented until a pathname is found 277 | // that does not already exist. 278 | // Examples: 'dir/foo_test.xml' or 'dir/foo_test_1.xml'. 279 | // There could be a race condition if two or more processes are calling this 280 | // function at the same time -- they could both pick the same filename. 281 | FilePath FilePath::GenerateUniqueFileName(const FilePath& directory, 282 | const FilePath& base_name, 283 | const char* extension) { 284 | FilePath full_pathname; 285 | int number = 0; 286 | do { 287 | full_pathname.Set(MakeFileName(directory, base_name, number++, extension)); 288 | } while (full_pathname.FileOrDirectoryExists()); 289 | return full_pathname; 290 | } 291 | 292 | // Returns true if FilePath ends with a path separator, which indicates that 293 | // it is intended to represent a directory. Returns false otherwise. 294 | // This does NOT check that a directory (or file) actually exists. 295 | bool FilePath::IsDirectory() const { 296 | return !pathname_.empty() && 297 | IsPathSeparator(pathname_.c_str()[pathname_.length() - 1]); 298 | } 299 | 300 | // Create directories so that path exists. Returns true if successful or if 301 | // the directories already exist; returns false if unable to create directories 302 | // for any reason. 303 | bool FilePath::CreateDirectoriesRecursively() const { 304 | if (!this->IsDirectory()) { 305 | return false; 306 | } 307 | 308 | if (pathname_.length() == 0 || this->DirectoryExists()) { 309 | return true; 310 | } 311 | 312 | const FilePath parent(this->RemoveTrailingPathSeparator().RemoveFileName()); 313 | return parent.CreateDirectoriesRecursively() && this->CreateFolder(); 314 | } 315 | 316 | // Create the directory so that path exists. Returns true if successful or 317 | // if the directory already exists; returns false if unable to create the 318 | // directory for any reason, including if the parent directory does not 319 | // exist. Not named "CreateDirectory" because that's a macro on Windows. 320 | bool FilePath::CreateFolder() const { 321 | #if GTEST_OS_WINDOWS_MOBILE 322 | FilePath removed_sep(this->RemoveTrailingPathSeparator()); 323 | LPCWSTR unicode = String::AnsiToUtf16(removed_sep.c_str()); 324 | int result = CreateDirectory(unicode, NULL) ? 0 : -1; 325 | delete [] unicode; 326 | #elif GTEST_OS_WINDOWS 327 | int result = _mkdir(pathname_.c_str()); 328 | #else 329 | int result = mkdir(pathname_.c_str(), 0777); 330 | #endif // GTEST_OS_WINDOWS_MOBILE 331 | 332 | if (result == -1) { 333 | return this->DirectoryExists(); // An error is OK if the directory exists. 334 | } 335 | return true; // No error. 336 | } 337 | 338 | // If input name has a trailing separator character, remove it and return the 339 | // name, otherwise return the name string unmodified. 340 | // On Windows platform, uses \ as the separator, other platforms use /. 341 | FilePath FilePath::RemoveTrailingPathSeparator() const { 342 | return IsDirectory() 343 | ? FilePath(pathname_.substr(0, pathname_.length() - 1)) 344 | : *this; 345 | } 346 | 347 | // Removes any redundant separators that might be in the pathname. 348 | // For example, "bar///foo" becomes "bar/foo". Does not eliminate other 349 | // redundancies that might be in a pathname involving "." or "..". 350 | // TODO(wan@google.com): handle Windows network shares (e.g. \\server\share). 351 | void FilePath::Normalize() { 352 | if (pathname_.c_str() == NULL) { 353 | pathname_ = ""; 354 | return; 355 | } 356 | const char* src = pathname_.c_str(); 357 | char* const dest = new char[pathname_.length() + 1]; 358 | char* dest_ptr = dest; 359 | memset(dest_ptr, 0, pathname_.length() + 1); 360 | 361 | while (*src != '\0') { 362 | *dest_ptr = *src; 363 | if (!IsPathSeparator(*src)) { 364 | src++; 365 | } else { 366 | #if GTEST_HAS_ALT_PATH_SEP_ 367 | if (*dest_ptr == kAlternatePathSeparator) { 368 | *dest_ptr = kPathSeparator; 369 | } 370 | #endif 371 | while (IsPathSeparator(*src)) 372 | src++; 373 | } 374 | dest_ptr++; 375 | } 376 | *dest_ptr = '\0'; 377 | pathname_ = dest; 378 | delete[] dest; 379 | } 380 | 381 | } // namespace internal 382 | } // namespace testing 383 | -------------------------------------------------------------------------------- /gtest/src/gtest-printers.cc: -------------------------------------------------------------------------------- 1 | // Copyright 2007, Google Inc. 2 | // All rights reserved. 3 | // 4 | // Redistribution and use in source and binary forms, with or without 5 | // modification, are permitted provided that the following conditions are 6 | // met: 7 | // 8 | // * Redistributions of source code must retain the above copyright 9 | // notice, this list of conditions and the following disclaimer. 10 | // * Redistributions in binary form must reproduce the above 11 | // copyright notice, this list of conditions and the following disclaimer 12 | // in the documentation and/or other materials provided with the 13 | // distribution. 14 | // * Neither the name of Google Inc. nor the names of its 15 | // contributors may be used to endorse or promote products derived from 16 | // this software without specific prior written permission. 17 | // 18 | // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 19 | // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 20 | // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 21 | // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 22 | // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 23 | // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 24 | // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 25 | // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 26 | // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 27 | // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 28 | // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 29 | // 30 | // Author: wan@google.com (Zhanyong Wan) 31 | 32 | // Google Test - The Google C++ Testing Framework 33 | // 34 | // This file implements a universal value printer that can print a 35 | // value of any type T: 36 | // 37 | // void ::testing::internal::UniversalPrinter::Print(value, ostream_ptr); 38 | // 39 | // It uses the << operator when possible, and prints the bytes in the 40 | // object otherwise. A user can override its behavior for a class 41 | // type Foo by defining either operator<<(::std::ostream&, const Foo&) 42 | // or void PrintTo(const Foo&, ::std::ostream*) in the namespace that 43 | // defines Foo. 44 | 45 | #include "gtest/gtest-printers.h" 46 | #include 47 | #include 48 | #include // NOLINT 49 | #include 50 | #include "gtest/internal/gtest-port.h" 51 | 52 | namespace testing { 53 | 54 | namespace { 55 | 56 | using ::std::ostream; 57 | 58 | // Prints a segment of bytes in the given object. 59 | void PrintByteSegmentInObjectTo(const unsigned char* obj_bytes, size_t start, 60 | size_t count, ostream* os) { 61 | char text[5] = ""; 62 | for (size_t i = 0; i != count; i++) { 63 | const size_t j = start + i; 64 | if (i != 0) { 65 | // Organizes the bytes into groups of 2 for easy parsing by 66 | // human. 67 | if ((j % 2) == 0) 68 | *os << ' '; 69 | else 70 | *os << '-'; 71 | } 72 | GTEST_SNPRINTF_(text, sizeof(text), "%02X", obj_bytes[j]); 73 | *os << text; 74 | } 75 | } 76 | 77 | // Prints the bytes in the given value to the given ostream. 78 | void PrintBytesInObjectToImpl(const unsigned char* obj_bytes, size_t count, 79 | ostream* os) { 80 | // Tells the user how big the object is. 81 | *os << count << "-byte object <"; 82 | 83 | const size_t kThreshold = 132; 84 | const size_t kChunkSize = 64; 85 | // If the object size is bigger than kThreshold, we'll have to omit 86 | // some details by printing only the first and the last kChunkSize 87 | // bytes. 88 | // TODO(wan): let the user control the threshold using a flag. 89 | if (count < kThreshold) { 90 | PrintByteSegmentInObjectTo(obj_bytes, 0, count, os); 91 | } else { 92 | PrintByteSegmentInObjectTo(obj_bytes, 0, kChunkSize, os); 93 | *os << " ... "; 94 | // Rounds up to 2-byte boundary. 95 | const size_t resume_pos = (count - kChunkSize + 1)/2*2; 96 | PrintByteSegmentInObjectTo(obj_bytes, resume_pos, count - resume_pos, os); 97 | } 98 | *os << ">"; 99 | } 100 | 101 | } // namespace 102 | 103 | namespace internal2 { 104 | 105 | // Delegates to PrintBytesInObjectToImpl() to print the bytes in the 106 | // given object. The delegation simplifies the implementation, which 107 | // uses the << operator and thus is easier done outside of the 108 | // ::testing::internal namespace, which contains a << operator that 109 | // sometimes conflicts with the one in STL. 110 | void PrintBytesInObjectTo(const unsigned char* obj_bytes, size_t count, 111 | ostream* os) { 112 | PrintBytesInObjectToImpl(obj_bytes, count, os); 113 | } 114 | 115 | } // namespace internal2 116 | 117 | namespace internal { 118 | 119 | // Depending on the value of a char (or wchar_t), we print it in one 120 | // of three formats: 121 | // - as is if it's a printable ASCII (e.g. 'a', '2', ' '), 122 | // - as a hexidecimal escape sequence (e.g. '\x7F'), or 123 | // - as a special escape sequence (e.g. '\r', '\n'). 124 | enum CharFormat { 125 | kAsIs, 126 | kHexEscape, 127 | kSpecialEscape 128 | }; 129 | 130 | // Returns true if c is a printable ASCII character. We test the 131 | // value of c directly instead of calling isprint(), which is buggy on 132 | // Windows Mobile. 133 | inline bool IsPrintableAscii(wchar_t c) { 134 | return 0x20 <= c && c <= 0x7E; 135 | } 136 | 137 | // Prints a wide or narrow char c as a character literal without the 138 | // quotes, escaping it when necessary; returns how c was formatted. 139 | // The template argument UnsignedChar is the unsigned version of Char, 140 | // which is the type of c. 141 | template 142 | static CharFormat PrintAsCharLiteralTo(Char c, ostream* os) { 143 | switch (static_cast(c)) { 144 | case L'\0': 145 | *os << "\\0"; 146 | break; 147 | case L'\'': 148 | *os << "\\'"; 149 | break; 150 | case L'\\': 151 | *os << "\\\\"; 152 | break; 153 | case L'\a': 154 | *os << "\\a"; 155 | break; 156 | case L'\b': 157 | *os << "\\b"; 158 | break; 159 | case L'\f': 160 | *os << "\\f"; 161 | break; 162 | case L'\n': 163 | *os << "\\n"; 164 | break; 165 | case L'\r': 166 | *os << "\\r"; 167 | break; 168 | case L'\t': 169 | *os << "\\t"; 170 | break; 171 | case L'\v': 172 | *os << "\\v"; 173 | break; 174 | default: 175 | if (IsPrintableAscii(c)) { 176 | *os << static_cast(c); 177 | return kAsIs; 178 | } else { 179 | *os << "\\x" + String::FormatHexInt(static_cast(c)); 180 | return kHexEscape; 181 | } 182 | } 183 | return kSpecialEscape; 184 | } 185 | 186 | // Prints a wchar_t c as if it's part of a string literal, escaping it when 187 | // necessary; returns how c was formatted. 188 | static CharFormat PrintAsStringLiteralTo(wchar_t c, ostream* os) { 189 | switch (c) { 190 | case L'\'': 191 | *os << "'"; 192 | return kAsIs; 193 | case L'"': 194 | *os << "\\\""; 195 | return kSpecialEscape; 196 | default: 197 | return PrintAsCharLiteralTo(c, os); 198 | } 199 | } 200 | 201 | // Prints a char c as if it's part of a string literal, escaping it when 202 | // necessary; returns how c was formatted. 203 | static CharFormat PrintAsStringLiteralTo(char c, ostream* os) { 204 | return PrintAsStringLiteralTo( 205 | static_cast(static_cast(c)), os); 206 | } 207 | 208 | // Prints a wide or narrow character c and its code. '\0' is printed 209 | // as "'\\0'", other unprintable characters are also properly escaped 210 | // using the standard C++ escape sequence. The template argument 211 | // UnsignedChar is the unsigned version of Char, which is the type of c. 212 | template 213 | void PrintCharAndCodeTo(Char c, ostream* os) { 214 | // First, print c as a literal in the most readable form we can find. 215 | *os << ((sizeof(c) > 1) ? "L'" : "'"); 216 | const CharFormat format = PrintAsCharLiteralTo(c, os); 217 | *os << "'"; 218 | 219 | // To aid user debugging, we also print c's code in decimal, unless 220 | // it's 0 (in which case c was printed as '\\0', making the code 221 | // obvious). 222 | if (c == 0) 223 | return; 224 | *os << " (" << static_cast(c); 225 | 226 | // For more convenience, we print c's code again in hexidecimal, 227 | // unless c was already printed in the form '\x##' or the code is in 228 | // [1, 9]. 229 | if (format == kHexEscape || (1 <= c && c <= 9)) { 230 | // Do nothing. 231 | } else { 232 | *os << ", 0x" << String::FormatHexInt(static_cast(c)); 233 | } 234 | *os << ")"; 235 | } 236 | 237 | void PrintTo(unsigned char c, ::std::ostream* os) { 238 | PrintCharAndCodeTo(c, os); 239 | } 240 | void PrintTo(signed char c, ::std::ostream* os) { 241 | PrintCharAndCodeTo(c, os); 242 | } 243 | 244 | // Prints a wchar_t as a symbol if it is printable or as its internal 245 | // code otherwise and also as its code. L'\0' is printed as "L'\\0'". 246 | void PrintTo(wchar_t wc, ostream* os) { 247 | PrintCharAndCodeTo(wc, os); 248 | } 249 | 250 | // Prints the given array of characters to the ostream. CharType must be either 251 | // char or wchar_t. 252 | // The array starts at begin, the length is len, it may include '\0' characters 253 | // and may not be NUL-terminated. 254 | template 255 | static void PrintCharsAsStringTo( 256 | const CharType* begin, size_t len, ostream* os) { 257 | const char* const kQuoteBegin = sizeof(CharType) == 1 ? "\"" : "L\""; 258 | *os << kQuoteBegin; 259 | bool is_previous_hex = false; 260 | for (size_t index = 0; index < len; ++index) { 261 | const CharType cur = begin[index]; 262 | if (is_previous_hex && IsXDigit(cur)) { 263 | // Previous character is of '\x..' form and this character can be 264 | // interpreted as another hexadecimal digit in its number. Break string to 265 | // disambiguate. 266 | *os << "\" " << kQuoteBegin; 267 | } 268 | is_previous_hex = PrintAsStringLiteralTo(cur, os) == kHexEscape; 269 | } 270 | *os << "\""; 271 | } 272 | 273 | // Prints a (const) char/wchar_t array of 'len' elements, starting at address 274 | // 'begin'. CharType must be either char or wchar_t. 275 | template 276 | static void UniversalPrintCharArray( 277 | const CharType* begin, size_t len, ostream* os) { 278 | // The code 279 | // const char kFoo[] = "foo"; 280 | // generates an array of 4, not 3, elements, with the last one being '\0'. 281 | // 282 | // Therefore when printing a char array, we don't print the last element if 283 | // it's '\0', such that the output matches the string literal as it's 284 | // written in the source code. 285 | if (len > 0 && begin[len - 1] == '\0') { 286 | PrintCharsAsStringTo(begin, len - 1, os); 287 | return; 288 | } 289 | 290 | // If, however, the last element in the array is not '\0', e.g. 291 | // const char kFoo[] = { 'f', 'o', 'o' }; 292 | // we must print the entire array. We also print a message to indicate 293 | // that the array is not NUL-terminated. 294 | PrintCharsAsStringTo(begin, len, os); 295 | *os << " (no terminating NUL)"; 296 | } 297 | 298 | // Prints a (const) char array of 'len' elements, starting at address 'begin'. 299 | void UniversalPrintArray(const char* begin, size_t len, ostream* os) { 300 | UniversalPrintCharArray(begin, len, os); 301 | } 302 | 303 | // Prints a (const) wchar_t array of 'len' elements, starting at address 304 | // 'begin'. 305 | void UniversalPrintArray(const wchar_t* begin, size_t len, ostream* os) { 306 | UniversalPrintCharArray(begin, len, os); 307 | } 308 | 309 | // Prints the given C string to the ostream. 310 | void PrintTo(const char* s, ostream* os) { 311 | if (s == NULL) { 312 | *os << "NULL"; 313 | } else { 314 | *os << ImplicitCast_(s) << " pointing to "; 315 | PrintCharsAsStringTo(s, strlen(s), os); 316 | } 317 | } 318 | 319 | // MSVC compiler can be configured to define whar_t as a typedef 320 | // of unsigned short. Defining an overload for const wchar_t* in that case 321 | // would cause pointers to unsigned shorts be printed as wide strings, 322 | // possibly accessing more memory than intended and causing invalid 323 | // memory accesses. MSVC defines _NATIVE_WCHAR_T_DEFINED symbol when 324 | // wchar_t is implemented as a native type. 325 | #if !defined(_MSC_VER) || defined(_NATIVE_WCHAR_T_DEFINED) 326 | // Prints the given wide C string to the ostream. 327 | void PrintTo(const wchar_t* s, ostream* os) { 328 | if (s == NULL) { 329 | *os << "NULL"; 330 | } else { 331 | *os << ImplicitCast_(s) << " pointing to "; 332 | PrintCharsAsStringTo(s, wcslen(s), os); 333 | } 334 | } 335 | #endif // wchar_t is native 336 | 337 | // Prints a ::string object. 338 | #if GTEST_HAS_GLOBAL_STRING 339 | void PrintStringTo(const ::string& s, ostream* os) { 340 | PrintCharsAsStringTo(s.data(), s.size(), os); 341 | } 342 | #endif // GTEST_HAS_GLOBAL_STRING 343 | 344 | void PrintStringTo(const ::std::string& s, ostream* os) { 345 | PrintCharsAsStringTo(s.data(), s.size(), os); 346 | } 347 | 348 | // Prints a ::wstring object. 349 | #if GTEST_HAS_GLOBAL_WSTRING 350 | void PrintWideStringTo(const ::wstring& s, ostream* os) { 351 | PrintCharsAsStringTo(s.data(), s.size(), os); 352 | } 353 | #endif // GTEST_HAS_GLOBAL_WSTRING 354 | 355 | #if GTEST_HAS_STD_WSTRING 356 | void PrintWideStringTo(const ::std::wstring& s, ostream* os) { 357 | PrintCharsAsStringTo(s.data(), s.size(), os); 358 | } 359 | #endif // GTEST_HAS_STD_WSTRING 360 | 361 | } // namespace internal 362 | 363 | } // namespace testing 364 | -------------------------------------------------------------------------------- /gtest/src/gtest-test-part.cc: -------------------------------------------------------------------------------- 1 | // Copyright 2008, Google Inc. 2 | // All rights reserved. 3 | // 4 | // Redistribution and use in source and binary forms, with or without 5 | // modification, are permitted provided that the following conditions are 6 | // met: 7 | // 8 | // * Redistributions of source code must retain the above copyright 9 | // notice, this list of conditions and the following disclaimer. 10 | // * Redistributions in binary form must reproduce the above 11 | // copyright notice, this list of conditions and the following disclaimer 12 | // in the documentation and/or other materials provided with the 13 | // distribution. 14 | // * Neither the name of Google Inc. nor the names of its 15 | // contributors may be used to endorse or promote products derived from 16 | // this software without specific prior written permission. 17 | // 18 | // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 19 | // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 20 | // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 21 | // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 22 | // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 23 | // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 24 | // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 25 | // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 26 | // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 27 | // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 28 | // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 29 | // 30 | // Author: mheule@google.com (Markus Heule) 31 | // 32 | // The Google C++ Testing Framework (Google Test) 33 | 34 | #include "gtest/gtest-test-part.h" 35 | 36 | // Indicates that this translation unit is part of Google Test's 37 | // implementation. It must come before gtest-internal-inl.h is 38 | // included, or there will be a compiler error. This trick is to 39 | // prevent a user from accidentally including gtest-internal-inl.h in 40 | // his code. 41 | #define GTEST_IMPLEMENTATION_ 1 42 | #include "src/gtest-internal-inl.h" 43 | #undef GTEST_IMPLEMENTATION_ 44 | 45 | namespace testing { 46 | 47 | using internal::GetUnitTestImpl; 48 | 49 | // Gets the summary of the failure message by omitting the stack trace 50 | // in it. 51 | std::string TestPartResult::ExtractSummary(const char* message) { 52 | const char* const stack_trace = strstr(message, internal::kStackTraceMarker); 53 | return stack_trace == NULL ? message : 54 | std::string(message, stack_trace); 55 | } 56 | 57 | // Prints a TestPartResult object. 58 | std::ostream& operator<<(std::ostream& os, const TestPartResult& result) { 59 | return os 60 | << result.file_name() << ":" << result.line_number() << ": " 61 | << (result.type() == TestPartResult::kSuccess ? "Success" : 62 | result.type() == TestPartResult::kFatalFailure ? "Fatal failure" : 63 | "Non-fatal failure") << ":\n" 64 | << result.message() << std::endl; 65 | } 66 | 67 | // Appends a TestPartResult to the array. 68 | void TestPartResultArray::Append(const TestPartResult& result) { 69 | array_.push_back(result); 70 | } 71 | 72 | // Returns the TestPartResult at the given index (0-based). 73 | const TestPartResult& TestPartResultArray::GetTestPartResult(int index) const { 74 | if (index < 0 || index >= size()) { 75 | printf("\nInvalid index (%d) into TestPartResultArray.\n", index); 76 | internal::posix::Abort(); 77 | } 78 | 79 | return array_[index]; 80 | } 81 | 82 | // Returns the number of TestPartResult objects in the array. 83 | int TestPartResultArray::size() const { 84 | return static_cast(array_.size()); 85 | } 86 | 87 | namespace internal { 88 | 89 | HasNewFatalFailureHelper::HasNewFatalFailureHelper() 90 | : has_new_fatal_failure_(false), 91 | original_reporter_(GetUnitTestImpl()-> 92 | GetTestPartResultReporterForCurrentThread()) { 93 | GetUnitTestImpl()->SetTestPartResultReporterForCurrentThread(this); 94 | } 95 | 96 | HasNewFatalFailureHelper::~HasNewFatalFailureHelper() { 97 | GetUnitTestImpl()->SetTestPartResultReporterForCurrentThread( 98 | original_reporter_); 99 | } 100 | 101 | void HasNewFatalFailureHelper::ReportTestPartResult( 102 | const TestPartResult& result) { 103 | if (result.fatally_failed()) 104 | has_new_fatal_failure_ = true; 105 | original_reporter_->ReportTestPartResult(result); 106 | } 107 | 108 | } // namespace internal 109 | 110 | } // namespace testing 111 | -------------------------------------------------------------------------------- /gtest/src/gtest-typed-test.cc: -------------------------------------------------------------------------------- 1 | // Copyright 2008 Google Inc. 2 | // All Rights Reserved. 3 | // 4 | // Redistribution and use in source and binary forms, with or without 5 | // modification, are permitted provided that the following conditions are 6 | // met: 7 | // 8 | // * Redistributions of source code must retain the above copyright 9 | // notice, this list of conditions and the following disclaimer. 10 | // * Redistributions in binary form must reproduce the above 11 | // copyright notice, this list of conditions and the following disclaimer 12 | // in the documentation and/or other materials provided with the 13 | // distribution. 14 | // * Neither the name of Google Inc. nor the names of its 15 | // contributors may be used to endorse or promote products derived from 16 | // this software without specific prior written permission. 17 | // 18 | // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 19 | // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 20 | // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 21 | // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 22 | // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 23 | // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 24 | // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 25 | // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 26 | // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 27 | // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 28 | // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 29 | // 30 | // Author: wan@google.com (Zhanyong Wan) 31 | 32 | #include "gtest/gtest-typed-test.h" 33 | #include "gtest/gtest.h" 34 | 35 | namespace testing { 36 | namespace internal { 37 | 38 | #if GTEST_HAS_TYPED_TEST_P 39 | 40 | // Skips to the first non-space char in str. Returns an empty string if str 41 | // contains only whitespace characters. 42 | static const char* SkipSpaces(const char* str) { 43 | while (IsSpace(*str)) 44 | str++; 45 | return str; 46 | } 47 | 48 | // Verifies that registered_tests match the test names in 49 | // defined_test_names_; returns registered_tests if successful, or 50 | // aborts the program otherwise. 51 | const char* TypedTestCasePState::VerifyRegisteredTestNames( 52 | const char* file, int line, const char* registered_tests) { 53 | typedef ::std::set::const_iterator DefinedTestIter; 54 | registered_ = true; 55 | 56 | // Skip initial whitespace in registered_tests since some 57 | // preprocessors prefix stringizied literals with whitespace. 58 | registered_tests = SkipSpaces(registered_tests); 59 | 60 | Message errors; 61 | ::std::set tests; 62 | for (const char* names = registered_tests; names != NULL; 63 | names = SkipComma(names)) { 64 | const std::string name = GetPrefixUntilComma(names); 65 | if (tests.count(name) != 0) { 66 | errors << "Test " << name << " is listed more than once.\n"; 67 | continue; 68 | } 69 | 70 | bool found = false; 71 | for (DefinedTestIter it = defined_test_names_.begin(); 72 | it != defined_test_names_.end(); 73 | ++it) { 74 | if (name == *it) { 75 | found = true; 76 | break; 77 | } 78 | } 79 | 80 | if (found) { 81 | tests.insert(name); 82 | } else { 83 | errors << "No test named " << name 84 | << " can be found in this test case.\n"; 85 | } 86 | } 87 | 88 | for (DefinedTestIter it = defined_test_names_.begin(); 89 | it != defined_test_names_.end(); 90 | ++it) { 91 | if (tests.count(*it) == 0) { 92 | errors << "You forgot to list test " << *it << ".\n"; 93 | } 94 | } 95 | 96 | const std::string& errors_str = errors.GetString(); 97 | if (errors_str != "") { 98 | fprintf(stderr, "%s %s", FormatFileLocation(file, line).c_str(), 99 | errors_str.c_str()); 100 | fflush(stderr); 101 | posix::Abort(); 102 | } 103 | 104 | return registered_tests; 105 | } 106 | 107 | #endif // GTEST_HAS_TYPED_TEST_P 108 | 109 | } // namespace internal 110 | } // namespace testing 111 | -------------------------------------------------------------------------------- /gtest/src/gtest_main.cc: -------------------------------------------------------------------------------- 1 | // Copyright 2006, Google Inc. 2 | // All rights reserved. 3 | // 4 | // Redistribution and use in source and binary forms, with or without 5 | // modification, are permitted provided that the following conditions are 6 | // met: 7 | // 8 | // * Redistributions of source code must retain the above copyright 9 | // notice, this list of conditions and the following disclaimer. 10 | // * Redistributions in binary form must reproduce the above 11 | // copyright notice, this list of conditions and the following disclaimer 12 | // in the documentation and/or other materials provided with the 13 | // distribution. 14 | // * Neither the name of Google Inc. nor the names of its 15 | // contributors may be used to endorse or promote products derived from 16 | // this software without specific prior written permission. 17 | // 18 | // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 19 | // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 20 | // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 21 | // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 22 | // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 23 | // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 24 | // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 25 | // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 26 | // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 27 | // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 28 | // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 29 | 30 | #include 31 | 32 | #include "gtest/gtest.h" 33 | 34 | GTEST_API_ int main(int argc, char **argv) { 35 | printf("Running main() from gtest_main.cc\n"); 36 | testing::InitGoogleTest(&argc, argv); 37 | return RUN_ALL_TESTS(); 38 | } 39 | -------------------------------------------------------------------------------- /iptree.c: -------------------------------------------------------------------------------- 1 | #include "iptree.h" 2 | 3 | #include 4 | #include 5 | #include 6 | 7 | const uint32_t masks[33] = {0x00000000, 0x80000000, 0xC0000000, 0xE0000000, 8 | 0xF0000000, 0xF8000000, 0xFC000000, 0xFE000000, 9 | 0xFF000000, 0xFF800000, 0xFFC00000, 0xFFE00000, 10 | 0xFFF00000, 0xFFF80000, 0xFFFC0000, 0xFFFE0000, 11 | 0xFFFF0000, 0xFFFF8000, 0xFFFFC000, 0xFFFFE000, 12 | 0xFFFFF000, 0xFFFFF800, 0xFFFFFC00, 0xFFFFFE00, 13 | 0xFFFFFF00, 0xFFFFFF80, 0xFFFFFFC0, 0xFFFFFFE0, 14 | 0xFFFFFFF0, 0xFFFFFFF8, 0xFFFFFFFC, 0xFFFFFFFE, 15 | 0xFFFFFFFF}; 16 | 17 | iptree_node_t *iptree_create () { 18 | iptree_node_t *root = calloc(1, sizeof(iptree_node_t)); 19 | root->prefix = 0; 20 | root->mask = 0; 21 | root->l = NULL; 22 | root->r = NULL; 23 | root->data = NULL; 24 | return root; 25 | } 26 | 27 | iptree_node_t *create_prefix (uint32_t ip, uint32_t mask, char* data) { 28 | iptree_node_t *node = calloc(1, sizeof(iptree_node_t)); 29 | node->prefix = ip & mask; 30 | node->mask = mask; 31 | node->l = NULL; 32 | node->r = NULL; 33 | node->data = data; 34 | return node; 35 | } 36 | 37 | uint32_t findCommonMask (uint32_t ip1, uint32_t ip2){ 38 | uint32_t ipXOR = ip1 ^ ip2; 39 | uint32_t mask = masks[__builtin_clz(ipXOR)]; 40 | return mask; 41 | } 42 | 43 | int iptree_parse_cidr(const char* cidr, uint32_t* ipAddr, uint32_t* mask) { 44 | int ipbytes[4]; 45 | char *slash = strchr(cidr, '/'); 46 | if (slash) { 47 | int count = sscanf(cidr, "%d.%d.%d.%d/%d", &ipbytes[3], &ipbytes[2], 48 | &ipbytes[1], &ipbytes[0], mask); 49 | if (count != 5) { 50 | return EXIT_FAILURE; 51 | } 52 | } else { 53 | int count = sscanf(cidr, "%d.%d.%d.%d", &ipbytes[3], &ipbytes[2], 54 | &ipbytes[1], &ipbytes[0]); 55 | if (count != 4) { 56 | return EXIT_FAILURE; 57 | } 58 | *mask = 0; 59 | } 60 | if (*mask > 32) { 61 | return EXIT_FAILURE; 62 | } 63 | *mask = masks[*mask]; 64 | *ipAddr = ipbytes[0] | ipbytes[1] << 8 | ipbytes[2] << 16 | ipbytes[3] << 24; 65 | return EXIT_SUCCESS; 66 | } 67 | 68 | iptree_node_t *insert_helper (iptree_node_t *root, uint32_t ip, uint32_t mask, 69 | char *data) { 70 | uint32_t commonMask; 71 | if (root->r == NULL) { 72 | root->r = create_prefix(ip, mask, data); 73 | return root->r; 74 | } else if (root->r->prefix == (ip & root->r->mask)) { 75 | if (root->r->mask == mask) { 76 | root->r->data = data; 77 | return root->r; 78 | } else if (root->r->mask > mask) { 79 | iptree_node_t *node = create_prefix(ip, mask, data); 80 | node->r = root->r; 81 | root->r = node; 82 | return root->r; 83 | } else { 84 | return insert_helper(root->r, ip, mask, data); 85 | } 86 | } else if (ip == (root->r->prefix & mask)) { 87 | iptree_node_t *node = create_prefix(ip, mask, data); 88 | node->r = root->r; 89 | root->r = node; 90 | return root->r; 91 | } else if (((commonMask = findCommonMask(root->r->prefix, ip)) & ip) 92 | != root->prefix || commonMask > root->mask) { 93 | iptree_node_t *node = create_prefix(ip, commonMask, NULL); 94 | node->r = root->r; 95 | node->l = create_prefix(ip, mask, data); 96 | root->r = node; 97 | return root->r->l; 98 | } 99 | if (root->l == NULL) { 100 | root->l = create_prefix(ip, mask, data); 101 | return root->l; 102 | } else if (root->l->prefix == (ip & root->l->mask)) { 103 | if (root->l->mask == mask) { 104 | root->l->data = data; 105 | return root->l; 106 | } else if (root->l->mask > mask) { 107 | iptree_node_t *node = create_prefix(ip, mask, data); 108 | node->r = root->l; 109 | root->l = node; 110 | return root->l; 111 | } else { 112 | return insert_helper(root->l, ip, mask, data); 113 | } 114 | } else if (ip == (root->l->prefix & mask)) { 115 | iptree_node_t *node = create_prefix(ip, mask, data); 116 | node->r = root->l; 117 | root->l = node; 118 | return root->l; 119 | } else if (((commonMask = findCommonMask(root->l->prefix, ip)) & ip) 120 | != root->prefix || commonMask > root->mask) { 121 | iptree_node_t *node = create_prefix(ip, commonMask, NULL); 122 | node->r = root->l; 123 | node->l = create_prefix(ip, mask, data); 124 | root->l = node; 125 | return root->l->l; 126 | } else { 127 | return NULL; 128 | } 129 | } 130 | 131 | iptree_node_t *iptree_insert (iptree_node_t *root, uint32_t ip, uint32_t mask, 132 | char *data) { 133 | if (0 == mask) { 134 | root->data = data; 135 | return root; 136 | } 137 | return insert_helper(root, ip, mask, data); 138 | } 139 | 140 | void iptree_insert_str (iptree_node_t *root, const char * cidr, char *data) { 141 | uint32_t ipAddr; 142 | uint32_t mask; 143 | iptree_parse_cidr(cidr, &ipAddr, &mask); 144 | iptree_insert(root, ipAddr, mask, data); 145 | } 146 | 147 | iptree_node_t *lookup_helper (iptree_node_t *root, uint32_t ip, uint32_t mask) { 148 | if (root->r == NULL) { 149 | 150 | } else if (root->r->prefix == (ip & root->r->mask)) { 151 | if (root->r->mask == mask) { 152 | return root->r; 153 | } else if (root->r->mask > mask) { 154 | 155 | } else { 156 | return lookup_helper(root->r, ip, mask); 157 | } 158 | } 159 | if (root->l == NULL) { 160 | return NULL; 161 | } else if (root->l->prefix == (ip & root->l->mask)) { 162 | if (root->l->mask == mask) { 163 | return root->l; 164 | } else if (root->l->mask > mask) { 165 | return NULL; 166 | } else { 167 | return lookup_helper(root->l, ip, mask); 168 | } 169 | } else { 170 | return NULL; 171 | } 172 | } 173 | 174 | iptree_node_t *iptree_lookup_exact (iptree_node_t *root, uint32_t ip, 175 | uint32_t mask) { 176 | if (0 == mask) { 177 | return root; 178 | } 179 | return lookup_helper(root, ip, mask); 180 | } 181 | 182 | iptree_node_t *lookup_best_helper (iptree_node_t *root, uint32_t ip, 183 | iptree_node_t* prefix) { 184 | if (root->r == NULL) { 185 | 186 | } else if (root->r->prefix == (ip & root->r->mask)) { 187 | if (root->r->data != NULL) { 188 | prefix = root->r; 189 | } 190 | return lookup_best_helper(root->r, ip, prefix); 191 | } 192 | if (root->l == NULL) { 193 | return prefix; 194 | } else if (root->l->prefix == (ip & root->l->mask)) { 195 | if (root->l->data != NULL) { 196 | prefix = root->l; 197 | } 198 | return lookup_best_helper(root->l, ip, prefix); 199 | } else { 200 | return prefix; 201 | } 202 | } 203 | 204 | iptree_node_t *iptree_lookup_best (iptree_node_t *root, uint32_t ip) { 205 | iptree_node_t *prefix = ((root->data != NULL) ? root : NULL); 206 | return lookup_best_helper(root, ip, prefix); 207 | } 208 | 209 | char * iptree_lookup_best_str (iptree_node_t *root, const char * ip) { 210 | uint32_t ipAddr; 211 | uint32_t mask; 212 | iptree_parse_cidr(ip, &ipAddr, &mask); 213 | iptree_node_t * ret = iptree_lookup_best(root, ipAddr); 214 | return ((ret == NULL) ? ret : ret->data); 215 | } 216 | 217 | void iptree_remove (iptree_node_t *root, uint32_t ip, uint32_t mask) { 218 | iptree_lookup_exact(root, ip, mask)->data = NULL; 219 | } 220 | 221 | void iptree_remove_str (iptree_node_t *root, const char * cidr) { 222 | uint32_t ipAddr; 223 | uint32_t mask; 224 | iptree_parse_cidr(cidr, &ipAddr, &mask); 225 | iptree_remove(root, ipAddr, mask); 226 | } 227 | 228 | void iptree_destroy (iptree_node_t *root) { 229 | if (root == NULL) { 230 | return; 231 | } 232 | iptree_destroy(root->r); 233 | iptree_destroy(root->l); 234 | free(root); 235 | } 236 | -------------------------------------------------------------------------------- /iptree.h: -------------------------------------------------------------------------------- 1 | /* 2 | * IPTree Copyright 2015 Regents of the University of Michigan 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); you 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 13 | * implied. See the License for the specific language governing 14 | * permissions and limitations under the License. 15 | */ 16 | 17 | #ifndef _IPTREE_H 18 | #define _IPTREE_H 19 | 20 | #ifdef __cplusplus 21 | extern "C" { 22 | #endif 23 | 24 | #include 25 | 26 | extern const uint32_t masks[33]; 27 | 28 | typedef struct _iptree_node_t { 29 | uint32_t prefix; /* what ip prefix */ 30 | uint32_t mask; /* the mask for the subnet */ 31 | struct _iptree_node_t *l, *r; /* left and right children */ 32 | char *data; /* pointer to data */ 33 | } iptree_node_t; 34 | 35 | int iptree_parse_cidr(const char* cidr, uint32_t* ipAddr, uint32_t* mask); 36 | 37 | iptree_node_t *iptree_create (); 38 | iptree_node_t *iptree_lookup_exact (iptree_node_t *root, uint32_t ip, 39 | uint32_t mask); 40 | iptree_node_t *iptree_lookup_best (iptree_node_t *root, uint32_t ip); 41 | char *iptree_lookup_best_str (iptree_node_t *root, const char * ip); 42 | iptree_node_t *iptree_insert (iptree_node_t *root, uint32_t ip, uint32_t mask, 43 | char *data); 44 | void iptree_insert_str (iptree_node_t *root, const char * cidr, char *data); 45 | void iptree_remove (iptree_node_t *root, uint32_t ip, uint32_t mask); 46 | void iptree_remove_str (iptree_node_t *root, const char * cidr); 47 | void iptree_destroy (iptree_node_t *root); 48 | 49 | #ifdef __cplusplus 50 | } 51 | #endif 52 | 53 | #endif /* _IPTREE_H */ 54 | -------------------------------------------------------------------------------- /test.c: -------------------------------------------------------------------------------- 1 | #include "iptree.h" 2 | #include 3 | 4 | int main(void) { 5 | iptree_node_t * root = iptree_create(); 6 | iptree_insert_str(root, "115.114.251.0/0", "h"); 7 | iptree_insert_str(root, "115.114.251.0/24", "heeee"); 8 | iptree_insert_str(root, "213.5.200.0/21", "yeeee"); 9 | iptree_insert_str(root, "8.26.230.0/23", "hee"); 10 | iptree_insert_str(root, "121.244.20.0/23", "hee"); 11 | iptree_insert_str(root, "204.127.151.0/24", "hee"); 12 | iptree_insert_str(root, "91.229.238.0/24", "heeeeeeeeeeeeeeeee"); 13 | iptree_insert_str(root, "69.197.91.0/24", "hee"); 14 | iptree_insert_str(root, "206.117.199.0/24", "haaaaaaaaa"); 15 | iptree_insert_str(root, "200.45.40.0/21", "hee"); 16 | printf("%s\n", iptree_lookup_best_str(root, "91.229.0.0")); 17 | printf("%s\n", iptree_lookup_best_str(root, "91.229.238.0")); 18 | iptree_destroy(root); 19 | return 0; 20 | } 21 | -------------------------------------------------------------------------------- /test_iptree.cc: -------------------------------------------------------------------------------- 1 | #include "iptree.h" 2 | #include 3 | 4 | TEST(CompilationTest, TestsCompile) { 5 | EXPECT_TRUE(true); 6 | } 7 | 8 | TEST(CreateTest,CreateIpTree) { 9 | iptree_node_t * root = iptree_create(); 10 | EXPECT_EQ(root->prefix, 0); 11 | EXPECT_EQ(root->mask, 0); 12 | EXPECT_EQ(root->l, nullptr); 13 | EXPECT_EQ(root->r, nullptr); 14 | EXPECT_EQ(root->data, nullptr); 15 | iptree_destroy(root); 16 | } 17 | 18 | TEST(InsertTest, BasicInsert) { 19 | iptree_node_t * root = iptree_create(); 20 | iptree_node_t * first = iptree_insert(root, 0x8FFFFFFF, 0x80000000, "first child"); 21 | iptree_node_t * second = iptree_insert(root, 0xC7FFFFFF, 0xC0000000, "second child"); 22 | iptree_node_t * third = iptree_insert(root, 0xF70FFFFF, 0xFF000000, "third child"); 23 | iptree_node_t * fourth = iptree_insert(root, 0xF7FFFFFF, 0xFFFFF000, "fourth child"); 24 | iptree_node_t * fifth = iptree_insert(root, 0xF7FFFFFF, 0xFFFFFFFF, "fifth child"); 25 | EXPECT_EQ(root->r, first); 26 | EXPECT_EQ(root->r->r, second); 27 | EXPECT_EQ(root->r->r->r, third); 28 | EXPECT_EQ(root->r->r->r->r, fourth); 29 | EXPECT_EQ(root->r->r->r->r->r, fifth); 30 | EXPECT_STREQ(iptree_lookup_exact(root,0x80000000,0x80000000)->data, "first child"); 31 | EXPECT_STREQ(iptree_lookup_exact(root,0xC0000000,0xC0000000)->data, "second child"); 32 | EXPECT_STREQ(iptree_lookup_exact(root,0xF7000000,0xFF000000)->data, "third child"); 33 | EXPECT_STREQ(iptree_lookup_exact(root,0xF7FFF000,0xFFFFF000)->data, "fourth child"); 34 | EXPECT_STREQ(iptree_lookup_exact(root,0xF7FFFFFF,0xFFFFFFFF)->data, "fifth child"); 35 | iptree_destroy(root); 36 | } 37 | 38 | TEST(InsertTest,InsertRoot) { 39 | iptree_node_t * root = iptree_create(); 40 | iptree_insert(root, 0xFFFFFFFF, 0x00000000, "root value"); 41 | EXPECT_EQ(root->data, "root value"); 42 | iptree_destroy(root); 43 | } 44 | 45 | TEST(InsertTest,InsertExisting) { 46 | iptree_node_t * root = iptree_create(); 47 | iptree_insert(root, 0x8FFFFFFF, 0x80000000, "first child"); 48 | iptree_insert(root, 0xC7FFFFFF, 0xC0000000, "second child"); 49 | iptree_insert(root, 0xF70FFFFF, 0xFF000000, "third child"); 50 | iptree_insert(root, 0xF7FFFFFF, 0xFFFFFFFE, "fourth child"); 51 | iptree_node_t * right = iptree_insert(root, 0xF7FFFFFF, 0xFFFFFFFF, "right child"); 52 | iptree_node_t * left = iptree_insert(root, 0xF7FFFFFE, 0xFFFFFFFF, "left child"); 53 | EXPECT_EQ(root->r->r->r->r->r, right); 54 | EXPECT_EQ(root->r->r->r->r->l, left); 55 | EXPECT_STREQ(iptree_lookup_exact(root,0xF7FFFFFF,0xFFFFFFFF)->data, "right child"); 56 | EXPECT_STREQ(iptree_lookup_exact(root,0xF7FFFFFE,0xFFFFFFFF)->data, "left child"); 57 | right = iptree_insert(root, 0xF7FFFFFF, 0xFFFFFFFF, "new right child"); 58 | left = iptree_insert(root, 0xF7FFFFFE, 0xFFFFFFFF, "new left child"); 59 | EXPECT_STREQ(iptree_lookup_exact(root,0xF7FFFFFF,0xFFFFFFFF)->data, "new right child"); 60 | EXPECT_STREQ(iptree_lookup_exact(root,0xF7FFFFFE,0xFFFFFFFF)->data, "new left child"); 61 | iptree_destroy(root); 62 | } 63 | 64 | TEST(InsertTest, InsertSameIPLargerMask) { 65 | iptree_node_t * root = iptree_create(); 66 | iptree_node_t * first = iptree_insert(root, 0xFFFFFFFF, 0x80000000, "first child"); 67 | iptree_node_t * second = iptree_insert(root, 0xFFFFFFFF, 0xFFFF0000, "second child"); 68 | EXPECT_EQ(root->r, first); 69 | EXPECT_EQ(root->r->r, second); 70 | EXPECT_STREQ(iptree_lookup_exact(root,0xFFFFFFFF,0x80000000)->data, "first child"); 71 | EXPECT_STREQ(iptree_lookup_exact(root,0xFFFFFFFF,0xFFFF0000)->data, "second child"); 72 | iptree_destroy(root); 73 | } 74 | 75 | TEST(InsertTest, InsertSameIPSmallerMask) { 76 | iptree_node_t * root = iptree_create(); 77 | iptree_node_t * second = iptree_insert(root, 0xFFFFFFFF, 0xFFFF0000, "second child"); 78 | EXPECT_EQ(root->r, second); 79 | iptree_node_t * first = iptree_insert(root, 0xFFFFFFFF, 0x80000000, "first child"); 80 | EXPECT_EQ(root->r, first); 81 | EXPECT_EQ(root->r->r, second); 82 | EXPECT_STREQ(iptree_lookup_exact(root,0xFFFFFFFF,0x80000000)->data, "first child"); 83 | EXPECT_STREQ(iptree_lookup_exact(root,0xFFFFFFFF,0xFFFF0000)->data, "second child"); 84 | iptree_destroy(root); 85 | } 86 | 87 | TEST(InsertTest, InsertPrefixOfExisting) { 88 | iptree_node_t * root = iptree_create(); 89 | iptree_node_t * second = iptree_insert(root, 0x0000FFFF, 0xFFFFFFFF, "second child"); 90 | EXPECT_EQ(root->r, second); 91 | iptree_node_t * first = iptree_insert(root, 0x00000000, 0xFFFF0000, "first child"); 92 | EXPECT_EQ(root->r, first); 93 | EXPECT_EQ(root->r->r, second); 94 | EXPECT_STREQ(iptree_lookup_exact(root,0x0000FFFF,0xFFFF0000)->data, "first child"); 95 | EXPECT_STREQ(iptree_lookup_exact(root,0x0000FFFF,0xFFFFFFFF)->data, "second child"); 96 | iptree_destroy(root); 97 | } 98 | 99 | TEST(InsertTest, InsertCommonPrefix) { 100 | iptree_node_t * root = iptree_create(); 101 | iptree_node_t * right = iptree_insert(root, 0x0000FFFF, 0xFFFFFFFF, "right child"); 102 | EXPECT_EQ(root->r, right); 103 | iptree_node_t * left = iptree_insert(root, 0x00F0FFFF, 0xFFFFFFFF, "left child"); 104 | EXPECT_EQ(root->r->prefix, 0x00000000); 105 | EXPECT_EQ(root->r->mask, 0xFF000000); 106 | EXPECT_EQ(root->r->r, right); 107 | EXPECT_EQ(root->r->l, left); 108 | EXPECT_EQ(iptree_lookup_exact(root,0x00000000,0xFF000000)->data, nullptr); 109 | EXPECT_STREQ(iptree_lookup_exact(root,0x0000FFFF,0xFFFFFFFF)->data, "right child"); 110 | EXPECT_STREQ(iptree_lookup_exact(root,0x00F0FFFF,0xFFFFFFFF)->data, "left child"); 111 | iptree_destroy(root); 112 | } 113 | 114 | TEST(InsertTest, InsertIntoIntermediary) { 115 | iptree_node_t * root = iptree_create(); 116 | iptree_node_t * right = iptree_insert(root, 0x0000FFFF, 0xFFFFFFFF, "right child"); 117 | iptree_node_t * left = iptree_insert(root, 0x00F0FFFF, 0xFFFFFFFF, "left child"); 118 | iptree_node_t * intermediary = iptree_insert(root, 0x00000000, 0xFF000000, "intermediary"); 119 | EXPECT_EQ(root->r, intermediary); 120 | EXPECT_EQ(root->r->r, right); 121 | EXPECT_EQ(root->r->l, left); 122 | EXPECT_EQ(iptree_lookup_exact(root,0x00000000,0xFF000000)->data, "intermediary"); 123 | EXPECT_STREQ(iptree_lookup_exact(root,0x0000FFFF,0xFFFFFFFF)->data, "right child"); 124 | EXPECT_STREQ(iptree_lookup_exact(root,0x00F0FFFF,0xFFFFFFFF)->data, "left child"); 125 | iptree_destroy(root); 126 | } 127 | 128 | TEST(InsertTest, InsertCommonPrefixFullChildren) { 129 | // Similar to above children but both left and right children exist when 130 | // the ip with a common prefix is inserted 131 | iptree_node_t * root = iptree_create(); 132 | iptree_node_t * right = iptree_insert(root, 0x0000FFFF, 0xFFFF0000, "right child"); 133 | EXPECT_EQ(root->r, right); 134 | iptree_node_t * left = iptree_insert(root, 0xF0F0FFFF, 0xFFFF0000, "left child"); 135 | EXPECT_EQ(root->l, left); 136 | iptree_node_t * common_with_left = iptree_insert(root, 0xF0FFFFFF, 0xFFFF0000, "left left child"); 137 | iptree_node_t * common_with_right = iptree_insert(root, 0x000FFFFF, 0xFFFF0000, "right left child"); 138 | EXPECT_EQ(root->l->prefix, 0xF0F00000); 139 | EXPECT_EQ(root->l->mask, 0xFFF00000); 140 | EXPECT_EQ(root->r->prefix, 0x00000000); 141 | EXPECT_EQ(root->r->mask, 0xFFF00000); 142 | EXPECT_EQ(root->r->r, right); 143 | EXPECT_EQ(root->r->l, common_with_right); 144 | EXPECT_EQ(root->l->r, left); 145 | EXPECT_EQ(root->l->l, common_with_left); 146 | EXPECT_EQ(iptree_lookup_exact(root,0x00000000,0xFFF00000)->data, nullptr); 147 | EXPECT_EQ(iptree_lookup_exact(root,0xF0F00000,0xFFF00000)->data, nullptr); 148 | EXPECT_STREQ(iptree_lookup_exact(root,0x0000FFFF,0xFFFF0000)->data, "right child"); 149 | EXPECT_STREQ(iptree_lookup_exact(root,0x000FFFFF,0xFFFF0000)->data, "right left child"); 150 | EXPECT_STREQ(iptree_lookup_exact(root,0xF0F0FFFF,0xFFFF0000)->data, "left child"); 151 | EXPECT_STREQ(iptree_lookup_exact(root,0xF0FFFFFF,0xFFFF0000)->data, "left left child"); 152 | iptree_destroy(root); 153 | } 154 | 155 | TEST(LookupTest, BasicLookup) { 156 | iptree_node_t * root = iptree_create(); 157 | iptree_insert(root, 0x8FFFFFFF, 0x00000000, "root"); 158 | EXPECT_STREQ(iptree_lookup_best(root,0xF7FFFFFF)->data, "root"); 159 | iptree_insert(root, 0x8FFFFFFF, 0x80000000, "first child"); 160 | EXPECT_STREQ(iptree_lookup_best(root,0xF7FFFFFF)->data, "first child"); 161 | iptree_insert(root, 0xC7FFFFFF, 0xC0000000, "second child"); 162 | EXPECT_STREQ(iptree_lookup_best(root,0xF7FFFFFF)->data, "second child"); 163 | iptree_insert(root, 0xF70FFFFF, 0xFF000000, "third child"); 164 | EXPECT_STREQ(iptree_lookup_best(root,0xF7FFFFFF)->data, "third child"); 165 | iptree_insert(root, 0xF7FFFFFF, 0xFFFFF000, "fourth child"); 166 | EXPECT_STREQ(iptree_lookup_best(root,0xF7FFFFFF)->data, "fourth child"); 167 | iptree_insert(root, 0xF7FFFFFF, 0xFFFFFFFF, "fifth child"); 168 | EXPECT_STREQ(iptree_lookup_best(root,0xF7FFFFFF)->data, "fifth child"); 169 | iptree_destroy(root); 170 | 171 | } 172 | 173 | TEST(LookupTest, LookupWithIntermediary) { 174 | iptree_node_t * root = iptree_create(); 175 | iptree_insert(root, 0x8FFFFFFF, 0x00000000, "root"); 176 | EXPECT_STREQ(iptree_lookup_best(root,0xF7FFFFFF)->data, "root"); 177 | iptree_insert(root, 0x8FFFFFFF, 0x80000000, "first child"); 178 | EXPECT_STREQ(iptree_lookup_best(root,0xF7FFFFFF)->data, "first child"); 179 | iptree_insert(root, 0xC7FFFFFF, 0xC0000000, "second child"); 180 | EXPECT_STREQ(iptree_lookup_best(root,0xF7FFFFFF)->data, "second child"); 181 | iptree_insert(root, 0xF70FFFFF, 0xFF000000, "third child"); 182 | EXPECT_STREQ(iptree_lookup_best(root,0xF7FFFFFF)->data, "third child"); 183 | iptree_insert(root, 0xF60FFFFF, 0xFF000000, "wrong child"); 184 | EXPECT_STREQ(iptree_lookup_best(root,0xF7FFFFFF)->data, "third child"); 185 | iptree_insert(root, 0xF7FFFFFF, 0xFFFFF000, "fourth child"); 186 | EXPECT_STREQ(iptree_lookup_best(root,0xF7FFFFFF)->data, "fourth child"); 187 | iptree_insert(root, 0xF7FFFFFF, 0xFFFFFFFF, "fifth child"); 188 | EXPECT_STREQ(iptree_lookup_best(root,0xF7FFFFFF)->data, "fifth child"); 189 | iptree_destroy(root); 190 | 191 | } 192 | 193 | TEST(LookupTest, LookupRoot) { 194 | iptree_node_t * root = iptree_create(); 195 | iptree_insert(root, 0x8FFFFFFF, 0x00000000, "root"); 196 | iptree_insert(root, 0x8FFFFFFF, 0x80000000, "first child"); 197 | iptree_insert(root, 0xC7FFFFFF, 0xC0000000, "second child"); 198 | iptree_insert(root, 0xF70FFFFF, 0xFF000000, "third child"); 199 | iptree_insert(root, 0xF7FFFFFF, 0xFFFFF000, "fourth child"); 200 | iptree_insert(root, 0xF7FFFFFF, 0xFFFFFFFF, "fifth child"); 201 | EXPECT_STREQ(iptree_lookup_best(root,0x07FFFFFF)->data, "root"); 202 | iptree_destroy(root); 203 | 204 | } 205 | 206 | TEST(LookupTest, LookupAffectedByInsert) { 207 | iptree_node_t * root = iptree_create(); 208 | iptree_insert(root, 0x8FFFFFFF, 0x00000000, "root"); 209 | iptree_insert(root, 0x8FFFFFFF, 0x80000000, "first child"); 210 | iptree_insert(root, 0xC7FFFFFF, 0xC0000000, "second child"); 211 | iptree_insert(root, 0xF70FFFFF, 0xFF000000, "third child"); 212 | EXPECT_STREQ(iptree_lookup_best(root,0xF7FFFFFF)->data, "third child"); 213 | iptree_insert(root, 0xF70FFFFF, 0xFF000000, "new third child"); 214 | EXPECT_STREQ(iptree_lookup_best(root,0xF7FFFFFF)->data, "new third child"); 215 | iptree_destroy(root); 216 | 217 | } 218 | 219 | TEST(LookupTest, LookupWithNullRoot) { 220 | iptree_node_t * root = iptree_create(); 221 | EXPECT_EQ(iptree_lookup_best(root,0xF7FFFFFF), nullptr); 222 | iptree_insert(root, 0x8FFFFFFF, 0x80000000, "first child"); 223 | EXPECT_STREQ(iptree_lookup_best(root,0xF7FFFFFF)->data, "first child"); 224 | iptree_destroy(root); 225 | 226 | } 227 | 228 | TEST(RemoveTest, RemoveTest) { 229 | iptree_node_t * root = iptree_create(); 230 | iptree_insert(root, 0x8FFFFFFF, 0x00000000, "root"); 231 | iptree_insert(root, 0x8FFFFFFF, 0x80000000, "first child"); 232 | iptree_insert(root, 0xC7FFFFFF, 0xC0000000, "second child"); 233 | iptree_insert(root, 0xF70FFFFF, 0xFF000000, "third child"); 234 | iptree_insert(root, 0xF7FFFFFF, 0xFFFFF000, "fourth child"); 235 | iptree_insert(root, 0xF7FFFFFF, 0xFFFFFFFF, "fifth child"); 236 | EXPECT_STREQ(iptree_lookup_best(root,0xF7FFFFFF)->data, "fifth child"); 237 | iptree_remove(root, 0xF7FFFFFF, 0xFFFFFFFF); 238 | EXPECT_STREQ(iptree_lookup_best(root,0xF7FFFFFF)->data, "fourth child"); 239 | iptree_destroy(root); 240 | 241 | } 242 | 243 | TEST(WrapperTest, WrapperTest) { 244 | iptree_node_t * root = iptree_create(); 245 | iptree_insert_str(root, "143.255.255.255/0", "root"); 246 | EXPECT_STREQ(iptree_lookup_best_str(root,"247.255.255.255"), "root"); 247 | iptree_insert_str(root, "143.255.255.255/1", "first child"); 248 | EXPECT_STREQ(iptree_lookup_best_str(root, "247.255.255.255"), "first child"); 249 | iptree_insert_str(root, "199.255.255.255/2", "second child"); 250 | EXPECT_STREQ(iptree_lookup_best_str(root, "247.255.255.255"), "second child"); 251 | iptree_insert_str(root, "247.15.255.255/8", "third child"); 252 | EXPECT_STREQ(iptree_lookup_best_str(root, "247.255.255.255"), "third child"); 253 | iptree_insert_str(root, "247.255.255.255/20", "fourth child"); 254 | EXPECT_STREQ(iptree_lookup_best_str(root, "247.255.255.255"), "fourth child"); 255 | iptree_insert_str(root, "247.255.255.255/32", "fifth child"); 256 | EXPECT_STREQ(iptree_lookup_best_str(root, "247.255.255.255"), "fifth child"); 257 | iptree_destroy(root); 258 | } 259 | 260 | TEST(IPTreeTest, ParseCidr) { 261 | uint32_t ip, mask; 262 | EXPECT_EQ(EXIT_SUCCESS, iptree_parse_cidr("1.2.3.4/32", &ip, &mask)); 263 | EXPECT_EQ(0x01020304, ip); 264 | EXPECT_EQ(mask, 0xFFFFFFFF); 265 | 266 | EXPECT_EQ(EXIT_SUCCESS, iptree_parse_cidr("228.32.127.4/17", &ip, &mask)); 267 | EXPECT_EQ(0xE4207F04, ip); 268 | EXPECT_EQ(mask, 0xFFFF8000); 269 | 270 | EXPECT_EQ(EXIT_FAILURE, iptree_parse_cidr("1.2.3.4/33", &ip, &mask)); 271 | EXPECT_EQ(EXIT_FAILURE, iptree_parse_cidr("1.2.3.4/-2", &ip, &mask)); 272 | 273 | EXPECT_EQ(EXIT_SUCCESS, iptree_parse_cidr("13.1.99.1/1", &ip, &mask)); 274 | EXPECT_EQ(0x0D016301, ip); 275 | EXPECT_EQ(mask, 0x80000000); 276 | } 277 | --------------------------------------------------------------------------------