SConscript 15.4 KB
Newer Older
1
# -*- Python -*-
2
# Copyright 2008 Google Inc. All Rights Reserved.
shiqian's avatar
shiqian committed
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
#     * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
#     * Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following disclaimer
# in the documentation and/or other materials provided with the
# distribution.
#     * Neither the name of Google Inc. nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.


31
32
33
"""Builds the Google Test (gtest) lib. This has been tested on Windows,
Linux, Mac OS X, and Cygwin.  The compilation settings from your project
will be used, with some specific flags required for gtest added.
shiqian's avatar
shiqian committed
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66

You should be able to call this file from more or less any SConscript
file.

You can optionally set a variable on the construction environment to
have the unit test executables copied to your output directory.  The
variable should be env['EXE_OUTPUT'].

Another optional variable is env['LIB_OUTPUT'].  If set, the generated
libraries are copied to the folder indicated by the variable.

If you place the gtest sources within your own project's source
directory, you should be able to call this SConscript file simply as
follows:

# -- cut here --
# Build gtest library; first tell it where to copy executables.
env['EXE_OUTPUT'] = '#/mybuilddir/mybuildmode'  # example, optional
env['LIB_OUTPUT'] = '#/mybuilddir/mybuildmode/lib'
env.SConscript('whateverpath/gtest/scons/SConscript')
# -- cut here --

If on the other hand you place the gtest sources in a directory
outside of your project's source tree, you would use a snippet similar
to the following:

# -- cut here --

# The following assumes that $BUILD_DIR refers to the root of the
# directory for your current build mode, e.g. "#/mybuilddir/mybuildmode"

# Build gtest library; as it is outside of our source root, we need to
# tell SCons that the directory it will refer to as
67
# e.g. $BUILD_DIR/gtest is actually on disk in original form as
shiqian's avatar
shiqian committed
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
# ../../gtest (relative to your project root directory).  Recall that
# SCons by default copies all source files into the build directory
# before building.
gtest_dir = env.Dir('$BUILD_DIR/gtest')

# Modify this part to point to gtest relative to the current
# SConscript or SConstruct file's directory.  The ../.. path would
# be different per project, to locate the base directory for gtest.
gtest_dir.addRepository(env.Dir('../../gtest'))

# Tell the gtest SCons file where to copy executables.
env['EXE_OUTPUT'] = '$BUILD_DIR'  # example, optional

# Call the gtest SConscript to build gtest.lib and unit tests.  The
# location of the library should end up as
# '$BUILD_DIR/gtest/scons/gtest.lib'
env.SConscript(env.File('scons/SConscript', gtest_dir))

# -- cut here --
"""


__author__ = 'joi@google.com (Joi Sigurdsson)'


93
94
95
96
97
import os

############################################################
# Environments for building the targets, sorted by name.

98
99
Import('env')
env = env.Clone()
100

101
BUILD_TESTS = env.get('GTEST_BUILD_TESTS', False)
102
103
common_exports = SConscript('SConscript.common')
EnvCreator = common_exports['EnvCreator']
104

105
106
107
108
# Note: The relative paths in SConscript files are relative to the location
# of the SConscript file itself. To make a path relative to the location of
# the main SConstruct file, prepend the path with the # sign.
#
109
110
111
112
113
# But if a project uses variant builds without source duplication (see
# http://www.scons.org/wiki/VariantDir%28%29 for more information), the
# above rule gets muddied a bit. In that case the paths must be counted from
# the location of the copy of the SConscript file in
# scons/build/<config>/gtest/scons.
114
#
115
116
117
# Include paths to gtest headers are relative to either the gtest
# directory or the 'include' subdirectory of it, and this SConscript
# file is one directory deeper than the gtest directory.
118
env.Prepend(CPPPATH = ['..', '../include'])
shiqian's avatar
shiqian committed
119

120
121
122
123
124
125
126
127
128
129
env_use_own_tuple = EnvCreator.Create(env, EnvCreator.UseOwnTuple)
env_less_optimized = EnvCreator.Create(env, EnvCreator.LessOptimized)
env_with_threads = EnvCreator.Create(env, EnvCreator.WithThreads)
# The following environments are used to compile gtest_unittest.cc, which
# triggers a warning  in all but the most recent GCC versions when compiling
# the EXPECT_EQ(NULL, ptr) statement.
env_warning_ok = EnvCreator.Create(env, EnvCreator.WarningOk)
env_with_exceptions = EnvCreator.Create(env_warning_ok,
                                        EnvCreator.WithExceptions)
env_without_rtti = EnvCreator.Create(env_warning_ok, EnvCreator.NoRtti)
130

131
132
133
134
env_with_exceptions_and_threads = EnvCreator.Create(env_with_threads,
                                                    EnvCreator.WithExceptions)
env_with_exceptions_and_threads['OBJ_SUFFIX'] = '_with_exceptions_and_threads'

135
136
############################################################
# Helpers for creating build targets.
137

138
139
140
141
142
# Caches object file targets built by GtestObject to allow passing the
# same source file with the same environment twice into the function as a
# convenience.
_all_objects = {}

143
144
145
146

def GetObjSuffix(env):
  return env.get('OBJ_SUFFIX', '')

147
148
def GtestObject(build_env, source):
  """Returns a target to build an object file from the given .cc source file."""
shiqian's avatar
shiqian committed
149

150
  object_name = os.path.basename(source).rstrip('.cc') + GetObjSuffix(build_env)
151
152
153
154
  if object_name not in _all_objects:
    _all_objects[object_name] = build_env.Object(target=object_name,
                                                 source=source)
  return _all_objects[object_name]
shiqian's avatar
shiqian committed
155
156


157
158
159
160
161
162
163
164
165
166
167
168
169
def GtestStaticLibraries(build_env):
  """Builds static libraries for gtest and gtest_main in build_env.

  Args:
    build_env: An environment in which to build libraries.

  Returns:
    A pair (gtest library, gtest_main library) built in the given environment.
  """

  gtest_object = GtestObject(build_env, '../src/gtest-all.cc')
  gtest_main_object = GtestObject(build_env, '../src/gtest_main.cc')

170
  return (build_env.StaticLibrary(target='gtest' + GetObjSuffix(build_env),
171
                                  source=[gtest_object]),
172
          build_env.StaticLibrary(target='gtest_main' + GetObjSuffix(build_env),
173
                                  source=[gtest_object, gtest_main_object]))
shiqian's avatar
shiqian committed
174

175

176
def GtestBinary(build_env, target, gtest_libs, sources):
177
  """Creates a target to build a binary (either test or sample).
178
179

  Args:
180
181
182
    build_env:  The SCons construction environment to use to build.
    target:     The basename of the target's main source file, also used as the
                target name.
183
    gtest_libs: The gtest library or the list of libraries to link.
184
    sources:    A list of source files in the target.
185
  """
186
187
188
189
190
191
192
193
194
195
  srcs = []  # The object targets corresponding to sources.
  for src in sources:
    if type(src) is str:
      srcs.append(GtestObject(build_env, src))
    else:
      srcs.append(src)

  if not gtest_libs:
    gtest_libs = []
  elif type(gtest_libs) != type(list()):
196
    gtest_libs = [gtest_libs]
197
198
199
200
201
  binary = build_env.Program(target=target, source=srcs, LIBS=gtest_libs)
  if 'EXE_OUTPUT' in build_env.Dictionary():
    build_env.Install('$EXE_OUTPUT', source=[binary])


202
def GtestTest(build_env, target, gtest_libs, additional_sources=None):
203
  """Creates a target to build the given test.
204
205

  Args:
206
207
    build_env:  The SCons construction environment to use to build.
    target:     The basename of the target test .cc file.
208
    gtest_libs: The gtest library or the list of libraries to use.
209
    additional_sources: A list of additional source files in the target.
210
  """
211
212

  GtestBinary(build_env, target, gtest_libs,
213
              ['../test/%s.cc' % target] + (additional_sources or []))
214

215

216
def GtestSample(build_env, target, additional_sources=None):
217
  """Creates a target to build the given sample.
218
219

  Args:
220
221
    build_env:  The SCons construction environment to use to build.
    target:     The basename of the target sample .cc file.
222
    gtest_libs: The gtest library or the list of libraries to use.
223
    additional_sources: A list of additional source files in the target.
224
  """
225
226
227
  GtestBinary(build_env, target, gtest_main,
              ['../samples/%s.cc' % target] + (additional_sources or []))

228
229
230
231

############################################################
# Object and library targets.

232
233
234
235
# gtest.lib to be used by most apps (if you have your own main function).
# gtest_main.lib can be used if you just want a basic main function; it is also
# used by some tests for Google Test itself.
gtest, gtest_main = GtestStaticLibraries(env)
236
237
238
gtest_ex, gtest_main_ex = GtestStaticLibraries(env_with_exceptions)
gtest_no_rtti, gtest_main_no_rtti = GtestStaticLibraries(env_without_rtti)
gtest_use_own_tuple, gtest_main_use_own_tuple = GtestStaticLibraries(
239
240
241
242
243
    env_use_own_tuple)
gtest_with_threads, gtest_main_with_threads = GtestStaticLibraries(
    env_with_threads)
gtest_ex_with_threads, gtest_main_ex_with_threads = GtestStaticLibraries(
    env_with_exceptions_and_threads)
244
245
246

# Install the libraries if needed.
if 'LIB_OUTPUT' in env.Dictionary():
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
  env.Install('$LIB_OUTPUT', source=[gtest, gtest_main])

if BUILD_TESTS:
  ############################################################
  # Test targets using the standard environment.
  GtestTest(env, 'gtest-filepath_test', gtest_main)
  GtestTest(env, 'gtest-message_test', gtest_main)
  GtestTest(env, 'gtest-options_test', gtest_main)
  GtestTest(env, 'gtest_environment_test', gtest)
  GtestTest(env, 'gtest_main_unittest', gtest_main)
  GtestTest(env, 'gtest_no_test_unittest', gtest)
  GtestTest(env, 'gtest_pred_impl_unittest', gtest_main)
  GtestTest(env, 'gtest_prod_test', gtest_main,
            additional_sources=['../test/production.cc'])
  GtestTest(env, 'gtest_repeat_test', gtest)
  GtestTest(env, 'gtest_sole_header_test', gtest_main)
  GtestTest(env, 'gtest-test-part_test', gtest_main)
  GtestTest(env, 'gtest-typed-test_test', gtest_main,
            additional_sources=['../test/gtest-typed-test2_test.cc'])
  GtestTest(env, 'gtest-param-test_test', gtest,
            additional_sources=['../test/gtest-param-test2_test.cc'])
  GtestTest(env, 'gtest_color_test_', gtest)
  GtestTest(env, 'gtest-linked_ptr_test', gtest_main)
  GtestTest(env, 'gtest_break_on_failure_unittest_', gtest)
  GtestTest(env, 'gtest_filter_unittest_', gtest)
  GtestTest(env, 'gtest_help_test_', gtest_main)
  GtestTest(env, 'gtest_list_tests_unittest_', gtest)
  GtestTest(env, 'gtest_throw_on_failure_test_', gtest)
  GtestTest(env, 'gtest_xml_outfile1_test_', gtest_main)
  GtestTest(env, 'gtest_xml_outfile2_test_', gtest_main)
  GtestTest(env, 'gtest_xml_output_unittest_', gtest)
  GtestTest(env, 'gtest-unittest-api_test', gtest)
  GtestTest(env, 'gtest-listener_test', gtest)
  GtestTest(env, 'gtest_shuffle_test_', gtest)

  ############################################################
  # Tests targets using custom environments.
  GtestTest(env_warning_ok, 'gtest_unittest', gtest_main)
285
286
  GtestTest(env_with_exceptions_and_threads, 'gtest_output_test_',
            gtest_ex_with_threads)
287
  GtestTest(env_with_exceptions, 'gtest_throw_on_failure_ex_test', gtest_ex)
288
289
290
  GtestTest(env_with_threads, 'gtest-death-test_test', gtest_main_with_threads)
  GtestTest(env_with_threads, 'gtest-port_test', gtest_main_with_threads)
  GtestTest(env_with_threads, 'gtest_stress_test', gtest_with_threads)
291
292
  GtestTest(env_less_optimized, 'gtest_env_var_test_', gtest)
  GtestTest(env_less_optimized, 'gtest_uninitialized_test_', gtest)
293
  GtestTest(env_use_own_tuple, 'gtest-tuple_test', gtest_main_use_own_tuple)
294
295
  GtestBinary(env_use_own_tuple,
              'gtest_use_own_tuple_test',
296
              gtest_main_use_own_tuple,
297
298
299
300
301
302
              ['../test/gtest-param-test_test.cc',
               '../test/gtest-param-test2_test.cc'])
  GtestBinary(env_with_exceptions, 'gtest_ex_unittest', gtest_main_ex,
              ['../test/gtest_unittest.cc'])
  GtestBinary(env_without_rtti, 'gtest_no_rtti_test', gtest_main_no_rtti,
              ['../test/gtest_unittest.cc'])
303

304
305
306
307
308
309
  # Tests that gtest works when built as a DLL on Windows.
  # We don't need to actually run this test.
  # Note: this is not supported under VC 7.1.
  if env['PLATFORM'] == 'win32' and env.get('GTEST_BUILD_DLL_TEST', None):
    test_env = EnvCreator.Create(env, EnvCreator.DllBuild)
    dll_env = test_env.Clone()
310
    dll_env.Append(LINKFLAGS=['-DEF:../msvc/gtest.def'])
311
312
313
314
315
316
317
318
319
320
321
322

    gtest_dll = dll_env.SharedLibrary(
                    target='gtest_dll',
                    source=[dll_env.SharedObject('gtest_all_dll',
                                                 '../src/gtest-all.cc'),
                            dll_env.SharedObject('gtest_main_dll',
                                                 '../src/gtest_main.cc')])
    # TODO(vladl@google.com): Get rid of the .data[1] hack. Find a proper
    # way to depend on a shared library without knowing its path in advance.
    test_env.Program('gtest_dll_test_',
                     ['../test/gtest_dll_test_.cc', gtest_dll.data[1]])

323
324
############################################################
# Sample targets.
325
326
327
328

# Use the GTEST_BUILD_SAMPLES build variable to control building of samples.
# In your SConstruct file, add
#   vars = Variables()
329
#   vars.Add(BoolVariable('GTEST_BUILD_SAMPLES', 'Build samples', False))
330
331
332
#   my_environment = Environment(variables = vars, ...)
# Then, in the command line use GTEST_BUILD_SAMPLES=true to enable them.
if env.get('GTEST_BUILD_SAMPLES', False):
333
334
  GtestSample(env, 'sample1_unittest',
              additional_sources=['../samples/sample1.cc'])
335
  GtestSample(env, 'sample2_unittest',
336
              additional_sources=['../samples/sample2.cc'])
337
338
  GtestSample(env, 'sample3_unittest')
  GtestSample(env, 'sample4_unittest',
339
              additional_sources=['../samples/sample4.cc'])
340
341
  GtestSample(env, 'sample5_unittest',
              additional_sources=['../samples/sample1.cc'])
342
343
344
  GtestSample(env, 'sample6_unittest')
  GtestSample(env, 'sample7_unittest')
  GtestSample(env, 'sample8_unittest')
345
346
  GtestSample(env, 'sample9_unittest')
  GtestSample(env, 'sample10_unittest')
347
348

gtest_exports = {'gtest': gtest,
349
                 'gtest_main': gtest_main,
350
351
352
353
354
355
                 'gtest_ex': gtest_ex,
                 'gtest_main_ex': gtest_main_ex,
                 'gtest_no_rtti': gtest_no_rtti,
                 'gtest_main_no_rtti': gtest_main_no_rtti,
                 'gtest_use_own_tuple': gtest_use_own_tuple,
                 'gtest_main_use_own_tuple': gtest_main_use_own_tuple,
356
                 # These exports are used by Google Mock.
357
358
359
                 'GtestObject': GtestObject,
                 'GtestBinary': GtestBinary,
                 'GtestTest': GtestTest}
360

361
362
# Makes the gtest_exports dictionary available to the invoking SConstruct.
Return('gtest_exports')