Remove most of base/test Change-Id: I19119b5cb23a293f80719ca92c980196671aa50f Reviewed-on: https://gn-review.googlesource.com/1424 Reviewed-by: Brett Wilson <brettw@chromium.org> Commit-Queue: Scott Graham <scottmg@chromium.org>
diff --git a/base/test/DEPS b/base/test/DEPS deleted file mode 100644 index 5827c26..0000000 --- a/base/test/DEPS +++ /dev/null
@@ -1,3 +0,0 @@ -include_rules = [ - "+third_party/libxml", -]
diff --git a/base/test/OWNERS b/base/test/OWNERS deleted file mode 100644 index 6807748..0000000 --- a/base/test/OWNERS +++ /dev/null
@@ -1,16 +0,0 @@ -per-file *task_scheduler*=file://base/task_scheduler/OWNERS - -# Metrics-related test utilites: -per-file *histogram_tester*=file://base/metrics/OWNERS -per-file *scoped_feature_list*=file://base/metrics/OWNERS -per-file *user_action_tester*=file://base/metrics/OWNERS - -# Tracing test utilities: -per-file trace_*=file://base/trace_event/OWNERS - -# For Android-specific changes: -per-file *android*=file://base/test/android/OWNERS -per-file BUILD.gn=file://base/test/android/OWNERS - -# Linux fontconfig changes -per-file *fontconfig*=file://base/nix/OWNERS
diff --git a/base/test/bind_test_util.h b/base/test/bind_test_util.h deleted file mode 100644 index 0dfcb46..0000000 --- a/base/test/bind_test_util.h +++ /dev/null
@@ -1,36 +0,0 @@ -// Copyright 2017 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef BASE_TEST_BIND_TEST_UTIL_H_ -#define BASE_TEST_BIND_TEST_UTIL_H_ - -#include "base/bind.h" - -namespace base { -namespace internal { - -template <typename F, typename Signature> -struct BindLambdaHelper; - -template <typename F, typename R, typename... Args> -struct BindLambdaHelper<F, R(Args...)> { - static R Run(const std::decay_t<F>& f, Args... args) { - return f(std::forward<Args>(args)...); - } -}; - -} // namespace internal - -// A variant of Bind() that can bind capturing lambdas for testing. -// This doesn't support extra arguments binding as the lambda itself can do. -template <typename F> -decltype(auto) BindLambdaForTesting(F&& f) { - using Signature = internal::ExtractCallableRunType<std::decay_t<F>>; - return BindRepeating(&internal::BindLambdaHelper<F, Signature>::Run, - std::forward<F>(f)); -} - -} // namespace base - -#endif // BASE_TEST_BIND_TEST_UTIL_H_
diff --git a/base/test/copy_only_int.h b/base/test/copy_only_int.h deleted file mode 100644 index 4e482c9..0000000 --- a/base/test/copy_only_int.h +++ /dev/null
@@ -1,55 +0,0 @@ -// Copyright 2017 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef BASE_TEST_COPY_ONLY_INT_H_ -#define BASE_TEST_COPY_ONLY_INT_H_ - -#include "base/macros.h" - -namespace base { - -// A copy-only (not moveable) class that holds an integer. This is designed for -// testing containers. See also MoveOnlyInt. -class CopyOnlyInt { - public: - explicit CopyOnlyInt(int data = 1) : data_(data) {} - CopyOnlyInt(const CopyOnlyInt& other) = default; - ~CopyOnlyInt() { data_ = 0; } - - friend bool operator==(const CopyOnlyInt& lhs, const CopyOnlyInt& rhs) { - return lhs.data_ == rhs.data_; - } - - friend bool operator!=(const CopyOnlyInt& lhs, const CopyOnlyInt& rhs) { - return !operator==(lhs, rhs); - } - - friend bool operator<(const CopyOnlyInt& lhs, const CopyOnlyInt& rhs) { - return lhs.data_ < rhs.data_; - } - - friend bool operator>(const CopyOnlyInt& lhs, const CopyOnlyInt& rhs) { - return rhs < lhs; - } - - friend bool operator<=(const CopyOnlyInt& lhs, const CopyOnlyInt& rhs) { - return !(rhs < lhs); - } - - friend bool operator>=(const CopyOnlyInt& lhs, const CopyOnlyInt& rhs) { - return !(lhs < rhs); - } - - int data() const { return data_; } - - private: - volatile int data_; - - CopyOnlyInt(CopyOnlyInt&&) = delete; - CopyOnlyInt& operator=(CopyOnlyInt&) = delete; -}; - -} // namespace base - -#endif // BASE_TEST_COPY_ONLY_INT_H_
diff --git a/base/test/data/file_util/binary_file.bin b/base/test/data/file_util/binary_file.bin deleted file mode 100644 index f53cc82..0000000 --- a/base/test/data/file_util/binary_file.bin +++ /dev/null Binary files differ
diff --git a/base/test/data/file_util/binary_file_diff.bin b/base/test/data/file_util/binary_file_diff.bin deleted file mode 100644 index 103b26d..0000000 --- a/base/test/data/file_util/binary_file_diff.bin +++ /dev/null Binary files differ
diff --git a/base/test/data/file_util/binary_file_same.bin b/base/test/data/file_util/binary_file_same.bin deleted file mode 100644 index f53cc82..0000000 --- a/base/test/data/file_util/binary_file_same.bin +++ /dev/null Binary files differ
diff --git a/base/test/data/file_util/blank_line.txt b/base/test/data/file_util/blank_line.txt deleted file mode 100644 index 8892069..0000000 --- a/base/test/data/file_util/blank_line.txt +++ /dev/null
@@ -1,3 +0,0 @@ -The next line is blank. - -But this one isn't.
diff --git a/base/test/data/file_util/blank_line_crlf.txt b/base/test/data/file_util/blank_line_crlf.txt deleted file mode 100644 index 3aefe52..0000000 --- a/base/test/data/file_util/blank_line_crlf.txt +++ /dev/null
@@ -1,3 +0,0 @@ -The next line is blank. - -But this one isn't.
diff --git a/base/test/data/file_util/crlf.txt b/base/test/data/file_util/crlf.txt deleted file mode 100644 index 0e62728..0000000 --- a/base/test/data/file_util/crlf.txt +++ /dev/null
@@ -1 +0,0 @@ -This file is the same.
diff --git a/base/test/data/file_util/different.txt b/base/test/data/file_util/different.txt deleted file mode 100644 index 5b9f9c4..0000000 --- a/base/test/data/file_util/different.txt +++ /dev/null
@@ -1 +0,0 @@ -This file is different.
diff --git a/base/test/data/file_util/different_first.txt b/base/test/data/file_util/different_first.txt deleted file mode 100644 index 8661d66..0000000 --- a/base/test/data/file_util/different_first.txt +++ /dev/null
@@ -1 +0,0 @@ -this file is the same.
diff --git a/base/test/data/file_util/different_last.txt b/base/test/data/file_util/different_last.txt deleted file mode 100644 index e8b3e5a..0000000 --- a/base/test/data/file_util/different_last.txt +++ /dev/null
@@ -1 +0,0 @@ -This file is the same. \ No newline at end of file
diff --git a/base/test/data/file_util/empty1.txt b/base/test/data/file_util/empty1.txt deleted file mode 100644 index e69de29..0000000 --- a/base/test/data/file_util/empty1.txt +++ /dev/null
diff --git a/base/test/data/file_util/empty2.txt b/base/test/data/file_util/empty2.txt deleted file mode 100644 index e69de29..0000000 --- a/base/test/data/file_util/empty2.txt +++ /dev/null
diff --git a/base/test/data/file_util/first1.txt b/base/test/data/file_util/first1.txt deleted file mode 100644 index 2c6e300..0000000 --- a/base/test/data/file_util/first1.txt +++ /dev/null
@@ -1,2 +0,0 @@ -The first line is the same. -The second line is different.
diff --git a/base/test/data/file_util/first2.txt b/base/test/data/file_util/first2.txt deleted file mode 100644 index e39b5ec..0000000 --- a/base/test/data/file_util/first2.txt +++ /dev/null
@@ -1,2 +0,0 @@ -The first line is the same. -The second line is not.
diff --git a/base/test/data/file_util/original.txt b/base/test/data/file_util/original.txt deleted file mode 100644 index 4422f57..0000000 --- a/base/test/data/file_util/original.txt +++ /dev/null
@@ -1 +0,0 @@ -This file is the same.
diff --git a/base/test/data/file_util/red.png b/base/test/data/file_util/red.png deleted file mode 100644 index 0806141..0000000 --- a/base/test/data/file_util/red.png +++ /dev/null Binary files differ
diff --git a/base/test/data/file_util/same.txt b/base/test/data/file_util/same.txt deleted file mode 100644 index 4422f57..0000000 --- a/base/test/data/file_util/same.txt +++ /dev/null
@@ -1 +0,0 @@ -This file is the same.
diff --git a/base/test/data/file_util/same_length.txt b/base/test/data/file_util/same_length.txt deleted file mode 100644 index 157405c..0000000 --- a/base/test/data/file_util/same_length.txt +++ /dev/null
@@ -1 +0,0 @@ -This file is not same.
diff --git a/base/test/data/file_util/shortened.txt b/base/test/data/file_util/shortened.txt deleted file mode 100644 index 2bee82c..0000000 --- a/base/test/data/file_util/shortened.txt +++ /dev/null
@@ -1 +0,0 @@ -This file is the \ No newline at end of file
diff --git a/base/test/data/file_version_info_unittest/FileVersionInfoTest1.dll b/base/test/data/file_version_info_unittest/FileVersionInfoTest1.dll deleted file mode 100755 index bdf8dc0..0000000 --- a/base/test/data/file_version_info_unittest/FileVersionInfoTest1.dll +++ /dev/null Binary files differ
diff --git a/base/test/data/file_version_info_unittest/FileVersionInfoTest2.dll b/base/test/data/file_version_info_unittest/FileVersionInfoTest2.dll deleted file mode 100755 index 51e7966..0000000 --- a/base/test/data/file_version_info_unittest/FileVersionInfoTest2.dll +++ /dev/null Binary files differ
diff --git a/base/test/data/json/bom_feff.json b/base/test/data/json/bom_feff.json deleted file mode 100644 index b05ae50..0000000 --- a/base/test/data/json/bom_feff.json +++ /dev/null
@@ -1,10 +0,0 @@ -{ - "appName": { - "message": "Gmail", - "description": "App name." - }, - "appDesc": { - "message": "بريد إلكتروني يوفر إمكانية البحث مع مقدار أقل من الرسائل غير المرغوب فيها.", - "description":"App description." - } -} \ No newline at end of file
diff --git a/base/test/data/pe_image/pe_image_test_32.dll b/base/test/data/pe_image/pe_image_test_32.dll deleted file mode 100755 index 539d631..0000000 --- a/base/test/data/pe_image/pe_image_test_32.dll +++ /dev/null Binary files differ
diff --git a/base/test/data/pe_image/pe_image_test_64.dll b/base/test/data/pe_image/pe_image_test_64.dll deleted file mode 100755 index 8801e23..0000000 --- a/base/test/data/pe_image/pe_image_test_64.dll +++ /dev/null Binary files differ
diff --git a/base/test/data/serializer_nested_test.json b/base/test/data/serializer_nested_test.json deleted file mode 100644 index cfea8e8..0000000 --- a/base/test/data/serializer_nested_test.json +++ /dev/null
@@ -1,17 +0,0 @@ -{ - "bool": true, - "dict": { - "bool": true, - "dict": { - "bees": "knees", - "cats": "meow" - }, - "foos": "bar", - "list": [ 3.4, "second", null ] - }, - "int": 42, - "list": [ 1, 2 ], - "null": null, - "real": 3.14, - "string": "hello" -}
diff --git a/base/test/data/serializer_test.json b/base/test/data/serializer_test.json deleted file mode 100644 index 446925e..0000000 --- a/base/test/data/serializer_test.json +++ /dev/null
@@ -1,8 +0,0 @@ -{ - "bool": true, - "int": 42, - "list": [ 1, 2 ], - "null": null, - "real": 3.14, - "string": "hello" -}
diff --git a/base/test/data/serializer_test_nowhitespace.json b/base/test/data/serializer_test_nowhitespace.json deleted file mode 100644 index a1afdc5..0000000 --- a/base/test/data/serializer_test_nowhitespace.json +++ /dev/null
@@ -1 +0,0 @@ -{"bool":true,"int":42,"list":[1,2],"null":null,"real":3.14,"string":"hello"} \ No newline at end of file
diff --git a/base/test/fontconfig_util_linux.cc b/base/test/fontconfig_util_linux.cc deleted file mode 100644 index 8bd7c92..0000000 --- a/base/test/fontconfig_util_linux.cc +++ /dev/null
@@ -1,496 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "base/test/fontconfig_util_linux.h" - -#include <fontconfig/fontconfig.h> - -#include "base/base_paths.h" -#include "base/files/file_path.h" -#include "base/files/file_util.h" -#include "base/logging.h" -#include "base/macros.h" -#include "base/path_service.h" -#include "base/strings/string_util.h" -#include "base/strings/stringprintf.h" - -namespace base { - -namespace { - -const char kFontsConfTemplate[] = R"(<?xml version="1.0"?> -<!DOCTYPE fontconfig SYSTEM "fonts.dtd"> -<fontconfig> - - <!-- Cache location. --> - <cachedir>$1</cachedir> - - <!-- GCS-synced fonts. --> - <dir>$2</dir> - - <!-- Default properties. --> - <match target="font"> - <edit name="embeddedbitmap" mode="append_last"> - <bool>false</bool> - </edit> - </match> - - <!-- TODO(thomasanderson): Figure out why this is necessary. --> - <match target="pattern"> - <test name="family" compare="eq"> - <string>Tinos</string> - </test> - <test name="prgname" compare="eq"> - <string>chromevox_tests</string> - </test> - <edit name="hintstyle" mode="assign"> - <const>hintslight</const> - </edit> - </match> - - <match target="pattern"> - <test qual="any" name="family"> - <string>Times</string> - </test> - <edit name="family" mode="assign"> - <string>Tinos</string> - </edit> - </match> - - <match target="pattern"> - <test qual="any" name="family"> - <string>sans</string> - </test> - <edit name="family" mode="assign"> - <string>DejaVu Sans</string> - </edit> - </match> - - <match target="pattern"> - <test qual="any" name="family"> - <string>sans serif</string> - </test> - <edit name="family" mode="assign"> - <string>Arimo</string> - </edit> - </match> - - <!-- Some layout tests specify Helvetica as a family and we need to make sure - that we don't fallback to Tinos for them --> - <match target="pattern"> - <test qual="any" name="family"> - <string>Helvetica</string> - </test> - <edit name="family" mode="assign"> - <string>Arimo</string> - </edit> - </match> - - <match target="pattern"> - <test qual="any" name="family"> - <string>sans-serif</string> - </test> - <edit name="family" mode="assign"> - <string>Arimo</string> - </edit> - </match> - - <match target="pattern"> - <test qual="any" name="family"> - <string>serif</string> - </test> - <edit name="family" mode="assign"> - <string>Tinos</string> - </edit> - </match> - - <match target="pattern"> - <test qual="any" name="family"> - <string>mono</string> - </test> - <edit name="family" mode="assign"> - <string>Cousine</string> - </edit> - </match> - - <match target="pattern"> - <test qual="any" name="family"> - <string>monospace</string> - </test> - <edit name="family" mode="assign"> - <string>Cousine</string> - </edit> - </match> - - <match target="pattern"> - <test qual="any" name="family"> - <string>Courier</string> - </test> - <edit name="family" mode="assign"> - <string>Cousine</string> - </edit> - </match> - - <match target="pattern"> - <test qual="any" name="family"> - <string>cursive</string> - </test> - <edit name="family" mode="assign"> - <string>Comic Sans MS</string> - </edit> - </match> - - <match target="pattern"> - <test qual="any" name="family"> - <string>fantasy</string> - </test> - <edit name="family" mode="assign"> - <string>Impact</string> - </edit> - </match> - - <match target="pattern"> - <test qual="any" name="family"> - <string>Monaco</string> - </test> - <edit name="family" mode="assign"> - <string>Tinos</string> - </edit> - </match> - - <match target="pattern"> - <test qual="any" name="family"> - <string>Arial</string> - </test> - <edit name="family" mode="assign"> - <string>Arimo</string> - </edit> - </match> - - <match target="pattern"> - <test qual="any" name="family"> - <string>Courier New</string> - </test> - <edit name="family" mode="assign"> - <string>Cousine</string> - </edit> - </match> - - <match target="pattern"> - <test qual="any" name="family"> - <string>Georgia</string> - </test> - <edit name="family" mode="assign"> - <string>Gelasio</string> - </edit> - </match> - - <match target="pattern"> - <test qual="any" name="family"> - <string>Times New Roman</string> - </test> - <edit name="family" mode="assign"> - <string>Tinos</string> - </edit> - </match> - - <match target="pattern"> - <test qual="any" name="family"> - <string>Verdana</string> - </test> - <!-- NOT metrically compatible! --> - <edit name="family" mode="assign"> - <string>Arimo</string> - </edit> - </match> - - <!-- TODO(thomasanderson): Move these configs to be test-specific. --> - <match target="pattern"> - <test name="family" compare="eq"> - <string>NonAntiAliasedSans</string> - </test> - <edit name="family" mode="assign"> - <string>Arimo</string> - </edit> - <edit name="antialias" mode="assign"> - <bool>false</bool> - </edit> - </match> - - <match target="pattern"> - <test name="family" compare="eq"> - <string>SlightHintedGeorgia</string> - </test> - <edit name="family" mode="assign"> - <string>Gelasio</string> - </edit> - <edit name="hintstyle" mode="assign"> - <const>hintslight</const> - </edit> - </match> - - <match target="pattern"> - <test name="family" compare="eq"> - <string>NonHintedSans</string> - </test> - <edit name="family" mode="assign"> - <string>Arimo</string> - </edit> - <!-- These deliberately contradict each other. The 'hinting' preference - should take priority --> - <edit name="hintstyle" mode="assign"> - <const>hintfull</const> - </edit> - <edit name="hinting" mode="assign"> - <bool>false</bool> - </edit> - </match> - - <match target="pattern"> - <test name="family" compare="eq"> - <string>AutohintedSerif</string> - </test> - <edit name="family" mode="assign"> - <string>Arimo</string> - </edit> - <edit name="autohint" mode="assign"> - <bool>true</bool> - </edit> - <edit name="hintstyle" mode="assign"> - <const>hintmedium</const> - </edit> - </match> - - <match target="pattern"> - <test name="family" compare="eq"> - <string>HintedSerif</string> - </test> - <edit name="family" mode="assign"> - <string>Arimo</string> - </edit> - <edit name="autohint" mode="assign"> - <bool>false</bool> - </edit> - <edit name="hintstyle" mode="assign"> - <const>hintmedium</const> - </edit> - </match> - - <match target="pattern"> - <test name="family" compare="eq"> - <string>FullAndAutoHintedSerif</string> - </test> - <edit name="family" mode="assign"> - <string>Arimo</string> - </edit> - <edit name="autohint" mode="assign"> - <bool>true</bool> - </edit> - <edit name="hintstyle" mode="assign"> - <const>hintfull</const> - </edit> - </match> - - <match target="pattern"> - <test name="family" compare="eq"> - <string>SubpixelEnabledArial</string> - </test> - <edit name="family" mode="assign"> - <string>Arimo</string> - </edit> - <edit name="rgba" mode="assign"> - <const>rgb</const> - </edit> - </match> - - <match target="pattern"> - <test name="family" compare="eq"> - <string>SubpixelDisabledArial</string> - </test> - <edit name="family" mode="assign"> - <string>Arimo</string> - </edit> - <edit name="rgba" mode="assign"> - <const>none</const> - </edit> - </match> - - <match target="pattern"> - <!-- FontConfig doesn't currently provide a well-defined way to turn on - subpixel positioning. This is just an arbitrary pattern to use after - turning subpixel positioning on globally to ensure that we don't have - issues with our style getting cached for other tests. --> - <test name="family" compare="eq"> - <string>SubpixelPositioning</string> - </test> - <edit name="family" mode="assign"> - <string>Tinos</string> - </edit> - </match> - - <match target="pattern"> - <!-- See comments above --> - <test name="family" compare="eq"> - <string>SubpixelPositioningAhem</string> - </test> - <edit name="family" mode="assign"> - <string>ahem</string> - </edit> - </match> - - <match target="pattern"> - <test name="family" compare="eq"> - <string>SlightHintedTimesNewRoman</string> - </test> - <edit name="family" mode="assign"> - <string>Tinos</string> - </edit> - <edit name="hintstyle" mode="assign"> - <const>hintslight</const> - </edit> - </match> - - <!-- When we encounter a character that the current font doesn't - support, gfx::GetFallbackFontForChar() returns the first font - that does have a glyph for the character. The list of fonts is - sorted by a pattern that includes the current locale, but doesn't - include a font family (which means that the fallback font depends - on the locale but not on the current font). - - DejaVu Sans is commonly the only font that supports some - characters, such as "⇧", and even when other candidates are - available, DejaVu Sans is commonly first among them, because of - the way Fontconfig is ordinarily configured. For example, the - configuration in the Fonconfig source lists DejaVu Sans under the - sans-serif generic family, and appends sans-serif to patterns - that don't already include a generic family (such as the pattern - in gfx::GetFallbackFontForChar()). - - To get the same fallback font in the layout tests, we could - duplicate this configuration here, or more directly, simply - append DejaVu Sans to all patterns. --> - <match target="pattern"> - <edit name="family" mode="append_last"> - <string>DejaVu Sans</string> - </edit> - </match> - -</fontconfig> -)"; - -} // namespace - -void SetUpFontconfig() { - FilePath dir_module; - PathService::Get(DIR_MODULE, &dir_module); - FilePath font_cache = dir_module.Append("fontconfig_caches"); - FilePath test_fonts = dir_module.Append("test_fonts"); - std::string fonts_conf = ReplaceStringPlaceholders( - kFontsConfTemplate, {font_cache.value(), test_fonts.value()}, nullptr); - - FcConfig* config = FcConfigCreate(); - CHECK(config); -#if FC_VERSION >= 21205 - CHECK(FcConfigParseAndLoadFromMemory( - config, reinterpret_cast<const FcChar8*>(fonts_conf.c_str()), FcTrue)); -#else - FilePath temp; - CHECK(CreateTemporaryFile(&temp)); - CHECK(WriteFile(temp, fonts_conf.c_str(), fonts_conf.size())); - CHECK(FcConfigParseAndLoad( - config, reinterpret_cast<const FcChar8*>(temp.value().c_str()), FcTrue)); - CHECK(DeleteFile(temp, false)); -#endif - CHECK(FcConfigBuildFonts(config)); - CHECK(FcConfigSetCurrent(config)); - - // Decrement the reference count for |config|. It's now owned by fontconfig. - FcConfigDestroy(config); -} - -void TearDownFontconfig() { - FcFini(); -} - -bool LoadFontIntoFontconfig(const FilePath& path) { - if (!PathExists(path)) { - LOG(ERROR) << "You are missing " << path.value() << ". Try re-running " - << "build/install-build-deps.sh. " - << "Please make sure that " - << "third_party/test_fonts/ has downloaded " - << "and extracted the test_fonts." - << "Also see " - << "https://chromium.googlesource.com/chromium/src/+/master/" - << "docs/layout_tests_linux.md"; - return false; - } - - if (!FcConfigAppFontAddFile( - NULL, reinterpret_cast<const FcChar8*>(path.value().c_str()))) { - LOG(ERROR) << "Failed to load font " << path.value(); - return false; - } - - return true; -} - -bool LoadConfigFileIntoFontconfig(const FilePath& path) { - // Unlike other FcConfig functions, FcConfigParseAndLoad() doesn't default to - // the current config when passed NULL. So that's cool. - if (!FcConfigParseAndLoad( - FcConfigGetCurrent(), - reinterpret_cast<const FcChar8*>(path.value().c_str()), FcTrue)) { - LOG(ERROR) << "Fontconfig failed to load " << path.value(); - return false; - } - return true; -} - -bool LoadConfigDataIntoFontconfig(const FilePath& temp_dir, - const std::string& data) { - FilePath path; - if (!CreateTemporaryFileInDir(temp_dir, &path)) { - PLOG(ERROR) << "Unable to create temporary file in " << temp_dir.value(); - return false; - } - if (WriteFile(path, data.data(), data.size()) != - static_cast<int>(data.size())) { - PLOG(ERROR) << "Unable to write config data to " << path.value(); - return false; - } - return LoadConfigFileIntoFontconfig(path); -} - -std::string CreateFontconfigEditStanza(const std::string& name, - const std::string& type, - const std::string& value) { - return StringPrintf( - " <edit name=\"%s\" mode=\"assign\">\n" - " <%s>%s</%s>\n" - " </edit>\n", - name.c_str(), type.c_str(), value.c_str(), type.c_str()); -} - -std::string CreateFontconfigTestStanza(const std::string& name, - const std::string& op, - const std::string& type, - const std::string& value) { - return StringPrintf( - " <test name=\"%s\" compare=\"%s\" qual=\"any\">\n" - " <%s>%s</%s>\n" - " </test>\n", - name.c_str(), op.c_str(), type.c_str(), value.c_str(), type.c_str()); -} - -std::string CreateFontconfigAliasStanza(const std::string& original_family, - const std::string& preferred_family) { - return StringPrintf( - " <alias>\n" - " <family>%s</family>\n" - " <prefer><family>%s</family></prefer>\n" - " </alias>\n", - original_family.c_str(), preferred_family.c_str()); -} - -} // namespace base
diff --git a/base/test/fontconfig_util_linux.h b/base/test/fontconfig_util_linux.h deleted file mode 100644 index ac7037a..0000000 --- a/base/test/fontconfig_util_linux.h +++ /dev/null
@@ -1,51 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef BASE_TEST_FONTCONFIG_UTIL_LINUX_H_ -#define BASE_TEST_FONTCONFIG_UTIL_LINUX_H_ - -#include <stddef.h> - -#include <string> - -namespace base { -class FilePath; - -// Initializes Fontconfig with a custom configuration suitable for tests. -void SetUpFontconfig(); - -// Deinitializes Fontconfig. -void TearDownFontconfig(); - -// Loads the font file at |path| into the current config, returning true on -// success. -bool LoadFontIntoFontconfig(const FilePath& path); - -// Instructs Fontconfig to load |path|, an XML configuration file, into the -// current config, returning true on success. -bool LoadConfigFileIntoFontconfig(const FilePath& path); - -// Writes |data| to a file in |temp_dir| and passes it to -// LoadConfigFileIntoFontconfig(). -bool LoadConfigDataIntoFontconfig(const FilePath& temp_dir, - const std::string& data); - -// Returns a Fontconfig <edit> stanza. -std::string CreateFontconfigEditStanza(const std::string& name, - const std::string& type, - const std::string& value); - -// Returns a Fontconfig <test> stanza. -std::string CreateFontconfigTestStanza(const std::string& name, - const std::string& op, - const std::string& type, - const std::string& value); - -// Returns a Fontconfig <alias> stanza. -std::string CreateFontconfigAliasStanza(const std::string& original_family, - const std::string& preferred_family); - -} // namespace base - -#endif // BASE_TEST_FONTCONFIG_UTIL_LINUX_H_
diff --git a/base/test/fuzzed_data_provider.cc b/base/test/fuzzed_data_provider.cc deleted file mode 100644 index b2d443a..0000000 --- a/base/test/fuzzed_data_provider.cc +++ /dev/null
@@ -1,98 +0,0 @@ -// Copyright 2016 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "base/test/fuzzed_data_provider.h" - -#include <algorithm> -#include <limits> - -#include "base/logging.h" - -namespace base { - -FuzzedDataProvider::FuzzedDataProvider(const uint8_t* data, size_t size) - : remaining_data_(reinterpret_cast<const char*>(data), size) {} - -FuzzedDataProvider::~FuzzedDataProvider() = default; - -std::string FuzzedDataProvider::ConsumeBytes(size_t num_bytes) { - num_bytes = std::min(num_bytes, remaining_data_.length()); - StringPiece result(remaining_data_.data(), num_bytes); - remaining_data_ = remaining_data_.substr(num_bytes); - return result.as_string(); -} - -std::string FuzzedDataProvider::ConsumeRemainingBytes() { - return ConsumeBytes(remaining_data_.length()); -} - -uint32_t FuzzedDataProvider::ConsumeUint32InRange(uint32_t min, uint32_t max) { - CHECK_LE(min, max); - - uint32_t range = max - min; - uint32_t offset = 0; - uint32_t result = 0; - - while (offset < 32 && (range >> offset) > 0 && !remaining_data_.empty()) { - // Pull bytes off the end of the seed data. Experimentally, this seems to - // allow the fuzzer to more easily explore the input space. This makes - // sense, since it works by modifying inputs that caused new code to run, - // and this data is often used to encode length of data read by - // ConsumeBytes. Separating out read lengths makes it easier modify the - // contents of the data that is actually read. - uint8_t next_byte = remaining_data_.back(); - remaining_data_.remove_suffix(1); - result = (result << 8) | next_byte; - offset += 8; - } - - // Avoid division by 0, in the case |range + 1| results in overflow. - if (range == std::numeric_limits<uint32_t>::max()) - return result; - - return min + result % (range + 1); -} - -std::string FuzzedDataProvider::ConsumeRandomLengthString(size_t max_length) { - // Reads bytes from start of |remaining_data_|. Maps "\\" to "\", and maps "\" - // followed by anything else to the end of the string. As a result of this - // logic, a fuzzer can insert characters into the string, and the string will - // be lengthened to include those new characters, resulting in a more stable - // fuzzer than picking the length of a string independently from picking its - // contents. - std::string out; - for (size_t i = 0; i < max_length && !remaining_data_.empty(); ++i) { - char next = remaining_data_[0]; - remaining_data_.remove_prefix(1); - if (next == '\\' && !remaining_data_.empty()) { - next = remaining_data_[0]; - remaining_data_.remove_prefix(1); - if (next != '\\') - return out; - } - out += next; - } - return out; -} - -int FuzzedDataProvider::ConsumeInt32InRange(int min, int max) { - CHECK_LE(min, max); - - uint32_t range = max - min; - return min + ConsumeUint32InRange(0, range); -} - -bool FuzzedDataProvider::ConsumeBool() { - return (ConsumeUint8() & 0x01) == 0x01; -} - -uint8_t FuzzedDataProvider::ConsumeUint8() { - return ConsumeUint32InRange(0, 0xFF); -} - -uint16_t FuzzedDataProvider::ConsumeUint16() { - return ConsumeUint32InRange(0, 0xFFFF); -} - -} // namespace base
diff --git a/base/test/fuzzed_data_provider.h b/base/test/fuzzed_data_provider.h deleted file mode 100644 index 425c820..0000000 --- a/base/test/fuzzed_data_provider.h +++ /dev/null
@@ -1,80 +0,0 @@ -// Copyright 2016 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef BASE_TEST_FUZZED_DATA_PROVIDER_H_ -#define BASE_TEST_FUZZED_DATA_PROVIDER_H_ - -#include <stdint.h> - -#include <string> - -#include "base/base_export.h" -#include "base/macros.h" -#include "base/strings/string_piece.h" - -namespace base { - -// Utility class to break up fuzzer input for multiple consumers. Whenever run -// on the same input, provides the same output, as long as its methods are -// called in the same order, with the same arguments. -class FuzzedDataProvider { - public: - // |data| is an array of length |size| that the FuzzedDataProvider wraps to - // provide more granular access. |data| must outlive the FuzzedDataProvider. - FuzzedDataProvider(const uint8_t* data, size_t size); - ~FuzzedDataProvider(); - - // Returns a std::string containing |num_bytes| of input data. If fewer than - // |num_bytes| of data remain, returns a shorter std::string containing all - // of the data that's left. - std::string ConsumeBytes(size_t num_bytes); - - // Returns a std::string containing all remaining bytes of the input data. - std::string ConsumeRemainingBytes(); - - // Returns a std::string of length from 0 to |max_length|. When it runs out of - // input data, returns what remains of the input. Designed to be more stable - // with respect to a fuzzer inserting characters than just picking a random - // length and then consuming that many bytes with ConsumeBytes(). - std::string ConsumeRandomLengthString(size_t max_length); - - // Returns a number in the range [min, max] by consuming bytes from the input - // data. The value might not be uniformly distributed in the given range. If - // there's no input data left, always returns |min|. |min| must be less than - // or equal to |max|. - uint32_t ConsumeUint32InRange(uint32_t min, uint32_t max); - int ConsumeInt32InRange(int min, int max); - - // Returns a bool, or false when no data remains. - bool ConsumeBool(); - - // Returns a uint8_t from the input or 0 if nothing remains. This is - // equivalent to ConsumeUint32InRange(0, 0xFF). - uint8_t ConsumeUint8(); - - // Returns a uint16_t from the input. If fewer than 2 bytes of data remain - // will fill the most significant bytes with 0. This is equivalent to - // ConsumeUint32InRange(0, 0xFFFF). - uint16_t ConsumeUint16(); - - // Returns a value from |array|, consuming as many bytes as needed to do so. - // |array| must be a fixed-size array. Equivalent to - // array[ConsumeUint32InRange(sizeof(array)-1)]; - template <typename Type, size_t size> - Type PickValueInArray(Type (&array)[size]) { - return array[ConsumeUint32InRange(0, size - 1)]; - } - - // Reports the remaining bytes available for fuzzed input. - size_t remaining_bytes() { return remaining_data_.length(); } - - private: - StringPiece remaining_data_; - - DISALLOW_COPY_AND_ASSIGN(FuzzedDataProvider); -}; - -} // namespace base - -#endif // BASE_TEST_FUZZED_DATA_PROVIDER_H_
diff --git a/base/test/generate_fontconfig_caches.cc b/base/test/generate_fontconfig_caches.cc deleted file mode 100644 index f12eb48..0000000 --- a/base/test/generate_fontconfig_caches.cc +++ /dev/null
@@ -1,24 +0,0 @@ -// Copyright 2018 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include <string> - -#include "base/files/file_path.h" -#include "base/files/file_util.h" -#include "base/path_service.h" -#include "base/test/fontconfig_util_linux.h" - -int main(void) { - base::SetUpFontconfig(); - base::TearDownFontconfig(); - - base::FilePath dir_module; - CHECK(base::PathService::Get(base::DIR_MODULE, &dir_module)); - base::FilePath fontconfig_caches = dir_module.Append("fontconfig_caches"); - CHECK(base::DirectoryExists(fontconfig_caches)); - base::FilePath stamp = fontconfig_caches.Append("STAMP"); - CHECK_EQ(0, base::WriteFile(stamp, "", 0)); - - return 0; -}
diff --git a/base/test/gtest_util.cc b/base/test/gtest_util.cc deleted file mode 100644 index e5d38f4..0000000 --- a/base/test/gtest_util.cc +++ /dev/null
@@ -1,111 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "base/test/gtest_util.h" - -#include <stddef.h> - -#include <memory> - -#include "base/files/file_path.h" -#include "base/json/json_file_value_serializer.h" -#include "base/strings/string_util.h" -#include "base/values.h" -#include "testing/gtest/include/gtest/gtest.h" - -namespace base { - -TestIdentifier::TestIdentifier() = default; - -TestIdentifier::TestIdentifier(const TestIdentifier& other) = default; - -std::string FormatFullTestName(const std::string& test_case_name, - const std::string& test_name) { - return test_case_name + "." + test_name; -} - -std::string TestNameWithoutDisabledPrefix(const std::string& full_test_name) { - std::string test_name_no_disabled(full_test_name); - ReplaceSubstringsAfterOffset(&test_name_no_disabled, 0, "DISABLED_", ""); - return test_name_no_disabled; -} - -std::vector<TestIdentifier> GetCompiledInTests() { - testing::UnitTest* const unit_test = testing::UnitTest::GetInstance(); - - std::vector<TestIdentifier> tests; - for (int i = 0; i < unit_test->total_test_case_count(); ++i) { - const testing::TestCase* test_case = unit_test->GetTestCase(i); - for (int j = 0; j < test_case->total_test_count(); ++j) { - const testing::TestInfo* test_info = test_case->GetTestInfo(j); - TestIdentifier test_data; - test_data.test_case_name = test_case->name(); - test_data.test_name = test_info->name(); - test_data.file = test_info->file(); - test_data.line = test_info->line(); - tests.push_back(test_data); - } - } - return tests; -} - -bool WriteCompiledInTestsToFile(const FilePath& path) { - std::vector<TestIdentifier> tests(GetCompiledInTests()); - - ListValue root; - for (size_t i = 0; i < tests.size(); ++i) { - std::unique_ptr<DictionaryValue> test_info(new DictionaryValue); - test_info->SetString("test_case_name", tests[i].test_case_name); - test_info->SetString("test_name", tests[i].test_name); - test_info->SetString("file", tests[i].file); - test_info->SetInteger("line", tests[i].line); - root.Append(std::move(test_info)); - } - - JSONFileValueSerializer serializer(path); - return serializer.Serialize(root); -} - -bool ReadTestNamesFromFile(const FilePath& path, - std::vector<TestIdentifier>* output) { - JSONFileValueDeserializer deserializer(path); - int error_code = 0; - std::string error_message; - std::unique_ptr<base::Value> value = - deserializer.Deserialize(&error_code, &error_message); - if (!value.get()) - return false; - - base::ListValue* tests = nullptr; - if (!value->GetAsList(&tests)) - return false; - - std::vector<base::TestIdentifier> result; - for (base::ListValue::iterator i = tests->begin(); i != tests->end(); ++i) { - base::DictionaryValue* test = nullptr; - if (!i->GetAsDictionary(&test)) - return false; - - TestIdentifier test_data; - - if (!test->GetStringASCII("test_case_name", &test_data.test_case_name)) - return false; - - if (!test->GetStringASCII("test_name", &test_data.test_name)) - return false; - - if (!test->GetStringASCII("file", &test_data.file)) - return false; - - if (!test->GetInteger("line", &test_data.line)) - return false; - - result.push_back(test_data); - } - - output->swap(result); - return true; -} - -} // namespace base
diff --git a/base/test/gtest_util.h b/base/test/gtest_util.h deleted file mode 100644 index e4ec0bf..0000000 --- a/base/test/gtest_util.h +++ /dev/null
@@ -1,84 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef BASE_TEST_GTEST_UTIL_H_ -#define BASE_TEST_GTEST_UTIL_H_ - -#include <string> -#include <utility> -#include <vector> - -#include "base/compiler_specific.h" -#include "base/logging.h" -#include "build_config.h" -#include "testing/gtest/include/gtest/gtest.h" - -// EXPECT/ASSERT_DCHECK_DEATH is intended to replace EXPECT/ASSERT_DEBUG_DEATH -// when the death is expected to be caused by a DCHECK. Contrary to -// EXPECT/ASSERT_DEBUG_DEATH however, it doesn't execute the statement in non- -// dcheck builds as DCHECKs are intended to catch things that should never -// happen and as such executing the statement results in undefined behavior -// (|statement| is compiled in unsupported configurations nonetheless). -// Death tests misbehave on Android. -#if DCHECK_IS_ON() && defined(GTEST_HAS_DEATH_TEST) && !defined(OS_ANDROID) - -// EXPECT/ASSERT_DCHECK_DEATH tests verify that a DCHECK is hit ("Check failed" -// is part of the error message), but intentionally do not expose the gtest -// death test's full |regex| parameter to avoid users having to verify the exact -// syntax of the error message produced by the DCHECK. -#define EXPECT_DCHECK_DEATH(statement) EXPECT_DEATH(statement, "Check failed") -#define ASSERT_DCHECK_DEATH(statement) ASSERT_DEATH(statement, "Check failed") - -#else -// DCHECK_IS_ON() && defined(GTEST_HAS_DEATH_TEST) && !defined(OS_ANDROID) - -#define EXPECT_DCHECK_DEATH(statement) \ - GTEST_UNSUPPORTED_DEATH_TEST(statement, "Check failed", ) -#define ASSERT_DCHECK_DEATH(statement) \ - GTEST_UNSUPPORTED_DEATH_TEST(statement, "Check failed", return) - -#endif -// DCHECK_IS_ON() && defined(GTEST_HAS_DEATH_TEST) && !defined(OS_ANDROID) - -namespace base { - -class FilePath; - -struct TestIdentifier { - TestIdentifier(); - TestIdentifier(const TestIdentifier& other); - - std::string test_case_name; - std::string test_name; - std::string file; - int line; -}; - -// Constructs a full test name given a test case name and a test name, -// e.g. for test case "A" and test name "B" returns "A.B". -std::string FormatFullTestName(const std::string& test_case_name, - const std::string& test_name); - -// Returns the full test name with the "DISABLED_" prefix stripped out. -// e.g. for the full test names "A.DISABLED_B", "DISABLED_A.B", and -// "DISABLED_A.DISABLED_B", returns "A.B". -std::string TestNameWithoutDisabledPrefix(const std::string& full_test_name); - -// Returns a vector of gtest-based tests compiled into -// current executable. -std::vector<TestIdentifier> GetCompiledInTests(); - -// Writes the list of gtest-based tests compiled into -// current executable as a JSON file. Returns true on success. -bool WriteCompiledInTestsToFile(const FilePath& path) WARN_UNUSED_RESULT; - -// Reads the list of gtest-based tests from |path| into |output|. -// Returns true on success. -bool ReadTestNamesFromFile( - const FilePath& path, - std::vector<TestIdentifier>* output) WARN_UNUSED_RESULT; - -} // namespace base - -#endif // BASE_TEST_GTEST_UTIL_H_
diff --git a/base/test/gtest_xml_unittest_result_printer.cc b/base/test/gtest_xml_unittest_result_printer.cc deleted file mode 100644 index 558a986..0000000 --- a/base/test/gtest_xml_unittest_result_printer.cc +++ /dev/null
@@ -1,162 +0,0 @@ -// Copyright 2015 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "base/test/gtest_xml_unittest_result_printer.h" - -#include "base/base64.h" -#include "base/command_line.h" -#include "base/files/file_util.h" -#include "base/logging.h" -#include "base/test/test_switches.h" -#include "base/time/time.h" - -namespace base { - -namespace { -const int kDefaultTestPartResultsLimit = 10; - -const char kTestPartLesultsLimitExceeded[] = - "Test part results limit exceeded. Use --test-launcher-test-part-limit to " - "increase or disable limit."; -} // namespace - -XmlUnitTestResultPrinter::XmlUnitTestResultPrinter() - : output_file_(nullptr), open_failed_(false) {} - -XmlUnitTestResultPrinter::~XmlUnitTestResultPrinter() { - if (output_file_ && !open_failed_) { - fprintf(output_file_, "</testsuites>\n"); - fflush(output_file_); - CloseFile(output_file_); - } -} - -bool XmlUnitTestResultPrinter::Initialize(const FilePath& output_file_path) { - DCHECK(!output_file_); - output_file_ = OpenFile(output_file_path, "w"); - if (!output_file_) { - // If the file open fails, we set the output location to stderr. This is - // because in current usage our caller CHECKs the result of this function. - // But that in turn causes a LogMessage that comes back to this object, - // which in turn causes a (double) crash. By pointing at stderr, there might - // be some indication what's going wrong. See https://crbug.com/736783. - output_file_ = stderr; - open_failed_ = true; - return false; - } - - fprintf(output_file_, - "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<testsuites>\n"); - fflush(output_file_); - - return true; -} - -void XmlUnitTestResultPrinter::OnAssert(const char* file, - int line, - const std::string& summary, - const std::string& message) { - WriteTestPartResult(file, line, testing::TestPartResult::kFatalFailure, - summary, message); -} - -void XmlUnitTestResultPrinter::OnTestCaseStart( - const testing::TestCase& test_case) { - fprintf(output_file_, " <testsuite>\n"); - fflush(output_file_); -} - -void XmlUnitTestResultPrinter::OnTestStart( - const testing::TestInfo& test_info) { - // This is our custom extension - it helps to recognize which test was - // running when the test binary crashed. Note that we cannot even open the - // <testcase> tag here - it requires e.g. run time of the test to be known. - fprintf(output_file_, - " <x-teststart name=\"%s\" classname=\"%s\" />\n", - test_info.name(), - test_info.test_case_name()); - fflush(output_file_); -} - -void XmlUnitTestResultPrinter::OnTestEnd(const testing::TestInfo& test_info) { - fprintf(output_file_, - " <testcase name=\"%s\" status=\"run\" time=\"%.3f\"" - " classname=\"%s\">\n", - test_info.name(), - static_cast<double>(test_info.result()->elapsed_time()) / - Time::kMillisecondsPerSecond, - test_info.test_case_name()); - if (test_info.result()->Failed()) { - fprintf(output_file_, - " <failure message=\"\" type=\"\"></failure>\n"); - } - - int limit = test_info.result()->total_part_count(); - if (CommandLine::ForCurrentProcess()->HasSwitch( - switches::kTestLauncherTestPartResultsLimit)) { - std::string limit_str = - CommandLine::ForCurrentProcess()->GetSwitchValueASCII( - switches::kTestLauncherTestPartResultsLimit); - int test_part_results_limit = std::strtol(limit_str.c_str(), nullptr, 10); - if (test_part_results_limit >= 0) - limit = std::min(limit, test_part_results_limit); - } else { - limit = std::min(limit, kDefaultTestPartResultsLimit); - } - - for (int i = 0; i < limit; ++i) { - const auto& test_part_result = test_info.result()->GetTestPartResult(i); - WriteTestPartResult(test_part_result.file_name(), - test_part_result.line_number(), test_part_result.type(), - test_part_result.summary(), test_part_result.message()); - } - - if (test_info.result()->total_part_count() > limit) { - WriteTestPartResult( - "<unknown>", 0, testing::TestPartResult::kNonFatalFailure, - kTestPartLesultsLimitExceeded, kTestPartLesultsLimitExceeded); - } - - fprintf(output_file_, " </testcase>\n"); - fflush(output_file_); -} - -void XmlUnitTestResultPrinter::OnTestCaseEnd( - const testing::TestCase& test_case) { - fprintf(output_file_, " </testsuite>\n"); - fflush(output_file_); -} - -void XmlUnitTestResultPrinter::WriteTestPartResult( - const char* file, - int line, - testing::TestPartResult::Type result_type, - const std::string& summary, - const std::string& message) { - const char* type = "unknown"; - switch (result_type) { - case testing::TestPartResult::kSuccess: - type = "success"; - break; - case testing::TestPartResult::kNonFatalFailure: - type = "failure"; - break; - case testing::TestPartResult::kFatalFailure: - type = "fatal_failure"; - break; - } - std::string summary_encoded; - Base64Encode(summary, &summary_encoded); - std::string message_encoded; - Base64Encode(message, &message_encoded); - fprintf(output_file_, - " <x-test-result-part type=\"%s\" file=\"%s\" line=\"%d\">\n" - " <summary>%s</summary>\n" - " <message>%s</message>\n" - " </x-test-result-part>\n", - type, file, line, summary_encoded.c_str(), message_encoded.c_str()); - fflush(output_file_); -} - -} // namespace base
diff --git a/base/test/gtest_xml_unittest_result_printer.h b/base/test/gtest_xml_unittest_result_printer.h deleted file mode 100644 index 9340382..0000000 --- a/base/test/gtest_xml_unittest_result_printer.h +++ /dev/null
@@ -1,55 +0,0 @@ -// Copyright 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef BASE_TEST_GTEST_XML_UNITTEST_RESULT_PRINTER_H_ -#define BASE_TEST_GTEST_XML_UNITTEST_RESULT_PRINTER_H_ - -#include <stdio.h> - -#include "base/compiler_specific.h" -#include "base/macros.h" -#include "testing/gtest/include/gtest/gtest.h" - -namespace base { - -class FilePath; - -// Generates an XML output file. Format is very close to GTest, but has -// extensions needed by the test launcher. -class XmlUnitTestResultPrinter : public testing::EmptyTestEventListener { - public: - XmlUnitTestResultPrinter(); - ~XmlUnitTestResultPrinter() override; - - // Must be called before adding as a listener. Returns true on success. - bool Initialize(const FilePath& output_file_path) WARN_UNUSED_RESULT; - - // CHECK/DCHECK failed. Print file/line and message to the xml. - void OnAssert(const char* file, - int line, - const std::string& summary, - const std::string& message); - - private: - // testing::EmptyTestEventListener: - void OnTestCaseStart(const testing::TestCase& test_case) override; - void OnTestStart(const testing::TestInfo& test_info) override; - void OnTestEnd(const testing::TestInfo& test_info) override; - void OnTestCaseEnd(const testing::TestCase& test_case) override; - - void WriteTestPartResult(const char* file, - int line, - testing::TestPartResult::Type type, - const std::string& summary, - const std::string& message); - - FILE* output_file_; - bool open_failed_; - - DISALLOW_COPY_AND_ASSIGN(XmlUnitTestResultPrinter); -}; - -} // namespace base - -#endif // BASE_TEST_GTEST_XML_UNITTEST_RESULT_PRINTER_H_
diff --git a/base/test/gtest_xml_util.cc b/base/test/gtest_xml_util.cc deleted file mode 100644 index 37104e8..0000000 --- a/base/test/gtest_xml_util.cc +++ /dev/null
@@ -1,234 +0,0 @@ -// Copyright 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "base/test/gtest_xml_util.h" - -#include <stdint.h> - -#include "base/base64.h" -#include "base/files/file_util.h" -#include "base/logging.h" -#include "base/strings/string_number_conversions.h" -#include "base/strings/stringprintf.h" -#include "base/test/gtest_util.h" -#include "base/test/launcher/test_launcher.h" -#include "third_party/libxml/chromium/libxml_utils.h" - -namespace base { - -namespace { - -// This is used for the xml parser to report errors. This assumes the context -// is a pointer to a std::string where the error message should be appended. -static void XmlErrorFunc(void *context, const char *message, ...) { - va_list args; - va_start(args, message); - std::string* error = static_cast<std::string*>(context); - StringAppendV(error, message, args); - va_end(args); -} - -} // namespace - -bool ProcessGTestOutput(const base::FilePath& output_file, - std::vector<TestResult>* results, - bool* crashed) { - DCHECK(results); - - std::string xml_contents; - if (!ReadFileToString(output_file, &xml_contents)) - return false; - - // Silence XML errors - otherwise they go to stderr. - std::string xml_errors; - ScopedXmlErrorFunc error_func(&xml_errors, &XmlErrorFunc); - - XmlReader xml_reader; - if (!xml_reader.Load(xml_contents)) - return false; - - enum { - STATE_INIT, - STATE_TESTSUITE, - STATE_TESTCASE, - STATE_TEST_RESULT, - STATE_FAILURE, - STATE_END, - } state = STATE_INIT; - - while (xml_reader.Read()) { - xml_reader.SkipToElement(); - std::string node_name(xml_reader.NodeName()); - - switch (state) { - case STATE_INIT: - if (node_name == "testsuites" && !xml_reader.IsClosingElement()) - state = STATE_TESTSUITE; - else - return false; - break; - case STATE_TESTSUITE: - if (node_name == "testsuites" && xml_reader.IsClosingElement()) - state = STATE_END; - else if (node_name == "testsuite" && !xml_reader.IsClosingElement()) - state = STATE_TESTCASE; - else - return false; - break; - case STATE_TESTCASE: - if (node_name == "testsuite" && xml_reader.IsClosingElement()) { - state = STATE_TESTSUITE; - } else if (node_name == "x-teststart" && - !xml_reader.IsClosingElement()) { - // This is our custom extension that helps recognize which test was - // running when the test binary crashed. - TestResult result; - - std::string test_case_name; - if (!xml_reader.NodeAttribute("classname", &test_case_name)) - return false; - std::string test_name; - if (!xml_reader.NodeAttribute("name", &test_name)) - return false; - result.full_name = FormatFullTestName(test_case_name, test_name); - - result.elapsed_time = TimeDelta(); - - // Assume the test crashed - we can correct that later. - result.status = TestResult::TEST_CRASH; - - results->push_back(result); - } else if (node_name == "testcase" && !xml_reader.IsClosingElement()) { - std::string test_status; - if (!xml_reader.NodeAttribute("status", &test_status)) - return false; - - if (test_status != "run" && test_status != "notrun") - return false; - if (test_status != "run") - break; - - TestResult result; - - std::string test_case_name; - if (!xml_reader.NodeAttribute("classname", &test_case_name)) - return false; - std::string test_name; - if (!xml_reader.NodeAttribute("name", &test_name)) - return false; - result.full_name = test_case_name + "." + test_name; - - std::string test_time_str; - if (!xml_reader.NodeAttribute("time", &test_time_str)) - return false; - result.elapsed_time = TimeDelta::FromMicroseconds( - static_cast<int64_t>(strtod(test_time_str.c_str(), nullptr) * - Time::kMicrosecondsPerSecond)); - - result.status = TestResult::TEST_SUCCESS; - - if (!results->empty() && - results->back().full_name == result.full_name && - results->back().status == TestResult::TEST_CRASH) { - // Erase the fail-safe "crashed" result - now we know the test did - // not crash. - results->pop_back(); - } - - results->push_back(result); - } else if (node_name == "failure" && !xml_reader.IsClosingElement()) { - std::string failure_message; - if (!xml_reader.NodeAttribute("message", &failure_message)) - return false; - - DCHECK(!results->empty()); - results->back().status = TestResult::TEST_FAILURE; - - state = STATE_FAILURE; - } else if (node_name == "testcase" && xml_reader.IsClosingElement()) { - // Deliberately empty. - } else if (node_name == "x-test-result-part" && - !xml_reader.IsClosingElement()) { - std::string result_type; - if (!xml_reader.NodeAttribute("type", &result_type)) - return false; - - std::string file_name; - if (!xml_reader.NodeAttribute("file", &file_name)) - return false; - - std::string line_number_str; - if (!xml_reader.NodeAttribute("line", &line_number_str)) - return false; - - int line_number; - if (!StringToInt(line_number_str, &line_number)) - return false; - - TestResultPart::Type type; - if (!TestResultPart::TypeFromString(result_type, &type)) - return false; - - TestResultPart test_result_part; - test_result_part.type = type; - test_result_part.file_name = file_name, - test_result_part.line_number = line_number; - DCHECK(!results->empty()); - results->back().test_result_parts.push_back(test_result_part); - - state = STATE_TEST_RESULT; - } else { - return false; - } - break; - case STATE_TEST_RESULT: - if (node_name == "summary" && !xml_reader.IsClosingElement()) { - std::string summary; - if (!xml_reader.ReadElementContent(&summary)) - return false; - - if (!Base64Decode(summary, &summary)) - return false; - - DCHECK(!results->empty()); - DCHECK(!results->back().test_result_parts.empty()); - results->back().test_result_parts.back().summary = summary; - } else if (node_name == "summary" && xml_reader.IsClosingElement()) { - } else if (node_name == "message" && !xml_reader.IsClosingElement()) { - std::string message; - if (!xml_reader.ReadElementContent(&message)) - return false; - - if (!Base64Decode(message, &message)) - return false; - - DCHECK(!results->empty()); - DCHECK(!results->back().test_result_parts.empty()); - results->back().test_result_parts.back().message = message; - } else if (node_name == "message" && xml_reader.IsClosingElement()) { - } else if (node_name == "x-test-result-part" && - xml_reader.IsClosingElement()) { - state = STATE_TESTCASE; - } else { - return false; - } - break; - case STATE_FAILURE: - if (node_name == "failure" && xml_reader.IsClosingElement()) - state = STATE_TESTCASE; - else - return false; - break; - case STATE_END: - // If we are here and there are still XML elements, the file has wrong - // format. - return false; - } - } - - *crashed = (state != STATE_END); - return true; -} - -} // namespace base
diff --git a/base/test/gtest_xml_util.h b/base/test/gtest_xml_util.h deleted file mode 100644 index b023f80..0000000 --- a/base/test/gtest_xml_util.h +++ /dev/null
@@ -1,27 +0,0 @@ -// Copyright 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef BASE_TEST_GTEST_XML_UTIL_H_ -#define BASE_TEST_GTEST_XML_UTIL_H_ - -#include <vector> - -#include "base/compiler_specific.h" - -namespace base { - -class FilePath; -struct TestResult; - -// Produces a vector of test results based on GTest output file. -// Returns true iff the output file exists and has been successfully parsed. -// On successful return |crashed| is set to true if the test results -// are valid but incomplete. -bool ProcessGTestOutput(const base::FilePath& output_file, - std::vector<TestResult>* results, - bool* crashed) WARN_UNUSED_RESULT; - -} // namespace base - -#endif // BASE_TEST_GTEST_XML_UTIL_H_
diff --git a/base/test/icu_test_util.cc b/base/test/icu_test_util.cc deleted file mode 100644 index a6f3e55..0000000 --- a/base/test/icu_test_util.cc +++ /dev/null
@@ -1,39 +0,0 @@ -// Copyright 2015 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "base/test/icu_test_util.h" - -#include "base/base_switches.h" -#include "base/command_line.h" -#include "base/i18n/icu_util.h" -#include "base/i18n/rtl.h" -#include "third_party/icu/source/common/unicode/uloc.h" - -namespace base { -namespace test { - -ScopedRestoreICUDefaultLocale::ScopedRestoreICUDefaultLocale() - : ScopedRestoreICUDefaultLocale(std::string()) {} - -ScopedRestoreICUDefaultLocale::ScopedRestoreICUDefaultLocale( - const std::string& locale) - : default_locale_(uloc_getDefault()) { - if (!locale.empty()) - i18n::SetICUDefaultLocale(locale.data()); -} - -ScopedRestoreICUDefaultLocale::~ScopedRestoreICUDefaultLocale() { - i18n::SetICUDefaultLocale(default_locale_.data()); -} - -void InitializeICUForTesting() { - if (!CommandLine::ForCurrentProcess()->HasSwitch( - switches::kTestDoNotInitializeIcu)) { - i18n::AllowMultipleInitializeCallsForTesting(); - i18n::InitializeICU(); - } -} - -} // namespace test -} // namespace base
diff --git a/base/test/icu_test_util.h b/base/test/icu_test_util.h deleted file mode 100644 index 1a6e47d..0000000 --- a/base/test/icu_test_util.h +++ /dev/null
@@ -1,35 +0,0 @@ -// Copyright 2015 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef BASE_TEST_ICU_TEST_UTIL_H_ -#define BASE_TEST_ICU_TEST_UTIL_H_ - -#include <string> - -#include "base/macros.h" - -namespace base { -namespace test { - -// In unit tests, prefer ScopedRestoreICUDefaultLocale over -// calling base::i18n::SetICUDefaultLocale() directly. This scoper makes it -// harder to accidentally forget to reset the locale. -class ScopedRestoreICUDefaultLocale { - public: - ScopedRestoreICUDefaultLocale(); - explicit ScopedRestoreICUDefaultLocale(const std::string& locale); - ~ScopedRestoreICUDefaultLocale(); - - private: - const std::string default_locale_; - - DISALLOW_COPY_AND_ASSIGN(ScopedRestoreICUDefaultLocale); -}; - -void InitializeICUForTesting(); - -} // namespace test -} // namespace base - -#endif // BASE_TEST_ICU_TEST_UTIL_H_
diff --git a/base/test/launcher/test_launcher.cc b/base/test/launcher/test_launcher.cc deleted file mode 100644 index b5197c5..0000000 --- a/base/test/launcher/test_launcher.cc +++ /dev/null
@@ -1,1349 +0,0 @@ -// Copyright 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "base/test/launcher/test_launcher.h" - -#include <stdio.h> - -#include <algorithm> -#include <map> -#include <utility> - -#include "base/at_exit.h" -#include "base/bind.h" -#include "base/command_line.h" -#include "base/environment.h" -#include "base/files/file_path.h" -#include "base/files/file_util.h" -#include "base/files/scoped_file.h" -#include "base/format_macros.h" -#include "base/hash.h" -#include "base/lazy_instance.h" -#include "base/location.h" -#include "base/logging.h" -#include "base/macros.h" -#include "base/memory/ptr_util.h" -#include "base/numerics/safe_conversions.h" -#include "base/process/kill.h" -#include "base/process/launch.h" -#include "base/run_loop.h" -#include "base/single_thread_task_runner.h" -#include "base/strings/pattern.h" -#include "base/strings/string_number_conversions.h" -#include "base/strings/string_piece.h" -#include "base/strings/string_split.h" -#include "base/strings/string_util.h" -#include "base/strings/stringize_macros.h" -#include "base/strings/stringprintf.h" -#include "base/strings/utf_string_conversions.h" -#include "base/sys_info.h" -#include "base/task_scheduler/post_task.h" -#include "base/task_scheduler/task_scheduler.h" -#include "base/test/gtest_util.h" -#include "base/test/launcher/test_launcher_tracer.h" -#include "base/test/launcher/test_results_tracker.h" -#include "base/test/test_switches.h" -#include "base/test/test_timeouts.h" -#include "base/threading/thread_restrictions.h" -#include "base/threading/thread_task_runner_handle.h" -#include "base/time/time.h" -#include "build_config.h" -#include "testing/gtest/include/gtest/gtest.h" - -#if defined(OS_POSIX) -#include <fcntl.h> - -#include "base/files/file_descriptor_watcher_posix.h" -#endif - -#if defined(OS_MACOSX) -#include "base/mac/scoped_nsautorelease_pool.h" -#endif - -#if defined(OS_WIN) -#include "base/win/windows_version.h" -#endif - -#if defined(OS_FUCHSIA) -// TODO(scottmg): For temporary code in OnOutputTimeout(). -#include <zircon/syscalls.h> -#include <zircon/syscalls/object.h> -#include "base/fuchsia/default_job.h" -#endif - -namespace base { - -// See https://groups.google.com/a/chromium.org/d/msg/chromium-dev/nkdTP7sstSc/uT3FaE_sgkAJ . -using ::operator<<; - -// The environment variable name for the total number of test shards. -const char kTestTotalShards[] = "GTEST_TOTAL_SHARDS"; -// The environment variable name for the test shard index. -const char kTestShardIndex[] = "GTEST_SHARD_INDEX"; - -namespace { - -// Global tag for test runs where the results are incomplete or unreliable -// for any reason, e.g. early exit because of too many broken tests. -const char kUnreliableResultsTag[] = "UNRELIABLE_RESULTS"; - -// Maximum time of no output after which we print list of processes still -// running. This deliberately doesn't use TestTimeouts (which is otherwise -// a recommended solution), because they can be increased. This would defeat -// the purpose of this timeout, which is 1) to avoid buildbot "no output for -// X seconds" timeout killing the process 2) help communicate status of -// the test launcher to people looking at the output (no output for a long -// time is mysterious and gives no info about what is happening) 3) help -// debugging in case the process hangs anyway. -constexpr TimeDelta kOutputTimeout = TimeDelta::FromSeconds(15); - -// Limit of output snippet lines when printing to stdout. -// Avoids flooding the logs with amount of output that gums up -// the infrastructure. -const size_t kOutputSnippetLinesLimit = 5000; - -// Limit of output snippet size. Exceeding this limit -// results in truncating the output and failing the test. -const size_t kOutputSnippetBytesLimit = 300 * 1024; - -// Set of live launch test processes with corresponding lock (it is allowed -// for callers to launch processes on different threads). -Lock* GetLiveProcessesLock() { - static auto* lock = new Lock; - return lock; -} - -std::map<ProcessHandle, CommandLine>* GetLiveProcesses() { - static auto* map = new std::map<ProcessHandle, CommandLine>; - return map; -} - -// Performance trace generator. -TestLauncherTracer* GetTestLauncherTracer() { - static auto* tracer = new TestLauncherTracer; - return tracer; -} - -// Creates and starts a TaskScheduler with |num_parallel_jobs| dedicated to -// foreground blocking tasks (corresponds to the traits used to launch and wait -// for child processes). -void CreateAndStartTaskScheduler(int num_parallel_jobs) { - // These values are taken from TaskScheduler::StartWithDefaultParams(), which - // is not used directly to allow a custom number of threads in the foreground - // blocking pool. - constexpr int kMaxBackgroundThreads = 1; - constexpr int kMaxBackgroundBlockingThreads = 2; - const int max_foreground_threads = - std::max(1, base::SysInfo::NumberOfProcessors()); - constexpr base::TimeDelta kSuggestedReclaimTime = - base::TimeDelta::FromSeconds(30); - base::TaskScheduler::Create("TestLauncher"); - base::TaskScheduler::GetInstance()->Start( - {{kMaxBackgroundThreads, kSuggestedReclaimTime}, - {kMaxBackgroundBlockingThreads, kSuggestedReclaimTime}, - {max_foreground_threads, kSuggestedReclaimTime}, - {num_parallel_jobs, kSuggestedReclaimTime}}); -} - -// TODO(fuchsia): Fuchsia does not have POSIX signals, but equivalent -// functionality will probably be necessary eventually. See -// https://crbug.com/706592. -#if defined(OS_POSIX) && !defined(OS_FUCHSIA) -// Self-pipe that makes it possible to do complex shutdown handling -// outside of the signal handler. -int g_shutdown_pipe[2] = { -1, -1 }; - -void ShutdownPipeSignalHandler(int signal) { - HANDLE_EINTR(write(g_shutdown_pipe[1], "q", 1)); -} - -void KillSpawnedTestProcesses() { - // Keep the lock until exiting the process to prevent further processes - // from being spawned. - AutoLock lock(*GetLiveProcessesLock()); - - fprintf(stdout, "Sending SIGTERM to %" PRIuS " child processes... ", - GetLiveProcesses()->size()); - fflush(stdout); - - for (const auto& pair : *GetLiveProcesses()) { - // Send the signal to entire process group. - kill((-1) * (pair.first), SIGTERM); - } - - fprintf(stdout, - "done.\nGiving processes a chance to terminate cleanly... "); - fflush(stdout); - - PlatformThread::Sleep(TimeDelta::FromMilliseconds(500)); - - fprintf(stdout, "done.\n"); - fflush(stdout); - - fprintf(stdout, "Sending SIGKILL to %" PRIuS " child processes... ", - GetLiveProcesses()->size()); - fflush(stdout); - - for (const auto& pair : *GetLiveProcesses()) { - // Send the signal to entire process group. - kill((-1) * (pair.first), SIGKILL); - } - - fprintf(stdout, "done.\n"); - fflush(stdout); -} -#endif // defined(OS_POSIX) && !defined(OS_FUCHSIA) - -// Parses the environment variable var as an Int32. If it is unset, returns -// true. If it is set, unsets it then converts it to Int32 before -// returning it in |result|. Returns true on success. -bool TakeInt32FromEnvironment(const char* const var, int32_t* result) { - std::unique_ptr<Environment> env(Environment::Create()); - std::string str_val; - - if (!env->GetVar(var, &str_val)) - return true; - - if (!env->UnSetVar(var)) { - LOG(ERROR) << "Invalid environment: we could not unset " << var << ".\n"; - return false; - } - - if (!StringToInt(str_val, result)) { - LOG(ERROR) << "Invalid environment: " << var << " is not an integer.\n"; - return false; - } - - return true; -} - -// Unsets the environment variable |name| and returns true on success. -// Also returns true if the variable just doesn't exist. -bool UnsetEnvironmentVariableIfExists(const std::string& name) { - std::unique_ptr<Environment> env(Environment::Create()); - std::string str_val; - if (!env->GetVar(name, &str_val)) - return true; - return env->UnSetVar(name); -} - -// Returns true if bot mode has been requested, i.e. defaults optimized -// for continuous integration bots. This way developers don't have to remember -// special command-line flags. -bool BotModeEnabled() { - std::unique_ptr<Environment> env(Environment::Create()); - return CommandLine::ForCurrentProcess()->HasSwitch( - switches::kTestLauncherBotMode) || - env->HasVar("CHROMIUM_TEST_LAUNCHER_BOT_MODE"); -} - -// Returns command line command line after gtest-specific processing -// and applying |wrapper|. -CommandLine PrepareCommandLineForGTest(const CommandLine& command_line, - const std::string& wrapper) { - CommandLine new_command_line(command_line.GetProgram()); - CommandLine::SwitchMap switches = command_line.GetSwitches(); - - // Strip out gtest_repeat flag - this is handled by the launcher process. - switches.erase(kGTestRepeatFlag); - - // Don't try to write the final XML report in child processes. - switches.erase(kGTestOutputFlag); - - for (CommandLine::SwitchMap::const_iterator iter = switches.begin(); - iter != switches.end(); ++iter) { - new_command_line.AppendSwitchNative((*iter).first, (*iter).second); - } - - // Prepend wrapper after last CommandLine quasi-copy operation. CommandLine - // does not really support removing switches well, and trying to do that - // on a CommandLine with a wrapper is known to break. - // TODO(phajdan.jr): Give it a try to support CommandLine removing switches. -#if defined(OS_WIN) - new_command_line.PrependWrapper(ASCIIToUTF16(wrapper)); -#elif defined(OS_POSIX) - new_command_line.PrependWrapper(wrapper); -#endif - - return new_command_line; -} - -// Launches a child process using |command_line|. If the child process is still -// running after |timeout|, it is terminated and |*was_timeout| is set to true. -// Returns exit code of the process. -int LaunchChildTestProcessWithOptions(const CommandLine& command_line, - const LaunchOptions& options, - int flags, - TimeDelta timeout, - ProcessLifetimeObserver* observer, - bool* was_timeout) { - TimeTicks start_time(TimeTicks::Now()); -#if defined(OS_FUCHSIA) // TODO(scottmg): https://crbug.com/755282 - const bool kOnBot = getenv("CHROME_HEADLESS") != nullptr; -#endif // OS_FUCHSIA - -#if defined(OS_POSIX) && !defined(OS_FUCHSIA) - // Make sure an option we rely on is present - see LaunchChildGTestProcess. - DCHECK(options.new_process_group); -#endif - - LaunchOptions new_options(options); - -#if defined(OS_WIN) - DCHECK(!new_options.job_handle); - - win::ScopedHandle job_handle; - if (flags & TestLauncher::USE_JOB_OBJECTS) { - job_handle.Set(CreateJobObject(NULL, NULL)); - if (!job_handle.IsValid()) { - LOG(ERROR) << "Could not create JobObject."; - return -1; - } - - DWORD job_flags = JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE; - - // Allow break-away from job since sandbox and few other places rely on it - // on Windows versions prior to Windows 8 (which supports nested jobs). - if (win::GetVersion() < win::VERSION_WIN8 && - flags & TestLauncher::ALLOW_BREAKAWAY_FROM_JOB) { - job_flags |= JOB_OBJECT_LIMIT_BREAKAWAY_OK; - } - - if (!SetJobObjectLimitFlags(job_handle.Get(), job_flags)) { - LOG(ERROR) << "Could not SetJobObjectLimitFlags."; - return -1; - } - - new_options.job_handle = job_handle.Get(); - } -#elif defined(OS_FUCHSIA) - DCHECK(!new_options.job_handle); - - ScopedZxHandle job_handle; - zx_status_t result = zx_job_create(GetDefaultJob(), 0, job_handle.receive()); - CHECK_EQ(ZX_OK, result) << "zx_job_create: " << zx_status_get_string(result); - new_options.job_handle = job_handle.get(); -#endif // defined(OS_FUCHSIA) - -#if defined(OS_LINUX) - // To prevent accidental privilege sharing to an untrusted child, processes - // are started with PR_SET_NO_NEW_PRIVS. Do not set that here, since this - // new child will be privileged and trusted. - new_options.allow_new_privs = true; -#endif - - Process process; - - { - // Note how we grab the lock before the process possibly gets created. - // This ensures that when the lock is held, ALL the processes are registered - // in the set. - AutoLock lock(*GetLiveProcessesLock()); - -#if defined(OS_WIN) - // Allow the handle used to capture stdio and stdout to be inherited by the - // child. Note that this is done under GetLiveProcessesLock() to ensure that - // only the desired child receives the handle. - if (new_options.stdout_handle) { - ::SetHandleInformation(new_options.stdout_handle, HANDLE_FLAG_INHERIT, - HANDLE_FLAG_INHERIT); - } -#endif - - process = LaunchProcess(command_line, new_options); - -#if defined(OS_WIN) - // Revoke inheritance so that the handle isn't leaked into other children. - // Note that this is done under GetLiveProcessesLock() to ensure that only - // the desired child receives the handle. - if (new_options.stdout_handle) - ::SetHandleInformation(new_options.stdout_handle, HANDLE_FLAG_INHERIT, 0); -#endif - - if (!process.IsValid()) - return -1; - -#if defined(OS_FUCHSIA) // TODO(scottmg): https://crbug.com/755282 - if (kOnBot) { - LOG(ERROR) << base::StringPrintf("adding %x to live process list", - process.Handle()); - } -#endif // OS_FUCHSIA - - // TODO(rvargas) crbug.com/417532: Don't store process handles. - GetLiveProcesses()->insert(std::make_pair(process.Handle(), command_line)); - } - - if (observer) - observer->OnLaunched(process.Handle(), process.Pid()); - - int exit_code = 0; - bool did_exit = false; - - { - base::ScopedAllowBaseSyncPrimitivesForTesting allow_base_sync_primitives; - did_exit = process.WaitForExitWithTimeout(timeout, &exit_code); - } - - if (!did_exit) { - if (observer) - observer->OnTimedOut(command_line); - - *was_timeout = true; - exit_code = -1; // Set a non-zero exit code to signal a failure. - -#if defined(OS_FUCHSIA) // TODO(scottmg): https://crbug.com/755282 - if (kOnBot) { - LOG(ERROR) << base::StringPrintf("about to process.Terminate() %x", - process.Handle()); - } - - // TODO(crbug.com/799268): Remove once we have debugged timed-out/hung - // test job processes. - LOG(ERROR) << "Dumping threads in process " << process.Pid(); - - CommandLine threads_cmdline(base::FilePath("/boot/bin/threads")); - threads_cmdline.AppendArg(IntToString(process.Pid())); - - LaunchOptions threads_options; - threads_options.wait = true; - LaunchProcess(threads_cmdline, threads_options); -#endif // OS_FUCHSIA - { - base::ScopedAllowBaseSyncPrimitivesForTesting allow_base_sync_primitives; - // Ensure that the process terminates. - process.Terminate(-1, true); - } - } - - { - // Note how we grab the log before issuing a possibly broad process kill. - // Other code parts that grab the log kill processes, so avoid trying - // to do that twice and trigger all kinds of log messages. - AutoLock lock(*GetLiveProcessesLock()); - -#if defined(OS_FUCHSIA) - // TODO(scottmg): https://crbug.com/755282 - if (kOnBot) { - LOG(ERROR) << base::StringPrintf("going to zx_task_kill(job) for %x", - process.Handle()); - } - - CHECK_EQ(zx_task_kill(job_handle.get()), ZX_OK); -#elif defined(OS_POSIX) - if (exit_code != 0) { - // On POSIX, in case the test does not exit cleanly, either due to a crash - // or due to it timing out, we need to clean up any child processes that - // it might have created. On Windows, child processes are automatically - // cleaned up using JobObjects. - KillProcessGroup(process.Handle()); - } -#endif - -#if defined(OS_FUCHSIA) // TODO(scottmg): https://crbug.com/755282 - if (kOnBot) { - LOG(ERROR) << base::StringPrintf("removing %x from live process list", - process.Handle()); - } -#endif // OS_FUCHSIA - GetLiveProcesses()->erase(process.Handle()); - } - - GetTestLauncherTracer()->RecordProcessExecution( - start_time, TimeTicks::Now() - start_time); - - return exit_code; -} - -void DoLaunchChildTestProcess( - const CommandLine& command_line, - TimeDelta timeout, - const TestLauncher::LaunchOptions& test_launch_options, - bool redirect_stdio, - SingleThreadTaskRunner* task_runner, - std::unique_ptr<ProcessLifetimeObserver> observer) { - TimeTicks start_time = TimeTicks::Now(); - - ScopedFILE output_file; - FilePath output_filename; - if (redirect_stdio) { - FILE* raw_output_file = CreateAndOpenTemporaryFile(&output_filename); - output_file.reset(raw_output_file); - CHECK(output_file); - } - - LaunchOptions options; -#if defined(OS_WIN) - options.inherit_mode = test_launch_options.inherit_mode; - options.handles_to_inherit = test_launch_options.handles_to_inherit; - if (redirect_stdio) { - HANDLE handle = - reinterpret_cast<HANDLE>(_get_osfhandle(_fileno(output_file.get()))); - CHECK_NE(INVALID_HANDLE_VALUE, handle); - options.stdin_handle = INVALID_HANDLE_VALUE; - options.stdout_handle = handle; - options.stderr_handle = handle; - // See LaunchOptions.stdout_handle comments for why this compares against - // FILE_TYPE_CHAR. - if (options.inherit_mode == base::LaunchOptions::Inherit::kSpecific && - GetFileType(handle) != FILE_TYPE_CHAR) { - options.handles_to_inherit.push_back(handle); - } - } -#elif defined(OS_POSIX) - options.fds_to_remap = test_launch_options.fds_to_remap; - if (redirect_stdio) { - int output_file_fd = fileno(output_file.get()); - CHECK_LE(0, output_file_fd); - options.fds_to_remap.push_back( - std::make_pair(output_file_fd, STDOUT_FILENO)); - options.fds_to_remap.push_back( - std::make_pair(output_file_fd, STDERR_FILENO)); - } - -#if !defined(OS_FUCHSIA) - options.new_process_group = true; -#endif -#if defined(OS_LINUX) - options.kill_on_parent_death = true; -#endif - -#endif // defined(OS_POSIX) - - bool was_timeout = false; - int exit_code = LaunchChildTestProcessWithOptions( - command_line, options, test_launch_options.flags, timeout, observer.get(), - &was_timeout); - - std::string output_file_contents; - if (redirect_stdio) { - fflush(output_file.get()); - output_file.reset(); - CHECK(ReadFileToString(output_filename, &output_file_contents)) - << output_filename; - - if (!DeleteFile(output_filename, false)) { - // This needs to be non-fatal at least for Windows. - LOG(WARNING) << "Failed to delete " << output_filename.AsUTF8Unsafe(); - } - } - - // Invoke OnCompleted on the thread it was originating from, not on a worker - // pool thread. - task_runner->PostTask( - FROM_HERE, - BindOnce(&ProcessLifetimeObserver::OnCompleted, std::move(observer), - exit_code, TimeTicks::Now() - start_time, was_timeout, - output_file_contents)); -} - -} // namespace - -const char kGTestBreakOnFailure[] = "gtest_break_on_failure"; -const char kGTestFilterFlag[] = "gtest_filter"; -const char kGTestFlagfileFlag[] = "gtest_flagfile"; -const char kGTestHelpFlag[] = "gtest_help"; -const char kGTestListTestsFlag[] = "gtest_list_tests"; -const char kGTestRepeatFlag[] = "gtest_repeat"; -const char kGTestRunDisabledTestsFlag[] = "gtest_also_run_disabled_tests"; -const char kGTestOutputFlag[] = "gtest_output"; - -TestLauncherDelegate::~TestLauncherDelegate() = default; - -TestLauncher::LaunchOptions::LaunchOptions() = default; -TestLauncher::LaunchOptions::LaunchOptions(const LaunchOptions& other) = - default; -TestLauncher::LaunchOptions::~LaunchOptions() = default; - -TestLauncher::TestLauncher(TestLauncherDelegate* launcher_delegate, - size_t parallel_jobs) - : launcher_delegate_(launcher_delegate), - total_shards_(1), - shard_index_(0), - cycles_(1), - test_found_count_(0), - test_started_count_(0), - test_finished_count_(0), - test_success_count_(0), - test_broken_count_(0), - retry_count_(0), - retry_limit_(0), - force_run_broken_tests_(false), - run_result_(true), - watchdog_timer_(FROM_HERE, - kOutputTimeout, - this, - &TestLauncher::OnOutputTimeout), - parallel_jobs_(parallel_jobs) {} - -TestLauncher::~TestLauncher() { - base::TaskScheduler::GetInstance()->Shutdown(); -} - -bool TestLauncher::Run() { - if (!Init()) - return false; - - // Value of |cycles_| changes after each iteration. Keep track of the - // original value. - int requested_cycles = cycles_; - -// TODO(fuchsia): Fuchsia does not have POSIX signals. Something similiar to -// this will likely need to be implemented. See https://crbug.com/706592. -#if defined(OS_POSIX) && !defined(OS_FUCHSIA) - CHECK_EQ(0, pipe(g_shutdown_pipe)); - - struct sigaction action; - memset(&action, 0, sizeof(action)); - sigemptyset(&action.sa_mask); - action.sa_handler = &ShutdownPipeSignalHandler; - - CHECK_EQ(0, sigaction(SIGINT, &action, nullptr)); - CHECK_EQ(0, sigaction(SIGQUIT, &action, nullptr)); - CHECK_EQ(0, sigaction(SIGTERM, &action, nullptr)); - - auto controller = base::FileDescriptorWatcher::WatchReadable( - g_shutdown_pipe[0], - base::Bind(&TestLauncher::OnShutdownPipeReadable, Unretained(this))); -#endif // defined(OS_POSIX) && !defined(OS_FUCHSIA) - - // Start the watchdog timer. - watchdog_timer_.Reset(); - - ThreadTaskRunnerHandle::Get()->PostTask( - FROM_HERE, BindOnce(&TestLauncher::RunTestIteration, Unretained(this))); - - RunLoop().Run(); - - if (requested_cycles != 1) - results_tracker_.PrintSummaryOfAllIterations(); - - MaybeSaveSummaryAsJSON(std::vector<std::string>()); - - return run_result_; -} - -void TestLauncher::LaunchChildGTestProcess( - const CommandLine& command_line, - const std::string& wrapper, - TimeDelta timeout, - const LaunchOptions& options, - std::unique_ptr<ProcessLifetimeObserver> observer) { - DCHECK(thread_checker_.CalledOnValidThread()); - - // Record the exact command line used to launch the child. - CommandLine new_command_line( - PrepareCommandLineForGTest(command_line, wrapper)); - - // When running in parallel mode we need to redirect stdio to avoid mixed-up - // output. We also always redirect on the bots to get the test output into - // JSON summary. - bool redirect_stdio = (parallel_jobs_ > 1) || BotModeEnabled(); - - PostTaskWithTraits( - FROM_HERE, {MayBlock(), TaskShutdownBehavior::BLOCK_SHUTDOWN}, - BindOnce(&DoLaunchChildTestProcess, new_command_line, timeout, options, - redirect_stdio, RetainedRef(ThreadTaskRunnerHandle::Get()), - std::move(observer))); -} - -void TestLauncher::OnTestFinished(const TestResult& original_result) { - ++test_finished_count_; - - TestResult result(original_result); - - if (result.output_snippet.length() > kOutputSnippetBytesLimit) { - if (result.status == TestResult::TEST_SUCCESS) - result.status = TestResult::TEST_EXCESSIVE_OUTPUT; - - // Keep the top and bottom of the log and truncate the middle part. - result.output_snippet = - result.output_snippet.substr(0, kOutputSnippetBytesLimit / 2) + "\n" + - StringPrintf("<truncated (%" PRIuS " bytes)>\n", - result.output_snippet.length()) + - result.output_snippet.substr(result.output_snippet.length() - - kOutputSnippetBytesLimit / 2) + - "\n"; - } - - bool print_snippet = false; - std::string print_test_stdio("auto"); - if (CommandLine::ForCurrentProcess()->HasSwitch( - switches::kTestLauncherPrintTestStdio)) { - print_test_stdio = CommandLine::ForCurrentProcess()->GetSwitchValueASCII( - switches::kTestLauncherPrintTestStdio); - } - if (print_test_stdio == "auto") { - print_snippet = (result.status != TestResult::TEST_SUCCESS); - } else if (print_test_stdio == "always") { - print_snippet = true; - } else if (print_test_stdio == "never") { - print_snippet = false; - } else { - LOG(WARNING) << "Invalid value of " << switches::kTestLauncherPrintTestStdio - << ": " << print_test_stdio; - } - if (print_snippet) { - std::vector<base::StringPiece> snippet_lines = - SplitStringPiece(result.output_snippet, "\n", base::KEEP_WHITESPACE, - base::SPLIT_WANT_ALL); - if (snippet_lines.size() > kOutputSnippetLinesLimit) { - size_t truncated_size = snippet_lines.size() - kOutputSnippetLinesLimit; - snippet_lines.erase( - snippet_lines.begin(), - snippet_lines.begin() + truncated_size); - snippet_lines.insert(snippet_lines.begin(), "<truncated>"); - } - fprintf(stdout, "%s", base::JoinString(snippet_lines, "\n").c_str()); - fflush(stdout); - } - - if (result.status == TestResult::TEST_SUCCESS) { - ++test_success_count_; - } else { - tests_to_retry_.insert(result.full_name); - } - - results_tracker_.AddTestResult(result); - - // TODO(phajdan.jr): Align counter (padding). - std::string status_line( - StringPrintf("[%" PRIuS "/%" PRIuS "] %s ", - test_finished_count_, - test_started_count_, - result.full_name.c_str())); - if (result.completed()) { - status_line.append(StringPrintf("(%" PRId64 " ms)", - result.elapsed_time.InMilliseconds())); - } else if (result.status == TestResult::TEST_TIMEOUT) { - status_line.append("(TIMED OUT)"); - } else if (result.status == TestResult::TEST_CRASH) { - status_line.append("(CRASHED)"); - } else if (result.status == TestResult::TEST_SKIPPED) { - status_line.append("(SKIPPED)"); - } else if (result.status == TestResult::TEST_UNKNOWN) { - status_line.append("(UNKNOWN)"); - } else { - // Fail very loudly so it's not ignored. - CHECK(false) << "Unhandled test result status: " << result.status; - } - fprintf(stdout, "%s\n", status_line.c_str()); - fflush(stdout); - - // We just printed a status line, reset the watchdog timer. - watchdog_timer_.Reset(); - - // Do not waste time on timeouts. We include tests with unknown results here - // because sometimes (e.g. hang in between unit tests) that's how a timeout - // gets reported. - if (result.status == TestResult::TEST_TIMEOUT || - result.status == TestResult::TEST_UNKNOWN) { - test_broken_count_++; - } - size_t broken_threshold = - std::max(static_cast<size_t>(20), test_found_count_ / 10); - if (!force_run_broken_tests_ && test_broken_count_ >= broken_threshold) { - fprintf(stdout, "Too many badly broken tests (%" PRIuS "), exiting now.\n", - test_broken_count_); - fflush(stdout); - -#if defined(OS_POSIX) && !defined(OS_FUCHSIA) - KillSpawnedTestProcesses(); -#endif // defined(OS_POSIX) && !defined(OS_FUCHSIA) - - MaybeSaveSummaryAsJSON({"BROKEN_TEST_EARLY_EXIT", kUnreliableResultsTag}); - - exit(1); - } - - if (test_finished_count_ != test_started_count_) - return; - - if (tests_to_retry_.empty() || retry_count_ >= retry_limit_) { - OnTestIterationFinished(); - return; - } - - if (!force_run_broken_tests_ && tests_to_retry_.size() >= broken_threshold) { - fprintf(stdout, - "Too many failing tests (%" PRIuS "), skipping retries.\n", - tests_to_retry_.size()); - fflush(stdout); - - results_tracker_.AddGlobalTag("BROKEN_TEST_SKIPPED_RETRIES"); - results_tracker_.AddGlobalTag(kUnreliableResultsTag); - - OnTestIterationFinished(); - return; - } - - retry_count_++; - - std::vector<std::string> test_names(tests_to_retry_.begin(), - tests_to_retry_.end()); - - tests_to_retry_.clear(); - - size_t retry_started_count = launcher_delegate_->RetryTests(this, test_names); - if (retry_started_count == 0) { - // Signal failure, but continue to run all requested test iterations. - // With the summary of all iterations at the end this is a good default. - run_result_ = false; - - OnTestIterationFinished(); - return; - } - - fprintf(stdout, "Retrying %" PRIuS " test%s (retry #%" PRIuS ")\n", - retry_started_count, - retry_started_count > 1 ? "s" : "", - retry_count_); - fflush(stdout); - - test_started_count_ += retry_started_count; -} - -// Helper used to parse test filter files. Syntax is documented in -// //testing/buildbot/filters/README.md . -bool LoadFilterFile(const FilePath& file_path, - std::vector<std::string>* positive_filter, - std::vector<std::string>* negative_filter) { - std::string file_content; - if (!ReadFileToString(file_path, &file_content)) { - LOG(ERROR) << "Failed to read the filter file."; - return false; - } - - std::vector<std::string> filter_lines = SplitString( - file_content, "\n", base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL); - int line_num = 0; - for (const std::string& filter_line : filter_lines) { - line_num++; - - size_t hash_pos = filter_line.find('#'); - - // In case when # symbol is not in the beginning of the line and is not - // proceeded with a space then it's likely that the comment was - // unintentional. - if (hash_pos != std::string::npos && hash_pos > 0 && - filter_line[hash_pos - 1] != ' ') { - LOG(WARNING) << "Content of line " << line_num << " in " << file_path - << " after # is treated as a comment, " << filter_line; - } - - // Strip comments and whitespace from each line. - std::string trimmed_line = - TrimWhitespaceASCII(filter_line.substr(0, hash_pos), TRIM_ALL) - .as_string(); - - if (trimmed_line.substr(0, 2) == "//") { - LOG(ERROR) << "Line " << line_num << " in " << file_path - << " starts with //, use # for comments."; - return false; - } - - // Treat a line starting with '//' as a comment. - if (trimmed_line.empty()) - continue; - - if (trimmed_line[0] == '-') - negative_filter->push_back(trimmed_line.substr(1)); - else - positive_filter->push_back(trimmed_line); - } - - return true; -} - -bool TestLauncher::Init() { - const CommandLine* command_line = CommandLine::ForCurrentProcess(); - - // Initialize sharding. Command line takes precedence over legacy environment - // variables. - if (command_line->HasSwitch(switches::kTestLauncherTotalShards) && - command_line->HasSwitch(switches::kTestLauncherShardIndex)) { - if (!StringToInt( - command_line->GetSwitchValueASCII( - switches::kTestLauncherTotalShards), - &total_shards_)) { - LOG(ERROR) << "Invalid value for " << switches::kTestLauncherTotalShards; - return false; - } - if (!StringToInt( - command_line->GetSwitchValueASCII( - switches::kTestLauncherShardIndex), - &shard_index_)) { - LOG(ERROR) << "Invalid value for " << switches::kTestLauncherShardIndex; - return false; - } - fprintf(stdout, - "Using sharding settings from command line. This is shard %d/%d\n", - shard_index_, total_shards_); - fflush(stdout); - } else { - if (!TakeInt32FromEnvironment(kTestTotalShards, &total_shards_)) - return false; - if (!TakeInt32FromEnvironment(kTestShardIndex, &shard_index_)) - return false; - fprintf(stdout, - "Using sharding settings from environment. This is shard %d/%d\n", - shard_index_, total_shards_); - fflush(stdout); - } - if (shard_index_ < 0 || - total_shards_ < 0 || - shard_index_ >= total_shards_) { - LOG(ERROR) << "Invalid sharding settings: we require 0 <= " - << kTestShardIndex << " < " << kTestTotalShards - << ", but you have " << kTestShardIndex << "=" << shard_index_ - << ", " << kTestTotalShards << "=" << total_shards_ << ".\n"; - return false; - } - - // Make sure we don't pass any sharding-related environment to the child - // processes. This test launcher implements the sharding completely. - CHECK(UnsetEnvironmentVariableIfExists("GTEST_TOTAL_SHARDS")); - CHECK(UnsetEnvironmentVariableIfExists("GTEST_SHARD_INDEX")); - - if (command_line->HasSwitch(kGTestRepeatFlag) && - !StringToInt(command_line->GetSwitchValueASCII(kGTestRepeatFlag), - &cycles_)) { - LOG(ERROR) << "Invalid value for " << kGTestRepeatFlag; - return false; - } - - if (command_line->HasSwitch(switches::kTestLauncherRetryLimit)) { - int retry_limit = -1; - if (!StringToInt(command_line->GetSwitchValueASCII( - switches::kTestLauncherRetryLimit), &retry_limit) || - retry_limit < 0) { - LOG(ERROR) << "Invalid value for " << switches::kTestLauncherRetryLimit; - return false; - } - - retry_limit_ = retry_limit; - } else if (!command_line->HasSwitch(kGTestFilterFlag) || BotModeEnabled()) { - // Retry failures 3 times by default if we are running all of the tests or - // in bot mode. - retry_limit_ = 3; - } - - if (command_line->HasSwitch(switches::kTestLauncherForceRunBrokenTests)) - force_run_broken_tests_ = true; - - fprintf(stdout, "Using %" PRIuS " parallel jobs.\n", parallel_jobs_); - fflush(stdout); - - CreateAndStartTaskScheduler(static_cast<int>(parallel_jobs_)); - - std::vector<std::string> positive_file_filter; - std::vector<std::string> positive_gtest_filter; - - if (command_line->HasSwitch(switches::kTestLauncherFilterFile)) { - base::FilePath filter_file_path = base::MakeAbsoluteFilePath( - command_line->GetSwitchValuePath(switches::kTestLauncherFilterFile)); - if (!LoadFilterFile(filter_file_path, &positive_file_filter, - &negative_test_filter_)) - return false; - } - - // Split --gtest_filter at '-', if there is one, to separate into - // positive filter and negative filter portions. - std::string filter = command_line->GetSwitchValueASCII(kGTestFilterFlag); - size_t dash_pos = filter.find('-'); - if (dash_pos == std::string::npos) { - positive_gtest_filter = - SplitString(filter, ":", base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL); - } else { - // Everything up to the dash. - positive_gtest_filter = - SplitString(filter.substr(0, dash_pos), ":", base::TRIM_WHITESPACE, - base::SPLIT_WANT_ALL); - - // Everything after the dash. - for (std::string pattern : - SplitString(filter.substr(dash_pos + 1), ":", base::TRIM_WHITESPACE, - base::SPLIT_WANT_ALL)) { - negative_test_filter_.push_back(pattern); - } - } - - if (!launcher_delegate_->GetTests(&tests_)) { - LOG(ERROR) << "Failed to get list of tests."; - return false; - } - - CombinePositiveTestFilters(std::move(positive_gtest_filter), - std::move(positive_file_filter)); - - if (!results_tracker_.Init(*command_line)) { - LOG(ERROR) << "Failed to initialize test results tracker."; - return 1; - } - -#if defined(NDEBUG) - results_tracker_.AddGlobalTag("MODE_RELEASE"); -#else - results_tracker_.AddGlobalTag("MODE_DEBUG"); -#endif - - // Operating systems (sorted alphabetically). - // Note that they can deliberately overlap, e.g. OS_LINUX is a subset - // of OS_POSIX. -#if defined(OS_ANDROID) - results_tracker_.AddGlobalTag("OS_ANDROID"); -#endif - -#if defined(OS_BSD) - results_tracker_.AddGlobalTag("OS_BSD"); -#endif - -#if defined(OS_FREEBSD) - results_tracker_.AddGlobalTag("OS_FREEBSD"); -#endif - -#if defined(OS_FUCHSIA) - results_tracker_.AddGlobalTag("OS_FUCHSIA"); -#endif - -#if defined(OS_IOS) - results_tracker_.AddGlobalTag("OS_IOS"); -#endif - -#if defined(OS_LINUX) - results_tracker_.AddGlobalTag("OS_LINUX"); -#endif - -#if defined(OS_MACOSX) - results_tracker_.AddGlobalTag("OS_MACOSX"); -#endif - -#if defined(OS_NACL) - results_tracker_.AddGlobalTag("OS_NACL"); -#endif - -#if defined(OS_OPENBSD) - results_tracker_.AddGlobalTag("OS_OPENBSD"); -#endif - -#if defined(OS_POSIX) - results_tracker_.AddGlobalTag("OS_POSIX"); -#endif - -#if defined(OS_SOLARIS) - results_tracker_.AddGlobalTag("OS_SOLARIS"); -#endif - -#if defined(OS_WIN) - results_tracker_.AddGlobalTag("OS_WIN"); -#endif - - // CPU-related tags. -#if defined(ARCH_CPU_32_BITS) - results_tracker_.AddGlobalTag("CPU_32_BITS"); -#endif - -#if defined(ARCH_CPU_64_BITS) - results_tracker_.AddGlobalTag("CPU_64_BITS"); -#endif - - return true; -} - -void TestLauncher::CombinePositiveTestFilters( - std::vector<std::string> filter_a, - std::vector<std::string> filter_b) { - has_at_least_one_positive_filter_ = !filter_a.empty() || !filter_b.empty(); - if (!has_at_least_one_positive_filter_) { - return; - } - // If two positive filters are present, only run tests that match a pattern - // in both filters. - if (!filter_a.empty() && !filter_b.empty()) { - for (size_t i = 0; i < tests_.size(); i++) { - std::string test_name = - FormatFullTestName(tests_[i].test_case_name, tests_[i].test_name); - bool found_a = false; - bool found_b = false; - for (size_t k = 0; k < filter_a.size(); ++k) { - found_a = found_a || MatchPattern(test_name, filter_a[k]); - } - for (size_t k = 0; k < filter_b.size(); ++k) { - found_b = found_b || MatchPattern(test_name, filter_b[k]); - } - if (found_a && found_b) { - positive_test_filter_.push_back(test_name); - } - } - } else if (!filter_a.empty()) { - positive_test_filter_ = std::move(filter_a); - } else { - positive_test_filter_ = std::move(filter_b); - } -} - -void TestLauncher::RunTests() { - std::vector<std::string> test_names; - const CommandLine* command_line = CommandLine::ForCurrentProcess(); - for (const TestIdentifier& test_id : tests_) { - std::string test_name = - FormatFullTestName(test_id.test_case_name, test_id.test_name); - - results_tracker_.AddTest(test_name); - - if (test_name.find("DISABLED") != std::string::npos) { - results_tracker_.AddDisabledTest(test_name); - - // Skip disabled tests unless explicitly requested. - if (!command_line->HasSwitch(kGTestRunDisabledTestsFlag)) - continue; - } - - if (!launcher_delegate_->ShouldRunTest(test_id.test_case_name, - test_id.test_name)) { - continue; - } - - // Count tests in the binary, before we apply filter and sharding. - test_found_count_++; - - std::string test_name_no_disabled = - TestNameWithoutDisabledPrefix(test_name); - - // Skip the test that doesn't match the filter (if given). - if (has_at_least_one_positive_filter_) { - bool found = false; - for (auto filter : positive_test_filter_) { - if (MatchPattern(test_name, filter) || - MatchPattern(test_name_no_disabled, filter)) { - found = true; - break; - } - } - - if (!found) - continue; - } - if (!negative_test_filter_.empty()) { - bool excluded = false; - for (auto filter : negative_test_filter_) { - if (MatchPattern(test_name, filter) || - MatchPattern(test_name_no_disabled, filter)) { - excluded = true; - break; - } - } - - if (excluded) - continue; - } - - if (Hash(test_name) % total_shards_ != static_cast<uint32_t>(shard_index_)) - continue; - - // Report test locations after applying all filters, so that we report test - // locations only for those tests that were run as part of this shard. - results_tracker_.AddTestLocation(test_name, test_id.file, test_id.line); - - test_names.push_back(test_name); - } - - // Save an early test summary in case the launcher crashes or gets killed. - MaybeSaveSummaryAsJSON({"EARLY_SUMMARY", kUnreliableResultsTag}); - - test_started_count_ = launcher_delegate_->RunTests(this, test_names); - - if (test_started_count_ == 0) { - fprintf(stdout, "0 tests run\n"); - fflush(stdout); - - // No tests have actually been started, so kick off the next iteration. - ThreadTaskRunnerHandle::Get()->PostTask( - FROM_HERE, BindOnce(&TestLauncher::RunTestIteration, Unretained(this))); - } -} - -void TestLauncher::RunTestIteration() { - const bool stop_on_failure = - CommandLine::ForCurrentProcess()->HasSwitch(kGTestBreakOnFailure); - if (cycles_ == 0 || - (stop_on_failure && test_success_count_ != test_finished_count_)) { - RunLoop::QuitCurrentWhenIdleDeprecated(); - return; - } - - // Special value "-1" means "repeat indefinitely". - cycles_ = (cycles_ == -1) ? cycles_ : cycles_ - 1; - - test_found_count_ = 0; - test_started_count_ = 0; - test_finished_count_ = 0; - test_success_count_ = 0; - test_broken_count_ = 0; - retry_count_ = 0; - tests_to_retry_.clear(); - results_tracker_.OnTestIterationStarting(); - - ThreadTaskRunnerHandle::Get()->PostTask( - FROM_HERE, BindOnce(&TestLauncher::RunTests, Unretained(this))); -} - -#if defined(OS_POSIX) && !defined(OS_FUCHSIA) -// I/O watcher for the reading end of the self-pipe above. -// Terminates any launched child processes and exits the process. -void TestLauncher::OnShutdownPipeReadable() { - fprintf(stdout, "\nCaught signal. Killing spawned test processes...\n"); - fflush(stdout); - - KillSpawnedTestProcesses(); - - MaybeSaveSummaryAsJSON({"CAUGHT_TERMINATION_SIGNAL", kUnreliableResultsTag}); - - // The signal would normally kill the process, so exit now. - _exit(1); -} -#endif // defined(OS_POSIX) - -void TestLauncher::MaybeSaveSummaryAsJSON( - const std::vector<std::string>& additional_tags) { - const CommandLine* command_line = CommandLine::ForCurrentProcess(); - if (command_line->HasSwitch(switches::kTestLauncherSummaryOutput)) { - FilePath summary_path(command_line->GetSwitchValuePath( - switches::kTestLauncherSummaryOutput)); - if (!results_tracker_.SaveSummaryAsJSON(summary_path, additional_tags)) { - LOG(ERROR) << "Failed to save test launcher output summary."; - } - } - if (command_line->HasSwitch(switches::kTestLauncherTrace)) { - FilePath trace_path( - command_line->GetSwitchValuePath(switches::kTestLauncherTrace)); - if (!GetTestLauncherTracer()->Dump(trace_path)) { - LOG(ERROR) << "Failed to save test launcher trace."; - } - } -} - -void TestLauncher::OnTestIterationFinished() { - TestResultsTracker::TestStatusMap tests_by_status( - results_tracker_.GetTestStatusMapForCurrentIteration()); - if (!tests_by_status[TestResult::TEST_UNKNOWN].empty()) - results_tracker_.AddGlobalTag(kUnreliableResultsTag); - - // When we retry tests, success is determined by having nothing more - // to retry (everything eventually passed), as opposed to having - // no failures at all. - if (tests_to_retry_.empty()) { - fprintf(stdout, "SUCCESS: all tests passed.\n"); - fflush(stdout); - } else { - // Signal failure, but continue to run all requested test iterations. - // With the summary of all iterations at the end this is a good default. - run_result_ = false; - } - - results_tracker_.PrintSummaryOfCurrentIteration(); - - // Kick off the next iteration. - ThreadTaskRunnerHandle::Get()->PostTask( - FROM_HERE, BindOnce(&TestLauncher::RunTestIteration, Unretained(this))); -} - -void TestLauncher::OnOutputTimeout() { - DCHECK(thread_checker_.CalledOnValidThread()); - - AutoLock lock(*GetLiveProcessesLock()); - - fprintf(stdout, "Still waiting for the following processes to finish:\n"); - - for (const auto& pair : *GetLiveProcesses()) { -#if defined(OS_WIN) - fwprintf(stdout, L"\t%s\n", pair.second.GetCommandLineString().c_str()); -#else - fprintf(stdout, "\t%s\n", pair.second.GetCommandLineString().c_str()); -#endif - -#if defined(OS_FUCHSIA) - // TODO(scottmg): Temporary code to try to identify why child processes - // appear to not be terminated after a timeout correctly. - // https://crbug.com/750370 and https://crbug.com/738275. - - zx_info_process_t proc_info = {}; - zx_status_t status = - zx_object_get_info(pair.first, ZX_INFO_PROCESS, &proc_info, - sizeof(proc_info), nullptr, nullptr); - if (status != ZX_OK) { - fprintf(stdout, "zx_object_get_info failed for '%s', status=%d\n", - pair.second.GetCommandLineString().c_str(), status); - } else { - fprintf(stdout, " return_code=%d\n", proc_info.return_code); - fprintf(stdout, " started=%d\n", proc_info.started); - fprintf(stdout, " exited=%d\n", proc_info.exited); - fprintf(stdout, " debugger_attached=%d\n", proc_info.debugger_attached); - } -#endif // OS_FUCHSIA - } - - fflush(stdout); - - // Arm the timer again - otherwise it would fire only once. - watchdog_timer_.Reset(); -} - -size_t NumParallelJobs() { - const CommandLine* command_line = CommandLine::ForCurrentProcess(); - if (command_line->HasSwitch(switches::kTestLauncherJobs)) { - // If the number of test launcher jobs was specified, return that number. - size_t jobs = 0U; - - if (!StringToSizeT( - command_line->GetSwitchValueASCII(switches::kTestLauncherJobs), - &jobs) || - !jobs) { - LOG(ERROR) << "Invalid value for " << switches::kTestLauncherJobs; - return 0U; - } - return jobs; - } - if (command_line->HasSwitch(kGTestFilterFlag) && !BotModeEnabled()) { - // Do not run jobs in parallel by default if we are running a subset of - // the tests and if bot mode is off. - return 1U; - } - - // Default to the number of processor cores. - return base::checked_cast<size_t>(SysInfo::NumberOfProcessors()); -} - -std::string GetTestOutputSnippet(const TestResult& result, - const std::string& full_output) { - size_t run_pos = full_output.find(std::string("[ RUN ] ") + - result.full_name); - if (run_pos == std::string::npos) - return std::string(); - - size_t end_pos = full_output.find(std::string("[ FAILED ] ") + - result.full_name, - run_pos); - // Only clip the snippet to the "OK" message if the test really - // succeeded. It still might have e.g. crashed after printing it. - if (end_pos == std::string::npos && - result.status == TestResult::TEST_SUCCESS) { - end_pos = full_output.find(std::string("[ OK ] ") + - result.full_name, - run_pos); - } - if (end_pos != std::string::npos) { - size_t newline_pos = full_output.find("\n", end_pos); - if (newline_pos != std::string::npos) - end_pos = newline_pos + 1; - } - - std::string snippet(full_output.substr(run_pos)); - if (end_pos != std::string::npos) - snippet = full_output.substr(run_pos, end_pos - run_pos); - - return snippet; -} - -} // namespace base
diff --git a/base/test/launcher/test_launcher.h b/base/test/launcher/test_launcher.h deleted file mode 100644 index fe9f080..0000000 --- a/base/test/launcher/test_launcher.h +++ /dev/null
@@ -1,262 +0,0 @@ -// Copyright 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef BASE_TEST_LAUNCHER_TEST_LAUNCHER_H_ -#define BASE_TEST_LAUNCHER_TEST_LAUNCHER_H_ - -#include <stddef.h> -#include <stdint.h> - -#include <memory> -#include <set> -#include <string> -#include <vector> - -#include "base/compiler_specific.h" -#include "base/macros.h" -#include "base/process/launch.h" -#include "base/test/gtest_util.h" -#include "base/test/launcher/test_result.h" -#include "base/test/launcher/test_results_tracker.h" -#include "base/threading/thread_checker.h" -#include "base/time/time.h" -#include "base/timer/timer.h" -#include "build_config.h" - -namespace base { - -class CommandLine; -struct LaunchOptions; -class TestLauncher; - -// Constants for GTest command-line flags. -extern const char kGTestFilterFlag[]; -extern const char kGTestFlagfileFlag[]; -extern const char kGTestHelpFlag[]; -extern const char kGTestListTestsFlag[]; -extern const char kGTestRepeatFlag[]; -extern const char kGTestRunDisabledTestsFlag[]; -extern const char kGTestOutputFlag[]; - -// Interface for use with LaunchTests that abstracts away exact details -// which tests and how are run. -class TestLauncherDelegate { - public: - // Called to get names of tests available for running. The delegate - // must put the result in |output| and return true on success. - virtual bool GetTests(std::vector<TestIdentifier>* output) = 0; - - // Called before a test is considered for running. If it returns false, - // the test is not run. If it returns true, the test will be run provided - // it is part of the current shard. - virtual bool ShouldRunTest(const std::string& test_case_name, - const std::string& test_name) = 0; - - // Called to make the delegate run the specified tests. The delegate must - // return the number of actual tests it's going to run (can be smaller, - // equal to, or larger than size of |test_names|). It must also call - // |test_launcher|'s OnTestFinished method once per every run test, - // regardless of its success. - virtual size_t RunTests(TestLauncher* test_launcher, - const std::vector<std::string>& test_names) = 0; - - // Called to make the delegate retry the specified tests. The delegate must - // return the number of actual tests it's going to retry (can be smaller, - // equal to, or larger than size of |test_names|). It must also call - // |test_launcher|'s OnTestFinished method once per every retried test, - // regardless of its success. - virtual size_t RetryTests(TestLauncher* test_launcher, - const std::vector<std::string>& test_names) = 0; - - protected: - virtual ~TestLauncherDelegate(); -}; - -// An observer of child process lifetime events generated by -// LaunchChildGTestProcess. -class ProcessLifetimeObserver { - public: - virtual ~ProcessLifetimeObserver() = default; - - // Invoked once the child process is started. |handle| is a handle to the - // child process and |id| is its pid. NOTE: this method is invoked on the - // thread the process is launched on immediately after it is launched. The - // caller owns the ProcessHandle. - virtual void OnLaunched(ProcessHandle handle, ProcessId id) {} - - // Invoked when a test process exceeds its runtime, immediately before it is - // terminated. |command_line| is the command line used to launch the process. - // NOTE: this method is invoked on the thread the process is launched on. - virtual void OnTimedOut(const CommandLine& command_line) {} - - // Invoked after a child process finishes, reporting the process |exit_code|, - // child process |elapsed_time|, whether or not the process was terminated as - // a result of a timeout, and the output of the child (stdout and stderr - // together). NOTE: this method is invoked on the same thread as - // LaunchChildGTestProcess. - virtual void OnCompleted(int exit_code, - TimeDelta elapsed_time, - bool was_timeout, - const std::string& output) {} - - protected: - ProcessLifetimeObserver() = default; - - private: - DISALLOW_COPY_AND_ASSIGN(ProcessLifetimeObserver); -}; - -// Launches tests using a TestLauncherDelegate. -class TestLauncher { - public: - // Flags controlling behavior of LaunchChildGTestProcess. - enum LaunchChildGTestProcessFlags { - // Allows usage of job objects on Windows. Helps properly clean up child - // processes. - USE_JOB_OBJECTS = (1 << 0), - - // Allows breakaway from job on Windows. May result in some child processes - // not being properly terminated after launcher dies if these processes - // fail to cooperate. - ALLOW_BREAKAWAY_FROM_JOB = (1 << 1), - }; - - struct LaunchOptions { - LaunchOptions(); - LaunchOptions(const LaunchOptions& other); - ~LaunchOptions(); - - int flags = 0; - // These mirror values in base::LaunchOptions, see it for details. -#if defined(OS_WIN) - base::LaunchOptions::Inherit inherit_mode = - base::LaunchOptions::Inherit::kSpecific; - base::HandlesToInheritVector handles_to_inherit; -#elif defined(OS_POSIX) - FileHandleMappingVector fds_to_remap; -#endif - }; - - // Constructor. |parallel_jobs| is the limit of simultaneous parallel test - // jobs. - TestLauncher(TestLauncherDelegate* launcher_delegate, size_t parallel_jobs); - ~TestLauncher(); - - // Runs the launcher. Must be called at most once. - bool Run() WARN_UNUSED_RESULT; - - // Launches a child process (assumed to be gtest-based binary) using - // |command_line|. If |wrapper| is not empty, it is prepended to the final - // command line. |observer|, if not null, is used to convey process lifetime - // events to the caller. |observer| is destroyed after its OnCompleted - // method is invoked. - void LaunchChildGTestProcess( - const CommandLine& command_line, - const std::string& wrapper, - TimeDelta timeout, - const LaunchOptions& options, - std::unique_ptr<ProcessLifetimeObserver> observer); - - // Called when a test has finished running. - void OnTestFinished(const TestResult& result); - - private: - bool Init() WARN_UNUSED_RESULT; - - // Runs all tests in current iteration. - void RunTests(); - - void CombinePositiveTestFilters(std::vector<std::string> filter_a, - std::vector<std::string> filter_b); - - void RunTestIteration(); - -#if defined(OS_POSIX) - void OnShutdownPipeReadable(); -#endif - - // Saves test results summary as JSON if requested from command line. - void MaybeSaveSummaryAsJSON(const std::vector<std::string>& additional_tags); - - // Called when a test iteration is finished. - void OnTestIterationFinished(); - - // Called by the delay timer when no output was made for a while. - void OnOutputTimeout(); - - // Make sure we don't accidentally call the wrong methods e.g. on the worker - // pool thread. Should be the first member so that it's destroyed last: when - // destroying other members, especially the worker pool, we may check the code - // is running on the correct thread. - ThreadChecker thread_checker_; - - TestLauncherDelegate* launcher_delegate_; - - // Support for outer sharding, just like gtest does. - int32_t total_shards_; // Total number of outer shards, at least one. - int32_t shard_index_; // Index of shard the launcher is to run. - - int cycles_; // Number of remaining test itreations, or -1 for infinite. - - // Test filters (empty means no filter). - bool has_at_least_one_positive_filter_; - std::vector<std::string> positive_test_filter_; - std::vector<std::string> negative_test_filter_; - - // Tests to use (cached result of TestLauncherDelegate::GetTests). - std::vector<TestIdentifier> tests_; - - // Number of tests found in this binary. - size_t test_found_count_; - - // Number of tests started in this iteration. - size_t test_started_count_; - - // Number of tests finished in this iteration. - size_t test_finished_count_; - - // Number of tests successfully finished in this iteration. - size_t test_success_count_; - - // Number of tests either timing out or having an unknown result, - // likely indicating a more systemic problem if widespread. - size_t test_broken_count_; - - // Number of retries in this iteration. - size_t retry_count_; - - // Maximum number of retries per iteration. - size_t retry_limit_; - - // If true will not early exit nor skip retries even if too many tests are - // broken. - bool force_run_broken_tests_; - - // Tests to retry in this iteration. - std::set<std::string> tests_to_retry_; - - // Result to be returned from Run. - bool run_result_; - - TestResultsTracker results_tracker_; - - // Watchdog timer to make sure we do not go without output for too long. - DelayTimer watchdog_timer_; - - // Number of jobs to run in parallel. - size_t parallel_jobs_; - - DISALLOW_COPY_AND_ASSIGN(TestLauncher); -}; - -// Return the number of parallel jobs to use, or 0U in case of error. -size_t NumParallelJobs(); - -// Extract part from |full_output| that applies to |result|. -std::string GetTestOutputSnippet(const TestResult& result, - const std::string& full_output); - -} // namespace base - -#endif // BASE_TEST_LAUNCHER_TEST_LAUNCHER_H_
diff --git a/base/test/launcher/test_launcher_nacl_nonsfi.cc b/base/test/launcher/test_launcher_nacl_nonsfi.cc deleted file mode 100644 index eeb0d92..0000000 --- a/base/test/launcher/test_launcher_nacl_nonsfi.cc +++ /dev/null
@@ -1,170 +0,0 @@ -// Copyright 2015 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include <inttypes.h> -#include <stdio.h> - -#include <string> - -#include "base/command_line.h" -#include "base/files/file_path.h" -#include "base/files/file_util.h" -#include "base/message_loop/message_loop.h" -#include "base/path_service.h" -#include "base/process/launch.h" -#include "base/strings/string_piece.h" -#include "base/strings/string_tokenizer.h" -#include "base/strings/string_util.h" -#include "base/sys_info.h" -#include "base/test/launcher/test_launcher.h" -#include "base/test/launcher/unit_test_launcher.h" -#include "base/test/test_switches.h" -#include "base/test/test_timeouts.h" -#include "build_config.h" - -#if defined(OS_POSIX) -#include "base/files/file_descriptor_watcher_posix.h" -#endif - -namespace base { - -namespace { - -const char kHelpFlag[] = "help"; - -void PrintUsage() { - fprintf(stdout, - "Runs tests using the gtest framework, each batch of tests being\n" - "run in their own process. Supported command-line flags:\n" - "\n" - " Common flags:\n" - " --gtest_filter=...\n" - " Runs a subset of tests (see --gtest_help for more info).\n" - "\n" - " --help\n" - " Shows this message.\n" - "\n" - " Other flags:\n" - " --test-launcher-retry-limit=N\n" - " Sets the limit of test retries on failures to N.\n" - "\n" - " --test-launcher-summary-output=PATH\n" - " Saves a JSON machine-readable summary of the run.\n" - "\n" - " --test-launcher-print-test-stdio=auto|always|never\n" - " Controls when full test output is printed.\n" - " auto means to print it when the test failed.\n" - "\n" - " --test-launcher-total-shards=N\n" - " Sets the total number of shards to N.\n" - "\n" - " --test-launcher-shard-index=N\n" - " Sets the shard index to run to N (from 0 to TOTAL - 1).\n"); - fflush(stdout); -} - -class NonSfiUnitTestPlatformDelegate : public base::UnitTestPlatformDelegate { - public: - NonSfiUnitTestPlatformDelegate() = default; - - bool Init(const std::string& test_binary) { - base::FilePath dir_exe; - if (!PathService::Get(base::DIR_EXE, &dir_exe)) { - LOG(ERROR) << "Failed to get directory of the current executable."; - return false; - } - - test_path_ = dir_exe.AppendASCII(test_binary); - return true; - } - - private: - bool CreateResultsFile(base::FilePath* path) override { - if (!base::CreateNewTempDirectory(base::FilePath::StringType(), path)) - return false; - *path = path->AppendASCII("test_results.xml"); - return true; - } - - bool CreateTemporaryFile(base::FilePath* path) override { return false; } - - bool GetTests(std::vector<base::TestIdentifier>* output) override { - base::FilePath output_file; - if (!base::CreateTemporaryFile(&output_file)) { - LOG(ERROR) << "Failed to create a temp file."; - return false; - } - - base::CommandLine cmd_line(test_path_); - cmd_line.AppendSwitchPath(switches::kTestLauncherListTests, output_file); - - base::LaunchOptions launch_options; - launch_options.wait = true; - - if (!base::LaunchProcess(cmd_line, launch_options).IsValid()) - return false; - - return base::ReadTestNamesFromFile(output_file, output); - } - - std::string GetWrapperForChildGTestProcess() override { - return std::string(); - } - - base::CommandLine GetCommandLineForChildGTestProcess( - const std::vector<std::string>& test_names, - const base::FilePath& output_file, - const base::FilePath& flag_file) override { - base::CommandLine cmd_line(test_path_); - cmd_line.AppendSwitchPath( - switches::kTestLauncherOutput, output_file); - cmd_line.AppendSwitchASCII( - base::kGTestFilterFlag, base::JoinString(test_names, ":")); - return cmd_line; - } - - void RelaunchTests(base::TestLauncher* test_launcher, - const std::vector<std::string>& test_names, - int launch_flags) override { - RunUnitTestsBatch(test_launcher, this, test_names, launch_flags); - } - - base::FilePath test_path_; -}; - -} // namespace - -int TestLauncherNonSfiMain(const std::string& test_binary) { - if (base::CommandLine::ForCurrentProcess()->HasSwitch(kHelpFlag)) { - PrintUsage(); - return 0; - } - - base::TimeTicks start_time(base::TimeTicks::Now()); - - TestTimeouts::Initialize(); - - base::MessageLoopForIO message_loop; -#if defined(OS_POSIX) - FileDescriptorWatcher file_descriptor_watcher(&message_loop); -#endif - - NonSfiUnitTestPlatformDelegate platform_delegate; - if (!platform_delegate.Init(test_binary)) { - fprintf(stderr, "Failed to initialize test launcher.\n"); - fflush(stderr); - return 1; - } - - base::UnitTestLauncherDelegate delegate(&platform_delegate, 10, true); - base::TestLauncher launcher(&delegate, base::SysInfo::NumberOfProcessors()); - bool success = launcher.Run(); - - fprintf(stdout, "Tests took %" PRId64 " seconds.\n", - (base::TimeTicks::Now() - start_time).InSeconds()); - fflush(stdout); - return success ? 0 : 1; -} - -} // namespace base
diff --git a/base/test/launcher/test_launcher_nacl_nonsfi.h b/base/test/launcher/test_launcher_nacl_nonsfi.h deleted file mode 100644 index 6cb3785..0000000 --- a/base/test/launcher/test_launcher_nacl_nonsfi.h +++ /dev/null
@@ -1,17 +0,0 @@ -// Copyright 2015 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef BASE_TEST_LAUNCHER_TEST_LAUNCHER_NACL_NONSFI_H_ -#define BASE_TEST_LAUNCHER_TEST_LAUNCHER_NACL_NONSFI_H_ - -#include <string> - -namespace base { - -// Launches the NaCl Non-SFI test binary |test_binary|. -int TestLauncherNonSfiMain(const std::string& test_binary); - -} // namespace base - -#endif // BASE_TEST_LAUNCHER_TEST_LAUNCHER_NACL_NONSFI_H_
diff --git a/base/test/launcher/test_launcher_tracer.cc b/base/test/launcher/test_launcher_tracer.cc deleted file mode 100644 index d525df7..0000000 --- a/base/test/launcher/test_launcher_tracer.cc +++ /dev/null
@@ -1,53 +0,0 @@ -// Copyright 2016 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "base/test/launcher/test_launcher_tracer.h" - -#include "base/json/json_file_value_serializer.h" -#include "base/strings/stringprintf.h" -#include "base/values.h" - -namespace base { - -TestLauncherTracer::TestLauncherTracer() - : trace_start_time_(TimeTicks::Now()) {} - -TestLauncherTracer::~TestLauncherTracer() = default; - -void TestLauncherTracer::RecordProcessExecution(TimeTicks start_time, - TimeDelta duration) { - AutoLock lock(lock_); - - Event event; - event.name = StringPrintf("process #%zu", events_.size()); - event.timestamp = start_time; - event.duration = duration; - event.thread_id = PlatformThread::CurrentId(); - events_.push_back(event); -} - -bool TestLauncherTracer::Dump(const FilePath& path) { - AutoLock lock(lock_); - - std::unique_ptr<ListValue> json_events(new ListValue); - for (const Event& event : events_) { - std::unique_ptr<DictionaryValue> json_event(new DictionaryValue); - json_event->SetString("name", event.name); - json_event->SetString("ph", "X"); - json_event->SetInteger( - "ts", (event.timestamp - trace_start_time_).InMicroseconds()); - json_event->SetInteger("dur", event.duration.InMicroseconds()); - json_event->SetInteger("tid", event.thread_id); - - // Add fake values required by the trace viewer. - json_event->SetInteger("pid", 0); - - json_events->Append(std::move(json_event)); - } - - JSONFileValueSerializer serializer(path); - return serializer.Serialize(*json_events); -} - -} // namespace base
diff --git a/base/test/launcher/test_launcher_tracer.h b/base/test/launcher/test_launcher_tracer.h deleted file mode 100644 index 58bc1b0..0000000 --- a/base/test/launcher/test_launcher_tracer.h +++ /dev/null
@@ -1,55 +0,0 @@ -// Copyright 2016 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef BASE_TEST_LAUNCHER_TEST_LAUNCHER_TRACER_H_ -#define BASE_TEST_LAUNCHER_TEST_LAUNCHER_TRACER_H_ - -#include <string> -#include <vector> - -#include "base/synchronization/lock.h" -#include "base/threading/platform_thread.h" -#include "base/time/time.h" - -namespace base { - -class FilePath; - -// Records traces of test execution, e.g. to analyze performance. -// Thread safe. -class TestLauncherTracer { - public: - TestLauncherTracer(); - ~TestLauncherTracer(); - - // Records an event corresponding to test process execution. - void RecordProcessExecution(TimeTicks start_time, TimeDelta duration); - - // Dumps trace data as JSON. Returns true on success. - bool Dump(const FilePath& path) WARN_UNUSED_RESULT; - - private: - // Simplified version of base::TraceEvent. - struct Event { - std::string name; // Displayed name. - TimeTicks timestamp; // Timestamp when this event began. - TimeDelta duration; // How long was this event. - PlatformThreadId thread_id; // Thread ID where event was reported. - }; - - // Timestamp when tracing started. - TimeTicks trace_start_time_; - - // Log of trace events. - std::vector<Event> events_; - - // Lock to protect all member variables. - Lock lock_; - - DISALLOW_COPY_AND_ASSIGN(TestLauncherTracer); -}; - -} // namespace base - -#endif // BASE_TEST_LAUNCHER_TEST_LAUNCHER_TRACER_H_
diff --git a/base/test/launcher/test_result.cc b/base/test/launcher/test_result.cc deleted file mode 100644 index 9f37a2b..0000000 --- a/base/test/launcher/test_result.cc +++ /dev/null
@@ -1,96 +0,0 @@ -// Copyright 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "base/test/launcher/test_result.h" - -#include <stddef.h> - -#include "base/logging.h" - -namespace base { - -TestResultPart::TestResultPart() = default; -TestResultPart::~TestResultPart() = default; - -TestResultPart::TestResultPart(const TestResultPart& other) = default; -TestResultPart::TestResultPart(TestResultPart&& other) = default; -TestResultPart& TestResultPart::operator=(const TestResultPart& other) = - default; -TestResultPart& TestResultPart::operator=(TestResultPart&& other) = default; - -// static -bool TestResultPart::TypeFromString(const std::string& str, Type* type) { - if (str == "success") - *type = kSuccess; - else if (str == "failure") - *type = kNonFatalFailure; - else if (str == "fatal_failure") - *type = kFatalFailure; - else - return false; - return true; -} - -std::string TestResultPart::TypeAsString() const { - switch (type) { - case kSuccess: - return "success"; - case kNonFatalFailure: - return "failure"; - case kFatalFailure: - return "fatal_failure"; - default: - NOTREACHED(); - } - return "unknown"; -} - -TestResult::TestResult() : status(TEST_UNKNOWN) { -} - -TestResult::~TestResult() = default; - -TestResult::TestResult(const TestResult& other) = default; -TestResult::TestResult(TestResult&& other) = default; -TestResult& TestResult::operator=(const TestResult& other) = default; -TestResult& TestResult::operator=(TestResult&& other) = default; - -std::string TestResult::StatusAsString() const { - switch (status) { - case TEST_UNKNOWN: - return "UNKNOWN"; - case TEST_SUCCESS: - return "SUCCESS"; - case TEST_FAILURE: - return "FAILURE"; - case TEST_FAILURE_ON_EXIT: - return "FAILURE_ON_EXIT"; - case TEST_CRASH: - return "CRASH"; - case TEST_TIMEOUT: - return "TIMEOUT"; - case TEST_SKIPPED: - return "SKIPPED"; - case TEST_EXCESSIVE_OUTPUT: - return "EXCESSIVE_OUTPUT"; - // Rely on compiler warnings to ensure all possible values are handled. - } - - NOTREACHED(); - return std::string(); -} - -std::string TestResult::GetTestName() const { - size_t dot_pos = full_name.find('.'); - CHECK_NE(dot_pos, std::string::npos); - return full_name.substr(dot_pos + 1); -} - -std::string TestResult::GetTestCaseName() const { - size_t dot_pos = full_name.find('.'); - CHECK_NE(dot_pos, std::string::npos); - return full_name.substr(0, dot_pos); -} - -} // namespace base
diff --git a/base/test/launcher/test_result.h b/base/test/launcher/test_result.h deleted file mode 100644 index 07338b3..0000000 --- a/base/test/launcher/test_result.h +++ /dev/null
@@ -1,104 +0,0 @@ -// Copyright 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef BASE_TEST_LAUNCHER_TEST_RESULT_H_ -#define BASE_TEST_LAUNCHER_TEST_RESULT_H_ - -#include <string> -#include <vector> - -#include "base/time/time.h" - -namespace base { - -// Structure contains result of a single EXPECT/ASSERT/SUCCESS. -struct TestResultPart { - enum Type { - kSuccess, // SUCCESS - kNonFatalFailure, // EXPECT - kFatalFailure, // ASSERT - }; - Type type; - - TestResultPart(); - ~TestResultPart(); - - TestResultPart(const TestResultPart& other); - TestResultPart(TestResultPart&& other); - TestResultPart& operator=(const TestResultPart& other); - TestResultPart& operator=(TestResultPart&& other); - - // Convert type to string and back. - static bool TypeFromString(const std::string& str, Type* type); - std::string TypeAsString() const; - - // Filename and line of EXPECT/ASSERT. - std::string file_name; - int line_number; - - // Message without stacktrace, etc. - std::string summary; - - // Complete message. - std::string message; -}; - -// Structure containing result of a single test. -struct TestResult { - enum Status { - TEST_UNKNOWN, // Status not set. - TEST_SUCCESS, // Test passed. - TEST_FAILURE, // Assertion failure (e.g. EXPECT_TRUE, not DCHECK). - TEST_FAILURE_ON_EXIT, // Passed but executable exit code was non-zero. - TEST_TIMEOUT, // Test timed out and was killed. - TEST_CRASH, // Test crashed (includes CHECK/DCHECK failures). - TEST_SKIPPED, // Test skipped (not run at all). - TEST_EXCESSIVE_OUTPUT, // Test exceeded output limit. - }; - - TestResult(); - ~TestResult(); - - TestResult(const TestResult& other); - TestResult(TestResult&& other); - TestResult& operator=(const TestResult& other); - TestResult& operator=(TestResult&& other); - - // Returns the test status as string (e.g. for display). - std::string StatusAsString() const; - - // Returns the test name (e.g. "B" for "A.B"). - std::string GetTestName() const; - - // Returns the test case name (e.g. "A" for "A.B"). - std::string GetTestCaseName() const; - - // Returns true if the test has completed (i.e. the test binary exited - // normally, possibly with an exit code indicating failure, but didn't crash - // or time out in the middle of the test). - bool completed() const { - return status == TEST_SUCCESS || - status == TEST_FAILURE || - status == TEST_FAILURE_ON_EXIT || - status == TEST_EXCESSIVE_OUTPUT; - } - - // Full name of the test (e.g. "A.B"). - std::string full_name; - - Status status; - - // Time it took to run the test. - base::TimeDelta elapsed_time; - - // Output of just this test (optional). - std::string output_snippet; - - // Information about failed expectations. - std::vector<TestResultPart> test_result_parts; -}; - -} // namespace base - -#endif // BASE_TEST_LAUNCHER_TEST_RESULT_H_
diff --git a/base/test/launcher/test_results_tracker.cc b/base/test/launcher/test_results_tracker.cc deleted file mode 100644 index a7e590c..0000000 --- a/base/test/launcher/test_results_tracker.cc +++ /dev/null
@@ -1,541 +0,0 @@ -// Copyright 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "base/test/launcher/test_results_tracker.h" - -#include <stddef.h> - -#include <memory> -#include <utility> - -#include "base/base64.h" -#include "base/command_line.h" -#include "base/files/file.h" -#include "base/files/file_path.h" -#include "base/files/file_util.h" -#include "base/format_macros.h" -#include "base/json/json_writer.h" -#include "base/json/string_escape.h" -#include "base/logging.h" -#include "base/strings/string_util.h" -#include "base/strings/stringprintf.h" -#include "base/test/gtest_util.h" -#include "base/test/launcher/test_launcher.h" -#include "base/time/time.h" -#include "base/values.h" - -namespace base { - -namespace { - -// The default output file for XML output. -const FilePath::CharType kDefaultOutputFile[] = FILE_PATH_LITERAL( - "test_detail.xml"); - -// Converts the given epoch time in milliseconds to a date string in the ISO -// 8601 format, without the timezone information. -// TODO(xyzzyz): Find a good place in Chromium to put it and refactor all uses -// to point to it. -std::string FormatTimeAsIso8601(Time time) { - Time::Exploded exploded; - time.UTCExplode(&exploded); - return StringPrintf("%04d-%02d-%02dT%02d:%02d:%02d", - exploded.year, - exploded.month, - exploded.day_of_month, - exploded.hour, - exploded.minute, - exploded.second); -} - -struct TestSuiteResultsAggregator { - TestSuiteResultsAggregator() - : tests(0), failures(0), disabled(0), errors(0) {} - - void Add(const TestResult& result) { - tests++; - elapsed_time += result.elapsed_time; - - switch (result.status) { - case TestResult::TEST_SUCCESS: - break; - case TestResult::TEST_FAILURE: - failures++; - break; - case TestResult::TEST_EXCESSIVE_OUTPUT: - case TestResult::TEST_FAILURE_ON_EXIT: - case TestResult::TEST_TIMEOUT: - case TestResult::TEST_CRASH: - case TestResult::TEST_UNKNOWN: - errors++; - break; - case TestResult::TEST_SKIPPED: - disabled++; - break; - } - } - - int tests; - int failures; - int disabled; - int errors; - - TimeDelta elapsed_time; -}; - -} // namespace - -TestResultsTracker::TestResultsTracker() : iteration_(-1), out_(nullptr) {} - -TestResultsTracker::~TestResultsTracker() { - DCHECK(thread_checker_.CalledOnValidThread()); - - if (!out_) - return; - - // Maps test case names to test results. - typedef std::map<std::string, std::vector<TestResult> > TestCaseMap; - TestCaseMap test_case_map; - - TestSuiteResultsAggregator all_tests_aggregator; - for (const PerIterationData::ResultsMap::value_type& i - : per_iteration_data_[iteration_].results) { - // Use the last test result as the final one. - TestResult result = i.second.test_results.back(); - test_case_map[result.GetTestCaseName()].push_back(result); - all_tests_aggregator.Add(result); - } - - fprintf(out_, "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"); - fprintf(out_, - "<testsuites name=\"AllTests\" tests=\"%d\" failures=\"%d\"" - " disabled=\"%d\" errors=\"%d\" time=\"%.3f\" timestamp=\"%s\">\n", - all_tests_aggregator.tests, all_tests_aggregator.failures, - all_tests_aggregator.disabled, all_tests_aggregator.errors, - all_tests_aggregator.elapsed_time.InSecondsF(), - FormatTimeAsIso8601(Time::Now()).c_str()); - - for (const TestCaseMap::value_type& i : test_case_map) { - const std::string testsuite_name = i.first; - const std::vector<TestResult>& results = i.second; - - TestSuiteResultsAggregator aggregator; - for (const TestResult& result : results) { - aggregator.Add(result); - } - fprintf(out_, - " <testsuite name=\"%s\" tests=\"%d\" " - "failures=\"%d\" disabled=\"%d\" errors=\"%d\" time=\"%.3f\" " - "timestamp=\"%s\">\n", - testsuite_name.c_str(), aggregator.tests, aggregator.failures, - aggregator.disabled, aggregator.errors, - aggregator.elapsed_time.InSecondsF(), - FormatTimeAsIso8601(Time::Now()).c_str()); - - for (const TestResult& result : results) { - fprintf(out_, " <testcase name=\"%s\" status=\"run\" time=\"%.3f\"" - " classname=\"%s\">\n", - result.GetTestName().c_str(), - result.elapsed_time.InSecondsF(), - result.GetTestCaseName().c_str()); - if (result.status != TestResult::TEST_SUCCESS) { - // The actual failure message is not propagated up to here, as it's too - // much work to escape it properly, and in case of failure, almost - // always one needs to look into full log anyway. - fprintf(out_, " <failure message=\"\" type=\"\"></failure>\n"); - } - fprintf(out_, " </testcase>\n"); - } - fprintf(out_, " </testsuite>\n"); - } - - fprintf(out_, "</testsuites>\n"); - fclose(out_); -} - -bool TestResultsTracker::Init(const CommandLine& command_line) { - DCHECK(thread_checker_.CalledOnValidThread()); - - // Prevent initializing twice. - if (out_) { - NOTREACHED(); - return false; - } - - if (!command_line.HasSwitch(kGTestOutputFlag)) - return true; - - std::string flag = command_line.GetSwitchValueASCII(kGTestOutputFlag); - size_t colon_pos = flag.find(':'); - FilePath path; - if (colon_pos != std::string::npos) { - FilePath flag_path = - command_line.GetSwitchValuePath(kGTestOutputFlag); - FilePath::StringType path_string = flag_path.value(); - path = FilePath(path_string.substr(colon_pos + 1)); - // If the given path ends with '/', consider it is a directory. - // Note: This does NOT check that a directory (or file) actually exists - // (the behavior is same as what gtest does). - if (path.EndsWithSeparator()) { - FilePath executable = command_line.GetProgram().BaseName(); - path = path.Append(executable.ReplaceExtension( - FilePath::StringType(FILE_PATH_LITERAL("xml")))); - } - } - if (path.value().empty()) - path = FilePath(kDefaultOutputFile); - FilePath dir_name = path.DirName(); - if (!DirectoryExists(dir_name)) { - LOG(WARNING) << "The output directory does not exist. " - << "Creating the directory: " << dir_name.value(); - // Create the directory if necessary (because the gtest does the same). - if (!CreateDirectory(dir_name)) { - LOG(ERROR) << "Failed to created directory " << dir_name.value(); - return false; - } - } - out_ = OpenFile(path, "w"); - if (!out_) { - LOG(ERROR) << "Cannot open output file: " - << path.value() << "."; - return false; - } - - return true; -} - -void TestResultsTracker::OnTestIterationStarting() { - DCHECK(thread_checker_.CalledOnValidThread()); - - // Start with a fresh state for new iteration. - iteration_++; - per_iteration_data_.push_back(PerIterationData()); -} - -void TestResultsTracker::AddTest(const std::string& test_name) { - // Record disabled test names without DISABLED_ prefix so that they are easy - // to compare with regular test names, e.g. before or after disabling. - all_tests_.insert(TestNameWithoutDisabledPrefix(test_name)); -} - -void TestResultsTracker::AddDisabledTest(const std::string& test_name) { - // Record disabled test names without DISABLED_ prefix so that they are easy - // to compare with regular test names, e.g. before or after disabling. - disabled_tests_.insert(TestNameWithoutDisabledPrefix(test_name)); -} - -void TestResultsTracker::AddTestLocation(const std::string& test_name, - const std::string& file, - int line) { - test_locations_.insert(std::make_pair(test_name, CodeLocation(file, line))); -} - -void TestResultsTracker::AddTestResult(const TestResult& result) { - DCHECK(thread_checker_.CalledOnValidThread()); - - // Record disabled test names without DISABLED_ prefix so that they are easy - // to compare with regular test names, e.g. before or after disabling. - per_iteration_data_[iteration_].results[ - TestNameWithoutDisabledPrefix(result.full_name)].test_results.push_back( - result); -} - -void TestResultsTracker::PrintSummaryOfCurrentIteration() const { - TestStatusMap tests_by_status(GetTestStatusMapForCurrentIteration()); - - PrintTests(tests_by_status[TestResult::TEST_FAILURE].begin(), - tests_by_status[TestResult::TEST_FAILURE].end(), - "failed"); - PrintTests(tests_by_status[TestResult::TEST_FAILURE_ON_EXIT].begin(), - tests_by_status[TestResult::TEST_FAILURE_ON_EXIT].end(), - "failed on exit"); - PrintTests(tests_by_status[TestResult::TEST_EXCESSIVE_OUTPUT].begin(), - tests_by_status[TestResult::TEST_EXCESSIVE_OUTPUT].end(), - "produced excessive output"); - PrintTests(tests_by_status[TestResult::TEST_TIMEOUT].begin(), - tests_by_status[TestResult::TEST_TIMEOUT].end(), - "timed out"); - PrintTests(tests_by_status[TestResult::TEST_CRASH].begin(), - tests_by_status[TestResult::TEST_CRASH].end(), - "crashed"); - PrintTests(tests_by_status[TestResult::TEST_SKIPPED].begin(), - tests_by_status[TestResult::TEST_SKIPPED].end(), - "skipped"); - PrintTests(tests_by_status[TestResult::TEST_UNKNOWN].begin(), - tests_by_status[TestResult::TEST_UNKNOWN].end(), - "had unknown result"); -} - -void TestResultsTracker::PrintSummaryOfAllIterations() const { - DCHECK(thread_checker_.CalledOnValidThread()); - - TestStatusMap tests_by_status(GetTestStatusMapForAllIterations()); - - fprintf(stdout, "Summary of all test iterations:\n"); - fflush(stdout); - - PrintTests(tests_by_status[TestResult::TEST_FAILURE].begin(), - tests_by_status[TestResult::TEST_FAILURE].end(), - "failed"); - PrintTests(tests_by_status[TestResult::TEST_FAILURE_ON_EXIT].begin(), - tests_by_status[TestResult::TEST_FAILURE_ON_EXIT].end(), - "failed on exit"); - PrintTests(tests_by_status[TestResult::TEST_EXCESSIVE_OUTPUT].begin(), - tests_by_status[TestResult::TEST_EXCESSIVE_OUTPUT].end(), - "produced excessive output"); - PrintTests(tests_by_status[TestResult::TEST_TIMEOUT].begin(), - tests_by_status[TestResult::TEST_TIMEOUT].end(), - "timed out"); - PrintTests(tests_by_status[TestResult::TEST_CRASH].begin(), - tests_by_status[TestResult::TEST_CRASH].end(), - "crashed"); - PrintTests(tests_by_status[TestResult::TEST_SKIPPED].begin(), - tests_by_status[TestResult::TEST_SKIPPED].end(), - "skipped"); - PrintTests(tests_by_status[TestResult::TEST_UNKNOWN].begin(), - tests_by_status[TestResult::TEST_UNKNOWN].end(), - "had unknown result"); - - fprintf(stdout, "End of the summary.\n"); - fflush(stdout); -} - -void TestResultsTracker::AddGlobalTag(const std::string& tag) { - global_tags_.insert(tag); -} - -bool TestResultsTracker::SaveSummaryAsJSON( - const FilePath& path, - const std::vector<std::string>& additional_tags) const { - std::unique_ptr<DictionaryValue> summary_root(new DictionaryValue); - - std::unique_ptr<ListValue> global_tags(new ListValue); - for (const auto& global_tag : global_tags_) { - global_tags->AppendString(global_tag); - } - for (const auto& tag : additional_tags) { - global_tags->AppendString(tag); - } - summary_root->Set("global_tags", std::move(global_tags)); - - std::unique_ptr<ListValue> all_tests(new ListValue); - for (const auto& test : all_tests_) { - all_tests->AppendString(test); - } - summary_root->Set("all_tests", std::move(all_tests)); - - std::unique_ptr<ListValue> disabled_tests(new ListValue); - for (const auto& disabled_test : disabled_tests_) { - disabled_tests->AppendString(disabled_test); - } - summary_root->Set("disabled_tests", std::move(disabled_tests)); - - std::unique_ptr<ListValue> per_iteration_data(new ListValue); - - for (int i = 0; i <= iteration_; i++) { - std::unique_ptr<DictionaryValue> current_iteration_data( - new DictionaryValue); - - for (PerIterationData::ResultsMap::const_iterator j = - per_iteration_data_[i].results.begin(); - j != per_iteration_data_[i].results.end(); - ++j) { - std::unique_ptr<ListValue> test_results(new ListValue); - - for (size_t k = 0; k < j->second.test_results.size(); k++) { - const TestResult& test_result = j->second.test_results[k]; - - std::unique_ptr<DictionaryValue> test_result_value(new DictionaryValue); - - test_result_value->SetString("status", test_result.StatusAsString()); - test_result_value->SetInteger( - "elapsed_time_ms", - static_cast<int>(test_result.elapsed_time.InMilliseconds())); - - bool lossless_snippet = false; - if (IsStringUTF8(test_result.output_snippet)) { - test_result_value->SetString( - "output_snippet", test_result.output_snippet); - lossless_snippet = true; - } else { - test_result_value->SetString( - "output_snippet", - "<non-UTF-8 snippet, see output_snippet_base64>"); - } - - // TODO(phajdan.jr): Fix typo in JSON key (losless -> lossless) - // making sure not to break any consumers of this data. - test_result_value->SetBoolean("losless_snippet", lossless_snippet); - - // Also include the raw version (base64-encoded so that it can be safely - // JSON-serialized - there are no guarantees about character encoding - // of the snippet). This can be very useful piece of information when - // debugging a test failure related to character encoding. - std::string base64_output_snippet; - Base64Encode(test_result.output_snippet, &base64_output_snippet); - test_result_value->SetString("output_snippet_base64", - base64_output_snippet); - - std::unique_ptr<ListValue> test_result_parts(new ListValue); - for (const TestResultPart& result_part : - test_result.test_result_parts) { - std::unique_ptr<DictionaryValue> result_part_value( - new DictionaryValue); - result_part_value->SetString("type", result_part.TypeAsString()); - result_part_value->SetString("file", result_part.file_name); - result_part_value->SetInteger("line", result_part.line_number); - - bool lossless_summary = IsStringUTF8(result_part.summary); - if (lossless_summary) { - result_part_value->SetString("summary", result_part.summary); - } else { - result_part_value->SetString( - "summary", "<non-UTF-8 snippet, see summary_base64>"); - } - result_part_value->SetBoolean("lossless_summary", lossless_summary); - - std::string encoded_summary; - Base64Encode(result_part.summary, &encoded_summary); - result_part_value->SetString("summary_base64", encoded_summary); - - bool lossless_message = IsStringUTF8(result_part.message); - if (lossless_message) { - result_part_value->SetString("message", result_part.message); - } else { - result_part_value->SetString( - "message", "<non-UTF-8 snippet, see message_base64>"); - } - result_part_value->SetBoolean("lossless_message", lossless_message); - - std::string encoded_message; - Base64Encode(result_part.message, &encoded_message); - result_part_value->SetString("message_base64", encoded_message); - - test_result_parts->Append(std::move(result_part_value)); - } - test_result_value->Set("result_parts", std::move(test_result_parts)); - - test_results->Append(std::move(test_result_value)); - } - - current_iteration_data->SetWithoutPathExpansion(j->first, - std::move(test_results)); - } - per_iteration_data->Append(std::move(current_iteration_data)); - } - summary_root->Set("per_iteration_data", std::move(per_iteration_data)); - - std::unique_ptr<DictionaryValue> test_locations(new DictionaryValue); - for (const auto& item : test_locations_) { - std::string test_name = item.first; - CodeLocation location = item.second; - std::unique_ptr<DictionaryValue> location_value(new DictionaryValue); - location_value->SetString("file", location.file); - location_value->SetInteger("line", location.line); - test_locations->SetWithoutPathExpansion(test_name, - std::move(location_value)); - } - summary_root->Set("test_locations", std::move(test_locations)); - - std::string json; - if (!JSONWriter::Write(*summary_root, &json)) - return false; - - File output(path, File::FLAG_CREATE_ALWAYS | File::FLAG_WRITE); - if (!output.IsValid()) - return false; - - int json_size = static_cast<int>(json.size()); - if (output.WriteAtCurrentPos(json.data(), json_size) != json_size) { - return false; - } - - // File::Flush() will call fsync(). This is important on Fuchsia to ensure - // that the file is written to the disk - the system running under qemu will - // shutdown shortly after the test completes. On Fuchsia fsync() times out - // after 15 seconds. Apparently this may not be enough in some cases, - // particularly when running net_unittests on buildbots, see - // https://crbug.com/796318. Try calling fsync() more than once to workaround - // this issue. - // - // TODO(sergeyu): Figure out a better solution. - int flush_attempts_left = 4; - while (flush_attempts_left-- > 0) { - if (output.Flush()) - return true; - LOG(ERROR) << "fsync() failed when saving test output summary. " - << ((flush_attempts_left > 0) ? "Retrying." : " Giving up."); - } - - return false; -} - -TestResultsTracker::TestStatusMap - TestResultsTracker::GetTestStatusMapForCurrentIteration() const { - TestStatusMap tests_by_status; - GetTestStatusForIteration(iteration_, &tests_by_status); - return tests_by_status; -} - -TestResultsTracker::TestStatusMap - TestResultsTracker::GetTestStatusMapForAllIterations() const { - TestStatusMap tests_by_status; - for (int i = 0; i <= iteration_; i++) - GetTestStatusForIteration(i, &tests_by_status); - return tests_by_status; -} - -void TestResultsTracker::GetTestStatusForIteration( - int iteration, TestStatusMap* map) const { - for (PerIterationData::ResultsMap::const_iterator j = - per_iteration_data_[iteration].results.begin(); - j != per_iteration_data_[iteration].results.end(); - ++j) { - // Use the last test result as the final one. - const TestResult& result = j->second.test_results.back(); - (*map)[result.status].insert(result.full_name); - } -} - -// Utility function to print a list of test names. Uses iterator to be -// compatible with different containers, like vector and set. -template<typename InputIterator> -void TestResultsTracker::PrintTests(InputIterator first, - InputIterator last, - const std::string& description) const { - size_t count = std::distance(first, last); - if (count == 0) - return; - - fprintf(stdout, - "%" PRIuS " test%s %s:\n", - count, - count != 1 ? "s" : "", - description.c_str()); - for (InputIterator it = first; it != last; ++it) { - const std::string& test_name = *it; - const auto location_it = test_locations_.find(test_name); - DCHECK(location_it != test_locations_.end()) << test_name; - const CodeLocation& location = location_it->second; - fprintf(stdout, " %s (%s:%d)\n", test_name.c_str(), - location.file.c_str(), location.line); - } - fflush(stdout); -} - -TestResultsTracker::AggregateTestResult::AggregateTestResult() = default; - -TestResultsTracker::AggregateTestResult::AggregateTestResult( - const AggregateTestResult& other) = default; - -TestResultsTracker::AggregateTestResult::~AggregateTestResult() = default; - -TestResultsTracker::PerIterationData::PerIterationData() = default; - -TestResultsTracker::PerIterationData::PerIterationData( - const PerIterationData& other) = default; - -TestResultsTracker::PerIterationData::~PerIterationData() = default; - -} // namespace base
diff --git a/base/test/launcher/test_results_tracker.h b/base/test/launcher/test_results_tracker.h deleted file mode 100644 index d89821d..0000000 --- a/base/test/launcher/test_results_tracker.h +++ /dev/null
@@ -1,149 +0,0 @@ -// Copyright 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef BASE_TEST_LAUNCHER_TEST_RESULTS_TRACKER_H_ -#define BASE_TEST_LAUNCHER_TEST_RESULTS_TRACKER_H_ - -#include <map> -#include <set> -#include <string> -#include <vector> - -#include "base/callback.h" -#include "base/macros.h" -#include "base/test/launcher/test_result.h" -#include "base/threading/thread_checker.h" - -namespace base { - -class CommandLine; -class FilePath; - -// A helper class to output results. -// Note: as currently XML is the only supported format by gtest, we don't -// check output format (e.g. "xml:" prefix) here and output an XML file -// unconditionally. -// Note: we don't output per-test-case or total summary info like -// total failed_test_count, disabled_test_count, elapsed_time and so on. -// Only each test (testcase element in the XML) will have the correct -// failed/disabled/elapsed_time information. Each test won't include -// detailed failure messages either. -class TestResultsTracker { - public: - TestResultsTracker(); - ~TestResultsTracker(); - - // Initialize the result tracker. Must be called exactly once before - // calling any other methods. Returns true on success. - bool Init(const CommandLine& command_line) WARN_UNUSED_RESULT; - - // Called when a test iteration is starting. - void OnTestIterationStarting(); - - // Adds |test_name| to the set of discovered tests (this includes all tests - // present in the executable, not necessarily run). - void AddTest(const std::string& test_name); - - // Adds |test_name| to the set of disabled tests. - void AddDisabledTest(const std::string& test_name); - - // Adds location for the |test_name|. - void AddTestLocation(const std::string& test_name, - const std::string& file, - int line); - - // Adds |result| to the stored test results. - void AddTestResult(const TestResult& result); - - // Prints a summary of current test iteration to stdout. - void PrintSummaryOfCurrentIteration() const; - - // Prints a summary of all test iterations (not just the last one) to stdout. - void PrintSummaryOfAllIterations() const; - - // Adds a string tag to the JSON summary. This is intended to indicate - // conditions that affect the entire test run, as opposed to individual tests. - void AddGlobalTag(const std::string& tag); - - // Saves a JSON summary of all test iterations results to |path|. Adds - // |additional_tags| to the summary (just for this invocation). Returns - // true on success. - bool SaveSummaryAsJSON( - const FilePath& path, - const std::vector<std::string>& additional_tags) const WARN_UNUSED_RESULT; - - // Map where keys are test result statuses, and values are sets of tests - // which finished with that status. - typedef std::map<TestResult::Status, std::set<std::string> > TestStatusMap; - - // Returns a test status map (see above) for current test iteration. - TestStatusMap GetTestStatusMapForCurrentIteration() const; - - // Returns a test status map (see above) for all test iterations. - TestStatusMap GetTestStatusMapForAllIterations() const; - - private: - void GetTestStatusForIteration(int iteration, TestStatusMap* map) const; - - template<typename InputIterator> - void PrintTests(InputIterator first, - InputIterator last, - const std::string& description) const; - - struct AggregateTestResult { - AggregateTestResult(); - AggregateTestResult(const AggregateTestResult& other); - ~AggregateTestResult(); - - std::vector<TestResult> test_results; - }; - - struct PerIterationData { - PerIterationData(); - PerIterationData(const PerIterationData& other); - ~PerIterationData(); - - // Aggregate test results grouped by full test name. - typedef std::map<std::string, AggregateTestResult> ResultsMap; - ResultsMap results; - }; - - struct CodeLocation { - CodeLocation(const std::string& f, int l) : file(f), line(l) { - } - - std::string file; - int line; - }; - - ThreadChecker thread_checker_; - - // Set of global tags, i.e. strings indicating conditions that apply to - // the entire test run. - std::set<std::string> global_tags_; - - // Set of all test names discovered in the current executable. - std::set<std::string> all_tests_; - - std::map<std::string, CodeLocation> test_locations_; - - // Set of all disabled tests in the current executable. - std::set<std::string> disabled_tests_; - - // Store test results for each iteration. - std::vector<PerIterationData> per_iteration_data_; - - // Index of current iteration (starting from 0). -1 before the first - // iteration. - int iteration_; - - // File handle of output file (can be NULL if no file). - FILE* out_; - - DISALLOW_COPY_AND_ASSIGN(TestResultsTracker); -}; - -} // namespace base - -#endif // BASE_TEST_LAUNCHER_TEST_RESULTS_TRACKER_H_
diff --git a/base/test/launcher/unit_test_launcher.cc b/base/test/launcher/unit_test_launcher.cc deleted file mode 100644 index 230ecc3..0000000 --- a/base/test/launcher/unit_test_launcher.cc +++ /dev/null
@@ -1,750 +0,0 @@ -// Copyright 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "base/test/launcher/unit_test_launcher.h" - -#include <map> -#include <memory> -#include <utility> - -#include "base/base_switches.h" -#include "base/bind.h" -#include "base/callback_helpers.h" -#include "base/command_line.h" -#include "base/compiler_specific.h" -#include "base/debug/debugger.h" -#include "base/files/file_util.h" -#include "base/files/scoped_temp_dir.h" -#include "base/format_macros.h" -#include "base/location.h" -#include "base/macros.h" -#include "base/message_loop/message_loop.h" -#include "base/sequence_checker.h" -#include "base/single_thread_task_runner.h" -#include "base/stl_util.h" -#include "base/strings/string_number_conversions.h" -#include "base/strings/string_util.h" -#include "base/sys_info.h" -#include "base/test/gtest_xml_util.h" -#include "base/test/launcher/test_launcher.h" -#include "base/test/test_switches.h" -#include "base/test/test_timeouts.h" -#include "base/third_party/dynamic_annotations/dynamic_annotations.h" -#include "base/threading/thread_checker.h" -#include "base/threading/thread_task_runner_handle.h" -#include "build_config.h" -#include "testing/gtest/include/gtest/gtest.h" - -#if defined(OS_POSIX) -#include "base/files/file_descriptor_watcher_posix.h" -#endif - -namespace base { - -namespace { - -// This constant controls how many tests are run in a single batch by default. -const size_t kDefaultTestBatchLimit = 10; - -const char kHelpFlag[] = "help"; - -// Flag to run all tests in a single process. -const char kSingleProcessTestsFlag[] = "single-process-tests"; - -void PrintUsage() { - fprintf(stdout, - "Runs tests using the gtest framework, each batch of tests being\n" - "run in their own process. Supported command-line flags:\n" - "\n" - " Common flags:\n" - " --gtest_filter=...\n" - " Runs a subset of tests (see --gtest_help for more info).\n" - "\n" - " --help\n" - " Shows this message.\n" - "\n" - " --gtest_help\n" - " Shows the gtest help message.\n" - "\n" - " --test-launcher-jobs=N\n" - " Sets the number of parallel test jobs to N.\n" - "\n" - " --single-process-tests\n" - " Runs the tests and the launcher in the same process. Useful\n" - " for debugging a specific test in a debugger.\n" - "\n" - " Other flags:\n" - " --test-launcher-filter-file=PATH\n" - " Like --gtest_filter, but read the test filter from PATH.\n" - " One pattern per line; lines starting with '-' are exclusions.\n" - " See also //testing/buildbot/filters/README.md file.\n" - "\n" - " --test-launcher-batch-limit=N\n" - " Sets the limit of test batch to run in a single process to N.\n" - "\n" - " --test-launcher-debug-launcher\n" - " Disables autodetection of debuggers and similar tools,\n" - " making it possible to use them to debug launcher itself.\n" - "\n" - " --test-launcher-retry-limit=N\n" - " Sets the limit of test retries on failures to N.\n" - "\n" - " --test-launcher-summary-output=PATH\n" - " Saves a JSON machine-readable summary of the run.\n" - "\n" - " --test-launcher-print-test-stdio=auto|always|never\n" - " Controls when full test output is printed.\n" - " auto means to print it when the test failed.\n" - "\n" - " --test-launcher-test-part-results-limit=N\n" - " Sets the limit of failed EXPECT/ASSERT entries in the xml and\n" - " JSON outputs per test to N (default N=10). Negative value \n" - " will disable this limit.\n" - "\n" - " --test-launcher-total-shards=N\n" - " Sets the total number of shards to N.\n" - "\n" - " --test-launcher-shard-index=N\n" - " Sets the shard index to run to N (from 0 to TOTAL - 1).\n"); - fflush(stdout); -} - -class DefaultUnitTestPlatformDelegate : public UnitTestPlatformDelegate { - public: - DefaultUnitTestPlatformDelegate() = default; - - private: - // UnitTestPlatformDelegate: - bool GetTests(std::vector<TestIdentifier>* output) override { - *output = GetCompiledInTests(); - return true; - } - - bool CreateResultsFile(base::FilePath* path) override { - if (!CreateNewTempDirectory(FilePath::StringType(), path)) - return false; - *path = path->AppendASCII("test_results.xml"); - return true; - } - - bool CreateTemporaryFile(base::FilePath* path) override { - if (!temp_dir_.IsValid() && !temp_dir_.CreateUniqueTempDir()) - return false; - return CreateTemporaryFileInDir(temp_dir_.GetPath(), path); - } - - CommandLine GetCommandLineForChildGTestProcess( - const std::vector<std::string>& test_names, - const base::FilePath& output_file, - const base::FilePath& flag_file) override { - CommandLine new_cmd_line(*CommandLine::ForCurrentProcess()); - - CHECK(base::PathExists(flag_file)); - - std::string long_flags( - std::string("--") + kGTestFilterFlag + "=" + - JoinString(test_names, ":")); - CHECK_EQ(static_cast<int>(long_flags.size()), - WriteFile(flag_file, long_flags.data(), - static_cast<int>(long_flags.size()))); - - new_cmd_line.AppendSwitchPath(switches::kTestLauncherOutput, output_file); - new_cmd_line.AppendSwitchPath(kGTestFlagfileFlag, flag_file); - new_cmd_line.AppendSwitch(kSingleProcessTestsFlag); - - return new_cmd_line; - } - - std::string GetWrapperForChildGTestProcess() override { - return std::string(); - } - - void RelaunchTests(TestLauncher* test_launcher, - const std::vector<std::string>& test_names, - int launch_flags) override { - // Relaunch requested tests in parallel, but only use single - // test per batch for more precise results (crashes, etc). - for (const std::string& test_name : test_names) { - std::vector<std::string> batch; - batch.push_back(test_name); - RunUnitTestsBatch(test_launcher, this, batch, launch_flags); - } - } - - ScopedTempDir temp_dir_; - - DISALLOW_COPY_AND_ASSIGN(DefaultUnitTestPlatformDelegate); -}; - -bool GetSwitchValueAsInt(const std::string& switch_name, int* result) { - if (!CommandLine::ForCurrentProcess()->HasSwitch(switch_name)) - return true; - - std::string switch_value = - CommandLine::ForCurrentProcess()->GetSwitchValueASCII(switch_name); - if (!StringToInt(switch_value, result) || *result < 0) { - LOG(ERROR) << "Invalid value for " << switch_name << ": " << switch_value; - return false; - } - - return true; -} - -int LaunchUnitTestsInternal(RunTestSuiteCallback run_test_suite, - size_t parallel_jobs, - int default_batch_limit, - bool use_job_objects, - OnceClosure gtest_init) { -#if defined(OS_ANDROID) - // We can't easily fork on Android, just run the test suite directly. - return std::move(run_test_suite).Run(); -#else - bool force_single_process = false; - if (CommandLine::ForCurrentProcess()->HasSwitch( - switches::kTestLauncherDebugLauncher)) { - fprintf(stdout, "Forcing test launcher debugging mode.\n"); - fflush(stdout); - } else { - if (base::debug::BeingDebugged()) { - fprintf(stdout, - "Debugger detected, switching to single process mode.\n" - "Pass --test-launcher-debug-launcher to debug the launcher " - "itself.\n"); - fflush(stdout); - force_single_process = true; - } - } - - if (CommandLine::ForCurrentProcess()->HasSwitch(kGTestHelpFlag) || - CommandLine::ForCurrentProcess()->HasSwitch(kGTestListTestsFlag) || - CommandLine::ForCurrentProcess()->HasSwitch(kSingleProcessTestsFlag) || - CommandLine::ForCurrentProcess()->HasSwitch( - switches::kTestChildProcess) || - force_single_process) { - return std::move(run_test_suite).Run(); - } -#endif - - if (CommandLine::ForCurrentProcess()->HasSwitch(kHelpFlag)) { - PrintUsage(); - return 0; - } - - TimeTicks start_time(TimeTicks::Now()); - - std::move(gtest_init).Run(); - TestTimeouts::Initialize(); - - int batch_limit = default_batch_limit; - if (!GetSwitchValueAsInt(switches::kTestLauncherBatchLimit, &batch_limit)) - return 1; - - fprintf(stdout, - "IMPORTANT DEBUGGING NOTE: batches of tests are run inside their\n" - "own process. For debugging a test inside a debugger, use the\n" - "--gtest_filter=<your_test_name> flag along with\n" - "--single-process-tests.\n"); - fflush(stdout); - - MessageLoopForIO message_loop; -#if defined(OS_POSIX) - FileDescriptorWatcher file_descriptor_watcher(&message_loop); -#endif - - DefaultUnitTestPlatformDelegate platform_delegate; - UnitTestLauncherDelegate delegate( - &platform_delegate, batch_limit, use_job_objects); - TestLauncher launcher(&delegate, parallel_jobs); - bool success = launcher.Run(); - - fprintf(stdout, "Tests took %" PRId64 " seconds.\n", - (TimeTicks::Now() - start_time).InSeconds()); - fflush(stdout); - - return (success ? 0 : 1); -} - -void InitGoogleTestChar(int* argc, char** argv) { - testing::InitGoogleTest(argc, argv); -} - -#if defined(OS_WIN) -void InitGoogleTestWChar(int* argc, wchar_t** argv) { - testing::InitGoogleTest(argc, argv); -} -#endif // defined(OS_WIN) - -// Interprets test results and reports to the test launcher. Returns true -// on success. -bool ProcessTestResults( - TestLauncher* test_launcher, - const std::vector<std::string>& test_names, - const base::FilePath& output_file, - const std::string& output, - int exit_code, - bool was_timeout, - std::vector<std::string>* tests_to_relaunch) { - std::vector<TestResult> test_results; - bool crashed = false; - bool have_test_results = - ProcessGTestOutput(output_file, &test_results, &crashed); - - bool called_any_callback = false; - - if (have_test_results) { - // TODO(phajdan.jr): Check for duplicates and mismatches between - // the results we got from XML file and tests we intended to run. - std::map<std::string, TestResult> results_map; - for (size_t i = 0; i < test_results.size(); i++) - results_map[test_results[i].full_name] = test_results[i]; - - bool had_interrupted_test = false; - - // Results to be reported back to the test launcher. - std::vector<TestResult> final_results; - - for (size_t i = 0; i < test_names.size(); i++) { - if (ContainsKey(results_map, test_names[i])) { - TestResult test_result = results_map[test_names[i]]; - if (test_result.status == TestResult::TEST_CRASH) { - had_interrupted_test = true; - - if (was_timeout) { - // Fix up the test status: we forcibly kill the child process - // after the timeout, so from XML results it looks just like - // a crash. - test_result.status = TestResult::TEST_TIMEOUT; - } - } else if (test_result.status == TestResult::TEST_SUCCESS || - test_result.status == TestResult::TEST_FAILURE) { - // We run multiple tests in a batch with a timeout applied - // to the entire batch. It is possible that with other tests - // running quickly some tests take longer than the per-test timeout. - // For consistent handling of tests independent of order and other - // factors, mark them as timing out. - if (test_result.elapsed_time > - TestTimeouts::test_launcher_timeout()) { - test_result.status = TestResult::TEST_TIMEOUT; - } - } - test_result.output_snippet = GetTestOutputSnippet(test_result, output); - final_results.push_back(test_result); - } else if (had_interrupted_test) { - tests_to_relaunch->push_back(test_names[i]); - } else { - // TODO(phajdan.jr): Explicitly pass the info that the test didn't - // run for a mysterious reason. - LOG(ERROR) << "no test result for " << test_names[i]; - TestResult test_result; - test_result.full_name = test_names[i]; - test_result.status = TestResult::TEST_UNKNOWN; - test_result.output_snippet = GetTestOutputSnippet(test_result, output); - final_results.push_back(test_result); - } - } - - // TODO(phajdan.jr): Handle the case where processing XML output - // indicates a crash but none of the test results is marked as crashing. - - if (final_results.empty()) - return false; - - bool has_non_success_test = false; - for (size_t i = 0; i < final_results.size(); i++) { - if (final_results[i].status != TestResult::TEST_SUCCESS) { - has_non_success_test = true; - break; - } - } - - if (!has_non_success_test && exit_code != 0) { - // This is a bit surprising case: all tests are marked as successful, - // but the exit code was not zero. This can happen e.g. under memory - // tools that report leaks this way. Mark all tests as a failure on exit, - // and for more precise info they'd need to be retried serially. - for (size_t i = 0; i < final_results.size(); i++) - final_results[i].status = TestResult::TEST_FAILURE_ON_EXIT; - } - - for (size_t i = 0; i < final_results.size(); i++) { - // Fix the output snippet after possible changes to the test result. - final_results[i].output_snippet = - GetTestOutputSnippet(final_results[i], output); - test_launcher->OnTestFinished(final_results[i]); - called_any_callback = true; - } - } else { - fprintf(stdout, - "Failed to get out-of-band test success data, " - "dumping full stdio below:\n%s\n", - output.c_str()); - fflush(stdout); - - // We do not have reliable details about test results (parsing test - // stdout is known to be unreliable). - if (test_names.size() == 1) { - // There is only one test. Try to determine status by exit code. - const std::string& test_name = test_names.front(); - TestResult test_result; - test_result.full_name = test_name; - - if (was_timeout) { - test_result.status = TestResult::TEST_TIMEOUT; - } else if (exit_code != 0) { - test_result.status = TestResult::TEST_FAILURE; - } else { - // It's strange case when test executed successfully, - // but we failed to read machine-readable report for it. - test_result.status = TestResult::TEST_UNKNOWN; - } - - test_launcher->OnTestFinished(test_result); - called_any_callback = true; - } else { - // There is more than one test. Retry them individually. - for (const std::string& test_name : test_names) - tests_to_relaunch->push_back(test_name); - } - } - - return called_any_callback; -} - -class UnitTestProcessLifetimeObserver : public ProcessLifetimeObserver { - public: - ~UnitTestProcessLifetimeObserver() override { - DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - } - - TestLauncher* test_launcher() { return test_launcher_; } - UnitTestPlatformDelegate* platform_delegate() { return platform_delegate_; } - const std::vector<std::string>& test_names() { return test_names_; } - int launch_flags() { return launch_flags_; } - const FilePath& output_file() { return output_file_; } - const FilePath& flag_file() { return flag_file_; } - - protected: - UnitTestProcessLifetimeObserver(TestLauncher* test_launcher, - UnitTestPlatformDelegate* platform_delegate, - const std::vector<std::string>& test_names, - int launch_flags, - const FilePath& output_file, - const FilePath& flag_file) - : ProcessLifetimeObserver(), - test_launcher_(test_launcher), - platform_delegate_(platform_delegate), - test_names_(test_names), - launch_flags_(launch_flags), - output_file_(output_file), - flag_file_(flag_file) {} - - SEQUENCE_CHECKER(sequence_checker_); - - private: - TestLauncher* const test_launcher_; - UnitTestPlatformDelegate* const platform_delegate_; - const std::vector<std::string> test_names_; - const int launch_flags_; - const FilePath output_file_; - const FilePath flag_file_; - - DISALLOW_COPY_AND_ASSIGN(UnitTestProcessLifetimeObserver); -}; - -class ParallelUnitTestProcessLifetimeObserver - : public UnitTestProcessLifetimeObserver { - public: - ParallelUnitTestProcessLifetimeObserver( - TestLauncher* test_launcher, - UnitTestPlatformDelegate* platform_delegate, - const std::vector<std::string>& test_names, - int launch_flags, - const FilePath& output_file, - const FilePath& flag_file) - : UnitTestProcessLifetimeObserver(test_launcher, - platform_delegate, - test_names, - launch_flags, - output_file, - flag_file) {} - ~ParallelUnitTestProcessLifetimeObserver() override = default; - - private: - // ProcessLifetimeObserver: - void OnCompleted(int exit_code, - TimeDelta elapsed_time, - bool was_timeout, - const std::string& output) override; - - DISALLOW_COPY_AND_ASSIGN(ParallelUnitTestProcessLifetimeObserver); -}; - -void ParallelUnitTestProcessLifetimeObserver::OnCompleted( - int exit_code, - TimeDelta elapsed_time, - bool was_timeout, - const std::string& output) { - DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - std::vector<std::string> tests_to_relaunch; - ProcessTestResults(test_launcher(), test_names(), output_file(), output, - exit_code, was_timeout, &tests_to_relaunch); - - if (!tests_to_relaunch.empty()) { - platform_delegate()->RelaunchTests(test_launcher(), tests_to_relaunch, - launch_flags()); - } - - // The temporary file's directory is also temporary. - DeleteFile(output_file().DirName(), true); - if (!flag_file().empty()) - DeleteFile(flag_file(), false); -} - -class SerialUnitTestProcessLifetimeObserver - : public UnitTestProcessLifetimeObserver { - public: - SerialUnitTestProcessLifetimeObserver( - TestLauncher* test_launcher, - UnitTestPlatformDelegate* platform_delegate, - const std::vector<std::string>& test_names, - int launch_flags, - const FilePath& output_file, - const FilePath& flag_file, - std::vector<std::string>&& next_test_names) - : UnitTestProcessLifetimeObserver(test_launcher, - platform_delegate, - test_names, - launch_flags, - output_file, - flag_file), - next_test_names_(std::move(next_test_names)) {} - ~SerialUnitTestProcessLifetimeObserver() override = default; - - private: - // ProcessLifetimeObserver: - void OnCompleted(int exit_code, - TimeDelta elapsed_time, - bool was_timeout, - const std::string& output) override; - - std::vector<std::string> next_test_names_; - - DISALLOW_COPY_AND_ASSIGN(SerialUnitTestProcessLifetimeObserver); -}; - -void SerialUnitTestProcessLifetimeObserver::OnCompleted( - int exit_code, - TimeDelta elapsed_time, - bool was_timeout, - const std::string& output) { - DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - std::vector<std::string> tests_to_relaunch; - bool called_any_callbacks = - ProcessTestResults(test_launcher(), test_names(), output_file(), output, - exit_code, was_timeout, &tests_to_relaunch); - - // There is only one test, there cannot be other tests to relaunch - // due to a crash. - DCHECK(tests_to_relaunch.empty()); - - // There is only one test, we should have called back with its result. - DCHECK(called_any_callbacks); - - // The temporary file's directory is also temporary. - DeleteFile(output_file().DirName(), true); - - if (!flag_file().empty()) - DeleteFile(flag_file(), false); - - ThreadTaskRunnerHandle::Get()->PostTask( - FROM_HERE, - BindOnce(&RunUnitTestsSerially, test_launcher(), platform_delegate(), - std::move(next_test_names_), launch_flags())); -} - -} // namespace - -int LaunchUnitTests(int argc, - char** argv, - RunTestSuiteCallback run_test_suite) { - CommandLine::Init(argc, argv); - size_t parallel_jobs = NumParallelJobs(); - if (parallel_jobs == 0U) { - return 1; - } - return LaunchUnitTestsInternal(std::move(run_test_suite), parallel_jobs, - kDefaultTestBatchLimit, true, - BindOnce(&InitGoogleTestChar, &argc, argv)); -} - -int LaunchUnitTestsSerially(int argc, - char** argv, - RunTestSuiteCallback run_test_suite) { - CommandLine::Init(argc, argv); - return LaunchUnitTestsInternal(std::move(run_test_suite), 1U, - kDefaultTestBatchLimit, true, - BindOnce(&InitGoogleTestChar, &argc, argv)); -} - -int LaunchUnitTestsWithOptions(int argc, - char** argv, - size_t parallel_jobs, - int default_batch_limit, - bool use_job_objects, - RunTestSuiteCallback run_test_suite) { - CommandLine::Init(argc, argv); - return LaunchUnitTestsInternal(std::move(run_test_suite), parallel_jobs, - default_batch_limit, use_job_objects, - BindOnce(&InitGoogleTestChar, &argc, argv)); -} - -#if defined(OS_WIN) -int LaunchUnitTests(int argc, - wchar_t** argv, - bool use_job_objects, - RunTestSuiteCallback run_test_suite) { - // Windows CommandLine::Init ignores argv anyway. - CommandLine::Init(argc, NULL); - size_t parallel_jobs = NumParallelJobs(); - if (parallel_jobs == 0U) { - return 1; - } - return LaunchUnitTestsInternal(std::move(run_test_suite), parallel_jobs, - kDefaultTestBatchLimit, use_job_objects, - BindOnce(&InitGoogleTestWChar, &argc, argv)); -} -#endif // defined(OS_WIN) - -void RunUnitTestsSerially( - TestLauncher* test_launcher, - UnitTestPlatformDelegate* platform_delegate, - const std::vector<std::string>& test_names, - int launch_flags) { - if (test_names.empty()) - return; - - // Create a dedicated temporary directory to store the xml result data - // per run to ensure clean state and make it possible to launch multiple - // processes in parallel. - FilePath output_file; - CHECK(platform_delegate->CreateResultsFile(&output_file)); - FilePath flag_file; - platform_delegate->CreateTemporaryFile(&flag_file); - - auto observer = std::make_unique<SerialUnitTestProcessLifetimeObserver>( - test_launcher, platform_delegate, - std::vector<std::string>(1, test_names.back()), launch_flags, output_file, - flag_file, - std::vector<std::string>(test_names.begin(), test_names.end() - 1)); - - CommandLine cmd_line(platform_delegate->GetCommandLineForChildGTestProcess( - observer->test_names(), output_file, flag_file)); - - TestLauncher::LaunchOptions launch_options; - launch_options.flags = launch_flags; - test_launcher->LaunchChildGTestProcess( - cmd_line, platform_delegate->GetWrapperForChildGTestProcess(), - TestTimeouts::test_launcher_timeout(), launch_options, - std::move(observer)); -} - -void RunUnitTestsBatch( - TestLauncher* test_launcher, - UnitTestPlatformDelegate* platform_delegate, - const std::vector<std::string>& test_names, - int launch_flags) { - if (test_names.empty()) - return; - - // Create a dedicated temporary directory to store the xml result data - // per run to ensure clean state and make it possible to launch multiple - // processes in parallel. - FilePath output_file; - CHECK(platform_delegate->CreateResultsFile(&output_file)); - FilePath flag_file; - platform_delegate->CreateTemporaryFile(&flag_file); - - auto observer = std::make_unique<ParallelUnitTestProcessLifetimeObserver>( - test_launcher, platform_delegate, test_names, launch_flags, output_file, - flag_file); - - CommandLine cmd_line(platform_delegate->GetCommandLineForChildGTestProcess( - test_names, output_file, flag_file)); - - // Adjust the timeout depending on how many tests we're running - // (note that e.g. the last batch of tests will be smaller). - // TODO(phajdan.jr): Consider an adaptive timeout, which can change - // depending on how many tests ran and how many remain. - // Note: do NOT parse child's stdout to do that, it's known to be - // unreliable (e.g. buffering issues can mix up the output). - TimeDelta timeout = test_names.size() * TestTimeouts::test_launcher_timeout(); - - TestLauncher::LaunchOptions options; - options.flags = launch_flags; - test_launcher->LaunchChildGTestProcess( - cmd_line, platform_delegate->GetWrapperForChildGTestProcess(), timeout, - options, std::move(observer)); -} - -UnitTestLauncherDelegate::UnitTestLauncherDelegate( - UnitTestPlatformDelegate* platform_delegate, - size_t batch_limit, - bool use_job_objects) - : platform_delegate_(platform_delegate), - batch_limit_(batch_limit), - use_job_objects_(use_job_objects) { -} - -UnitTestLauncherDelegate::~UnitTestLauncherDelegate() { - DCHECK(thread_checker_.CalledOnValidThread()); -} - -bool UnitTestLauncherDelegate::GetTests(std::vector<TestIdentifier>* output) { - DCHECK(thread_checker_.CalledOnValidThread()); - return platform_delegate_->GetTests(output); -} - -bool UnitTestLauncherDelegate::ShouldRunTest(const std::string& test_case_name, - const std::string& test_name) { - DCHECK(thread_checker_.CalledOnValidThread()); - - // There is no additional logic to disable specific tests. - return true; -} - -size_t UnitTestLauncherDelegate::RunTests( - TestLauncher* test_launcher, - const std::vector<std::string>& test_names) { - DCHECK(thread_checker_.CalledOnValidThread()); - - int launch_flags = use_job_objects_ ? TestLauncher::USE_JOB_OBJECTS : 0; - - std::vector<std::string> batch; - for (size_t i = 0; i < test_names.size(); i++) { - batch.push_back(test_names[i]); - - // Use 0 to indicate unlimited batch size. - if (batch.size() >= batch_limit_ && batch_limit_ != 0) { - RunUnitTestsBatch(test_launcher, platform_delegate_, batch, launch_flags); - batch.clear(); - } - } - - RunUnitTestsBatch(test_launcher, platform_delegate_, batch, launch_flags); - - return test_names.size(); -} - -size_t UnitTestLauncherDelegate::RetryTests( - TestLauncher* test_launcher, - const std::vector<std::string>& test_names) { - ThreadTaskRunnerHandle::Get()->PostTask( - FROM_HERE, - BindOnce(&RunUnitTestsSerially, test_launcher, platform_delegate_, - test_names, - use_job_objects_ ? TestLauncher::USE_JOB_OBJECTS : 0)); - return test_names.size(); -} - -} // namespace base
diff --git a/base/test/launcher/unit_test_launcher.h b/base/test/launcher/unit_test_launcher.h deleted file mode 100644 index 4e3d314..0000000 --- a/base/test/launcher/unit_test_launcher.h +++ /dev/null
@@ -1,134 +0,0 @@ -// Copyright 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef BASE_TEST_LAUNCHER_UNIT_TEST_LAUNCHER_H_ -#define BASE_TEST_LAUNCHER_UNIT_TEST_LAUNCHER_H_ - -#include <stddef.h> - -#include <string> -#include <vector> - -#include "base/callback.h" -#include "base/files/file_path.h" -#include "base/macros.h" -#include "base/test/launcher/test_launcher.h" -#include "build_config.h" - -namespace base { - -// Callback that runs a test suite and returns exit code. -using RunTestSuiteCallback = OnceCallback<int(void)>; - -// Launches unit tests in given test suite. Returns exit code. -int LaunchUnitTests(int argc, char** argv, RunTestSuiteCallback run_test_suite); - -// Same as above, but always runs tests serially. -int LaunchUnitTestsSerially(int argc, - char** argv, - RunTestSuiteCallback run_test_suite); - -// Launches unit tests in given test suite. Returns exit code. -// |parallel_jobs| is the number of parallel test jobs. -// |default_batch_limit| is the default size of test batch -// (use 0 to disable batching). -// |use_job_objects| determines whether to use job objects. -int LaunchUnitTestsWithOptions(int argc, - char** argv, - size_t parallel_jobs, - int default_batch_limit, - bool use_job_objects, - RunTestSuiteCallback run_test_suite); - -#if defined(OS_WIN) -// Launches unit tests in given test suite. Returns exit code. -// |use_job_objects| determines whether to use job objects. -int LaunchUnitTests(int argc, - wchar_t** argv, - bool use_job_objects, - RunTestSuiteCallback run_test_suite); -#endif // defined(OS_WIN) - -// Delegate to abstract away platform differences for unit tests. -class UnitTestPlatformDelegate { - public: - // Called to get names of tests available for running. The delegate - // must put the result in |output| and return true on success. - virtual bool GetTests(std::vector<TestIdentifier>* output) = 0; - - // Called to create a temporary for storing test results. The delegate - // must put the resulting path in |path| and return true on success. - virtual bool CreateResultsFile(base::FilePath* path) = 0; - - // Called to create a new temporary file. The delegate must put the resulting - // path in |path| and return true on success. - virtual bool CreateTemporaryFile(base::FilePath* path) = 0; - - // Returns command line for child GTest process based on the command line - // of current process. |test_names| is a vector of test full names - // (e.g. "A.B"), |output_file| is path to the GTest XML output file. - virtual CommandLine GetCommandLineForChildGTestProcess( - const std::vector<std::string>& test_names, - const base::FilePath& output_file, - const base::FilePath& flag_file) = 0; - - // Returns wrapper to use for child GTest process. Empty string means - // no wrapper. - virtual std::string GetWrapperForChildGTestProcess() = 0; - - // Relaunch tests, e.g. after a crash. - virtual void RelaunchTests(TestLauncher* test_launcher, - const std::vector<std::string>& test_names, - int launch_flags) = 0; - - protected: - ~UnitTestPlatformDelegate() = default; -}; - -// Runs tests serially, each in its own process. -void RunUnitTestsSerially(TestLauncher* test_launcher, - UnitTestPlatformDelegate* platform_delegate, - const std::vector<std::string>& test_names, - int launch_flags); - -// Runs tests in batches (each batch in its own process). -void RunUnitTestsBatch(TestLauncher* test_launcher, - UnitTestPlatformDelegate* platform_delegate, - const std::vector<std::string>& test_names, - int launch_flags); - -// Test launcher delegate for unit tests (mostly to support batching). -class UnitTestLauncherDelegate : public TestLauncherDelegate { - public: - UnitTestLauncherDelegate(UnitTestPlatformDelegate* delegate, - size_t batch_limit, - bool use_job_objects); - ~UnitTestLauncherDelegate() override; - - private: - // TestLauncherDelegate: - bool GetTests(std::vector<TestIdentifier>* output) override; - bool ShouldRunTest(const std::string& test_case_name, - const std::string& test_name) override; - size_t RunTests(TestLauncher* test_launcher, - const std::vector<std::string>& test_names) override; - size_t RetryTests(TestLauncher* test_launcher, - const std::vector<std::string>& test_names) override; - - ThreadChecker thread_checker_; - - UnitTestPlatformDelegate* platform_delegate_; - - // Maximum number of tests to run in a single batch. - size_t batch_limit_; - - // Determines whether we use job objects on Windows. - bool use_job_objects_; - - DISALLOW_COPY_AND_ASSIGN(UnitTestLauncherDelegate); -}; - -} // namespace base - -#endif // BASE_TEST_LAUNCHER_UNIT_TEST_LAUNCHER_H_
diff --git a/base/test/launcher/unit_test_launcher_nacl_nonsfi.cc b/base/test/launcher/unit_test_launcher_nacl_nonsfi.cc deleted file mode 100644 index 237a3da..0000000 --- a/base/test/launcher/unit_test_launcher_nacl_nonsfi.cc +++ /dev/null
@@ -1,51 +0,0 @@ -// Copyright 2015 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "base/test/launcher/unit_test_launcher.h" - -#include "base/command_line.h" -#include "base/files/file_util.h" -#include "base/test/gtest_util.h" -#include "base/test/gtest_xml_unittest_result_printer.h" -#include "base/test/test_switches.h" -#include "testing/gtest/include/gtest/gtest.h" - -namespace base { - -int LaunchUnitTests(int argc, - char** argv, - RunTestSuiteCallback run_test_suite) { - CHECK(CommandLine::InitializedForCurrentProcess() || - CommandLine::Init(argc, argv)); - const CommandLine* command_line = CommandLine::ForCurrentProcess(); - if (command_line->HasSwitch(switches::kTestLauncherListTests)) { - // Dump all test list into a file. - FilePath list_path( - command_line->GetSwitchValuePath(switches::kTestLauncherListTests)); - if (!WriteCompiledInTestsToFile(list_path)) { - LOG(ERROR) << "Failed to write list of tests."; - return 1; - } - - // Successfully done. - return 0; - } - - // Register XML output printer, if --test-launcher-output flag is set. - if (command_line->HasSwitch(switches::kTestLauncherOutput)) { - FilePath output_path = command_line->GetSwitchValuePath( - switches::kTestLauncherOutput); - if (PathExists(output_path)) { - LOG(WARNING) << "Test launcher output path exists. Do not override"; - } else { - XmlUnitTestResultPrinter* printer = new XmlUnitTestResultPrinter; - CHECK(printer->Initialize(output_path)); - testing::UnitTest::GetInstance()->listeners().Append(printer); - } - } - - return std::move(run_test_suite).Run(); -} - -} // namespace base
diff --git a/base/test/malloc_wrapper.cc b/base/test/malloc_wrapper.cc deleted file mode 100644 index eb280a3..0000000 --- a/base/test/malloc_wrapper.cc +++ /dev/null
@@ -1,11 +0,0 @@ -// Copyright 2015 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "malloc_wrapper.h" - -#include <stdlib.h> - -void* MallocWrapper(size_t size) { - return malloc(size); -}
diff --git a/base/test/malloc_wrapper.h b/base/test/malloc_wrapper.h deleted file mode 100644 index d06228d..0000000 --- a/base/test/malloc_wrapper.h +++ /dev/null
@@ -1,21 +0,0 @@ -// Copyright 2015 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef BASE_TEST_MALLOC_WRAPPER_H_ -#define BASE_TEST_MALLOC_WRAPPER_H_ - -#include <stddef.h> - -// BASE_EXPORT depends on COMPONENT_BUILD. -// This will always be a separate shared library, so don't use BASE_EXPORT here. -#if defined(WIN32) -#define MALLOC_WRAPPER_EXPORT __declspec(dllexport) -#else -#define MALLOC_WRAPPER_EXPORT __attribute__((visibility("default"))) -#endif // defined(WIN32) - -// Calls malloc directly. -MALLOC_WRAPPER_EXPORT void* MallocWrapper(size_t size); - -#endif // BASE_TEST_MALLOC_WRAPPER_H_
diff --git a/base/test/mock_callback.h b/base/test/mock_callback.h deleted file mode 100644 index 7ac4d34..0000000 --- a/base/test/mock_callback.h +++ /dev/null
@@ -1,366 +0,0 @@ -// This file was GENERATED by command: -// pump.py mock_callback.h.pump -// DO NOT EDIT BY HAND!!! - -// Copyright 2017 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -// Analogous to GMock's built-in MockFunction, but for base::Callback instead of -// std::function. It takes the full callback type as a parameter, so that it can -// support both OnceCallback and RepeatingCallback. -// -// Use: -// using FooCallback = base::Callback<int(std::string)>; -// -// TEST(FooTest, RunsCallbackWithBarArgument) { -// base::MockCallback<FooCallback> callback; -// EXPECT_CALL(callback, Run("bar")).WillOnce(Return(1)); -// Foo(callback.Get()); -// } -// -// Can be used with StrictMock and NiceMock. Caller must ensure that it outlives -// any base::Callback obtained from it. - -#ifndef BASE_TEST_MOCK_CALLBACK_H_ -#define BASE_TEST_MOCK_CALLBACK_H_ - -#include "base/bind.h" -#include "base/callback.h" -#include "base/macros.h" -#include "testing/gmock/include/gmock/gmock.h" - -namespace base { - -// clang-format off - -template <typename F> -class MockCallback; - -template <typename R> -class MockCallback<Callback<R()>> { - public: - MockCallback() = default; - MOCK_METHOD0_T(Run, R()); - - Callback<R()> Get() { - return Bind(&MockCallback::Run, Unretained(this)); - } - - private: - DISALLOW_COPY_AND_ASSIGN(MockCallback); -}; - -template <typename R> -class MockCallback<OnceCallback<R()>> { - public: - MockCallback() = default; - MOCK_METHOD0_T(Run, R()); - - OnceCallback<R()> Get() { - return BindOnce(&MockCallback::Run, Unretained(this)); - } - - private: - DISALLOW_COPY_AND_ASSIGN(MockCallback); -}; - -template <typename R, typename A1> -class MockCallback<Callback<R(A1)>> { - public: - MockCallback() = default; - MOCK_METHOD1_T(Run, R(A1)); - - Callback<R(A1)> Get() { - return Bind(&MockCallback::Run, Unretained(this)); - } - - private: - DISALLOW_COPY_AND_ASSIGN(MockCallback); -}; - -template <typename R, typename A1> -class MockCallback<OnceCallback<R(A1)>> { - public: - MockCallback() = default; - MOCK_METHOD1_T(Run, R(A1)); - - OnceCallback<R(A1)> Get() { - return BindOnce(&MockCallback::Run, Unretained(this)); - } - - private: - DISALLOW_COPY_AND_ASSIGN(MockCallback); -}; - -template <typename R, typename A1, typename A2> -class MockCallback<Callback<R(A1, A2)>> { - public: - MockCallback() = default; - MOCK_METHOD2_T(Run, R(A1, A2)); - - Callback<R(A1, A2)> Get() { - return Bind(&MockCallback::Run, Unretained(this)); - } - - private: - DISALLOW_COPY_AND_ASSIGN(MockCallback); -}; - -template <typename R, typename A1, typename A2> -class MockCallback<OnceCallback<R(A1, A2)>> { - public: - MockCallback() = default; - MOCK_METHOD2_T(Run, R(A1, A2)); - - OnceCallback<R(A1, A2)> Get() { - return BindOnce(&MockCallback::Run, Unretained(this)); - } - - private: - DISALLOW_COPY_AND_ASSIGN(MockCallback); -}; - -template <typename R, typename A1, typename A2, typename A3> -class MockCallback<Callback<R(A1, A2, A3)>> { - public: - MockCallback() = default; - MOCK_METHOD3_T(Run, R(A1, A2, A3)); - - Callback<R(A1, A2, A3)> Get() { - return Bind(&MockCallback::Run, Unretained(this)); - } - - private: - DISALLOW_COPY_AND_ASSIGN(MockCallback); -}; - -template <typename R, typename A1, typename A2, typename A3> -class MockCallback<OnceCallback<R(A1, A2, A3)>> { - public: - MockCallback() = default; - MOCK_METHOD3_T(Run, R(A1, A2, A3)); - - OnceCallback<R(A1, A2, A3)> Get() { - return BindOnce(&MockCallback::Run, Unretained(this)); - } - - private: - DISALLOW_COPY_AND_ASSIGN(MockCallback); -}; - -template <typename R, typename A1, typename A2, typename A3, typename A4> -class MockCallback<Callback<R(A1, A2, A3, A4)>> { - public: - MockCallback() = default; - MOCK_METHOD4_T(Run, R(A1, A2, A3, A4)); - - Callback<R(A1, A2, A3, A4)> Get() { - return Bind(&MockCallback::Run, Unretained(this)); - } - - private: - DISALLOW_COPY_AND_ASSIGN(MockCallback); -}; - -template <typename R, typename A1, typename A2, typename A3, typename A4> -class MockCallback<OnceCallback<R(A1, A2, A3, A4)>> { - public: - MockCallback() = default; - MOCK_METHOD4_T(Run, R(A1, A2, A3, A4)); - - OnceCallback<R(A1, A2, A3, A4)> Get() { - return BindOnce(&MockCallback::Run, Unretained(this)); - } - - private: - DISALLOW_COPY_AND_ASSIGN(MockCallback); -}; - -template <typename R, typename A1, typename A2, typename A3, typename A4, - typename A5> -class MockCallback<Callback<R(A1, A2, A3, A4, A5)>> { - public: - MockCallback() = default; - MOCK_METHOD5_T(Run, R(A1, A2, A3, A4, A5)); - - Callback<R(A1, A2, A3, A4, A5)> Get() { - return Bind(&MockCallback::Run, Unretained(this)); - } - - private: - DISALLOW_COPY_AND_ASSIGN(MockCallback); -}; - -template <typename R, typename A1, typename A2, typename A3, typename A4, - typename A5> -class MockCallback<OnceCallback<R(A1, A2, A3, A4, A5)>> { - public: - MockCallback() = default; - MOCK_METHOD5_T(Run, R(A1, A2, A3, A4, A5)); - - OnceCallback<R(A1, A2, A3, A4, A5)> Get() { - return BindOnce(&MockCallback::Run, Unretained(this)); - } - - private: - DISALLOW_COPY_AND_ASSIGN(MockCallback); -}; - -template <typename R, typename A1, typename A2, typename A3, typename A4, - typename A5, typename A6> -class MockCallback<Callback<R(A1, A2, A3, A4, A5, A6)>> { - public: - MockCallback() = default; - MOCK_METHOD6_T(Run, R(A1, A2, A3, A4, A5, A6)); - - Callback<R(A1, A2, A3, A4, A5, A6)> Get() { - return Bind(&MockCallback::Run, Unretained(this)); - } - - private: - DISALLOW_COPY_AND_ASSIGN(MockCallback); -}; - -template <typename R, typename A1, typename A2, typename A3, typename A4, - typename A5, typename A6> -class MockCallback<OnceCallback<R(A1, A2, A3, A4, A5, A6)>> { - public: - MockCallback() = default; - MOCK_METHOD6_T(Run, R(A1, A2, A3, A4, A5, A6)); - - OnceCallback<R(A1, A2, A3, A4, A5, A6)> Get() { - return BindOnce(&MockCallback::Run, Unretained(this)); - } - - private: - DISALLOW_COPY_AND_ASSIGN(MockCallback); -}; - -template <typename R, typename A1, typename A2, typename A3, typename A4, - typename A5, typename A6, typename A7> -class MockCallback<Callback<R(A1, A2, A3, A4, A5, A6, A7)>> { - public: - MockCallback() = default; - MOCK_METHOD7_T(Run, R(A1, A2, A3, A4, A5, A6, A7)); - - Callback<R(A1, A2, A3, A4, A5, A6, A7)> Get() { - return Bind(&MockCallback::Run, Unretained(this)); - } - - private: - DISALLOW_COPY_AND_ASSIGN(MockCallback); -}; - -template <typename R, typename A1, typename A2, typename A3, typename A4, - typename A5, typename A6, typename A7> -class MockCallback<OnceCallback<R(A1, A2, A3, A4, A5, A6, A7)>> { - public: - MockCallback() = default; - MOCK_METHOD7_T(Run, R(A1, A2, A3, A4, A5, A6, A7)); - - OnceCallback<R(A1, A2, A3, A4, A5, A6, A7)> Get() { - return BindOnce(&MockCallback::Run, Unretained(this)); - } - - private: - DISALLOW_COPY_AND_ASSIGN(MockCallback); -}; - -template <typename R, typename A1, typename A2, typename A3, typename A4, - typename A5, typename A6, typename A7, typename A8> -class MockCallback<Callback<R(A1, A2, A3, A4, A5, A6, A7, A8)>> { - public: - MockCallback() = default; - MOCK_METHOD8_T(Run, R(A1, A2, A3, A4, A5, A6, A7, A8)); - - Callback<R(A1, A2, A3, A4, A5, A6, A7, A8)> Get() { - return Bind(&MockCallback::Run, Unretained(this)); - } - - private: - DISALLOW_COPY_AND_ASSIGN(MockCallback); -}; - -template <typename R, typename A1, typename A2, typename A3, typename A4, - typename A5, typename A6, typename A7, typename A8> -class MockCallback<OnceCallback<R(A1, A2, A3, A4, A5, A6, A7, A8)>> { - public: - MockCallback() = default; - MOCK_METHOD8_T(Run, R(A1, A2, A3, A4, A5, A6, A7, A8)); - - OnceCallback<R(A1, A2, A3, A4, A5, A6, A7, A8)> Get() { - return BindOnce(&MockCallback::Run, Unretained(this)); - } - - private: - DISALLOW_COPY_AND_ASSIGN(MockCallback); -}; - -template <typename R, typename A1, typename A2, typename A3, typename A4, - typename A5, typename A6, typename A7, typename A8, typename A9> -class MockCallback<Callback<R(A1, A2, A3, A4, A5, A6, A7, A8, A9)>> { - public: - MockCallback() = default; - MOCK_METHOD9_T(Run, R(A1, A2, A3, A4, A5, A6, A7, A8, A9)); - - Callback<R(A1, A2, A3, A4, A5, A6, A7, A8, A9)> Get() { - return Bind(&MockCallback::Run, Unretained(this)); - } - - private: - DISALLOW_COPY_AND_ASSIGN(MockCallback); -}; - -template <typename R, typename A1, typename A2, typename A3, typename A4, - typename A5, typename A6, typename A7, typename A8, typename A9> -class MockCallback<OnceCallback<R(A1, A2, A3, A4, A5, A6, A7, A8, A9)>> { - public: - MockCallback() = default; - MOCK_METHOD9_T(Run, R(A1, A2, A3, A4, A5, A6, A7, A8, A9)); - - OnceCallback<R(A1, A2, A3, A4, A5, A6, A7, A8, A9)> Get() { - return BindOnce(&MockCallback::Run, Unretained(this)); - } - - private: - DISALLOW_COPY_AND_ASSIGN(MockCallback); -}; - -template <typename R, typename A1, typename A2, typename A3, typename A4, - typename A5, typename A6, typename A7, typename A8, typename A9, - typename A10> -class MockCallback<Callback<R(A1, A2, A3, A4, A5, A6, A7, A8, A9, A10)>> { - public: - MockCallback() = default; - MOCK_METHOD10_T(Run, R(A1, A2, A3, A4, A5, A6, A7, A8, A9, A10)); - - Callback<R(A1, A2, A3, A4, A5, A6, A7, A8, A9, A10)> Get() { - return Bind(&MockCallback::Run, Unretained(this)); - } - - private: - DISALLOW_COPY_AND_ASSIGN(MockCallback); -}; - -template <typename R, typename A1, typename A2, typename A3, typename A4, - typename A5, typename A6, typename A7, typename A8, typename A9, - typename A10> -class MockCallback<OnceCallback<R(A1, A2, A3, A4, A5, A6, A7, A8, A9, A10)>> { - public: - MockCallback() = default; - MOCK_METHOD10_T(Run, R(A1, A2, A3, A4, A5, A6, A7, A8, A9, A10)); - - OnceCallback<R(A1, A2, A3, A4, A5, A6, A7, A8, A9, A10)> Get() { - return BindOnce(&MockCallback::Run, Unretained(this)); - } - - private: - DISALLOW_COPY_AND_ASSIGN(MockCallback); -}; - -// clang-format on - -} // namespace base - -#endif // BASE_TEST_MOCK_CALLBACK_H_
diff --git a/base/test/mock_callback.h.pump b/base/test/mock_callback.h.pump deleted file mode 100644 index 3372789..0000000 --- a/base/test/mock_callback.h.pump +++ /dev/null
@@ -1,85 +0,0 @@ -$$ This is a pump file for generating file templates. Pump is a python -$$ script that is part of the Google Test suite of utilities. Description -$$ can be found here: -$$ -$$ https://github.com/google/googletest/blob/master/googletest/docs/PumpManual.md -$$ -$$ MAX_ARITY controls the number of arguments that MockCallback supports. -$$ It is choosen to match the number GMock supports. -$var MAX_ARITY = 10 -$$ -// Copyright 2017 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -// Analogous to GMock's built-in MockFunction, but for base::Callback instead of -// std::function. It takes the full callback type as a parameter, so that it can -// support both OnceCallback and RepeatingCallback. -// -// Use: -// using FooCallback = base::Callback<int(std::string)>; -// -// TEST(FooTest, RunsCallbackWithBarArgument) { -// base::MockCallback<FooCallback> callback; -// EXPECT_CALL(callback, Run("bar")).WillOnce(Return(1)); -// Foo(callback.Get()); -// } -// -// Can be used with StrictMock and NiceMock. Caller must ensure that it outlives -// any base::Callback obtained from it. - -#ifndef BASE_TEST_MOCK_CALLBACK_H_ -#define BASE_TEST_MOCK_CALLBACK_H_ - -#include "base/bind.h" -#include "base/callback.h" -#include "base/macros.h" -#include "testing/gmock/include/gmock/gmock.h" - -namespace base { - -// clang-format off - -template <typename F> -class MockCallback; - -$range i 0..MAX_ARITY -$for i [[ -$range j 1..i -$var run_type = [[R($for j, [[A$j]])]] - -template <typename R$for j [[, typename A$j]]> -class MockCallback<Callback<$run_type>> { - public: - MockCallback() = default; - MOCK_METHOD$(i)_T(Run, $run_type); - - Callback<$run_type> Get() { - return Bind(&MockCallback::Run, Unretained(this)); - } - - private: - DISALLOW_COPY_AND_ASSIGN(MockCallback); -}; - -template <typename R$for j [[, typename A$j]]> -class MockCallback<OnceCallback<$run_type>> { - public: - MockCallback() = default; - MOCK_METHOD$(i)_T(Run, $run_type); - - OnceCallback<$run_type> Get() { - return BindOnce(&MockCallback::Run, Unretained(this)); - } - - private: - DISALLOW_COPY_AND_ASSIGN(MockCallback); -}; - -]] - -// clang-format on - -} // namespace base - -#endif // BASE_TEST_MOCK_CALLBACK_H_
diff --git a/base/test/mock_chrome_application_mac.h b/base/test/mock_chrome_application_mac.h deleted file mode 100644 index ffa3080..0000000 --- a/base/test/mock_chrome_application_mac.h +++ /dev/null
@@ -1,33 +0,0 @@ -// Copyright (c) 2011 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef BASE_TEST_MOCK_CHROME_APPLICATION_MAC_H_ -#define BASE_TEST_MOCK_CHROME_APPLICATION_MAC_H_ - -#if defined(__OBJC__) - -#import <AppKit/AppKit.h> - -#include "base/mac/scoped_sending_event.h" -#include "base/message_loop/message_pump_mac.h" - -// A basic implementation of CrAppProtocol and -// CrAppControlProtocol. This can be used in tests that need an -// NSApplication and use a runloop, or which need a ScopedSendingEvent -// when handling a nested event loop. -@interface MockCrApp : NSApplication<CrAppProtocol, - CrAppControlProtocol> { - @private - BOOL handlingSendEvent_; -} -@end - -#endif - -// To be used to instantiate MockCrApp from C++ code. -namespace mock_cr_app { -void RegisterMockCrApp(); -} // namespace mock_cr_app - -#endif // BASE_TEST_MOCK_CHROME_APPLICATION_MAC_H_
diff --git a/base/test/mock_chrome_application_mac.mm b/base/test/mock_chrome_application_mac.mm deleted file mode 100644 index 0890553..0000000 --- a/base/test/mock_chrome_application_mac.mm +++ /dev/null
@@ -1,44 +0,0 @@ -// Copyright (c) 2011 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "base/test/mock_chrome_application_mac.h" - -#include "base/auto_reset.h" -#include "base/logging.h" - -@implementation MockCrApp - -+ (NSApplication*)sharedApplication { - NSApplication* app = [super sharedApplication]; - DCHECK([app conformsToProtocol:@protocol(CrAppControlProtocol)]) - << "Existing NSApp (class " << [[app className] UTF8String] - << ") does not conform to required protocol."; - DCHECK(base::MessagePumpMac::UsingCrApp()) - << "MessagePumpMac::Create() was called before " - << "+[MockCrApp sharedApplication]"; - return app; -} - -- (void)sendEvent:(NSEvent*)event { - base::AutoReset<BOOL> scoper(&handlingSendEvent_, YES); - [super sendEvent:event]; -} - -- (void)setHandlingSendEvent:(BOOL)handlingSendEvent { - handlingSendEvent_ = handlingSendEvent; -} - -- (BOOL)isHandlingSendEvent { - return handlingSendEvent_; -} - -@end - -namespace mock_cr_app { - -void RegisterMockCrApp() { - [MockCrApp sharedApplication]; -} - -} // namespace mock_cr_app
diff --git a/base/test/mock_devices_changed_observer.cc b/base/test/mock_devices_changed_observer.cc deleted file mode 100644 index 9fc57cd..0000000 --- a/base/test/mock_devices_changed_observer.cc +++ /dev/null
@@ -1,13 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "base/test/mock_devices_changed_observer.h" - -namespace base { - -MockDevicesChangedObserver::MockDevicesChangedObserver() = default; - -MockDevicesChangedObserver::~MockDevicesChangedObserver() = default; - -} // namespace base
diff --git a/base/test/mock_devices_changed_observer.h b/base/test/mock_devices_changed_observer.h deleted file mode 100644 index 0734fb4..0000000 --- a/base/test/mock_devices_changed_observer.h +++ /dev/null
@@ -1,31 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef BASE_TEST_MOCK_DEVICES_CHANGED_OBSERVER_H_ -#define BASE_TEST_MOCK_DEVICES_CHANGED_OBSERVER_H_ - -#include <string> - -#include "base/macros.h" -#include "base/system_monitor/system_monitor.h" -#include "testing/gmock/include/gmock/gmock.h" - -namespace base { - -class MockDevicesChangedObserver - : public base::SystemMonitor::DevicesChangedObserver { - public: - MockDevicesChangedObserver(); - ~MockDevicesChangedObserver() override; - - MOCK_METHOD1(OnDevicesChanged, - void(base::SystemMonitor::DeviceType device_type)); - - private: - DISALLOW_COPY_AND_ASSIGN(MockDevicesChangedObserver); -}; - -} // namespace base - -#endif // BASE_TEST_MOCK_DEVICES_CHANGED_OBSERVER_H_
diff --git a/base/test/mock_entropy_provider.cc b/base/test/mock_entropy_provider.cc deleted file mode 100644 index f3fd2a4..0000000 --- a/base/test/mock_entropy_provider.cc +++ /dev/null
@@ -1,20 +0,0 @@ -// Copyright 2015 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "base/test/mock_entropy_provider.h" - -namespace base { - -MockEntropyProvider::MockEntropyProvider() : entropy_value_(0.5) {} -MockEntropyProvider::MockEntropyProvider(double entropy_value) - : entropy_value_(entropy_value) {} -MockEntropyProvider::~MockEntropyProvider() = default; - -double MockEntropyProvider::GetEntropyForTrial( - const std::string& trial_name, - uint32_t randomization_seed) const { - return entropy_value_; -} - -} // namespace base
diff --git a/base/test/mock_entropy_provider.h b/base/test/mock_entropy_provider.h deleted file mode 100644 index ca2b4bc..0000000 --- a/base/test/mock_entropy_provider.h +++ /dev/null
@@ -1,32 +0,0 @@ -// Copyright 2015 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef BASE_TEST_MOCK_ENTROPY_PROVIDER_H_ -#define BASE_TEST_MOCK_ENTROPY_PROVIDER_H_ - -#include <stdint.h> - -#include "base/metrics/field_trial.h" - -namespace base { - -class MockEntropyProvider : public base::FieldTrial::EntropyProvider { - public: - MockEntropyProvider(); - explicit MockEntropyProvider(double entropy_value); - ~MockEntropyProvider() override; - - // base::FieldTrial::EntropyProvider: - double GetEntropyForTrial(const std::string& trial_name, - uint32_t randomization_seed) const override; - - private: - double entropy_value_; - - DISALLOW_COPY_AND_ASSIGN(MockEntropyProvider); -}; - -} // namespace base - -#endif // BASE_TEST_MOCK_ENTROPY_PROVIDER_H_
diff --git a/base/test/mock_log.cc b/base/test/mock_log.cc deleted file mode 100644 index a09000d..0000000 --- a/base/test/mock_log.cc +++ /dev/null
@@ -1,68 +0,0 @@ -// Copyright 2015 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "base/test/mock_log.h" - -namespace base { -namespace test { - -// static -MockLog* MockLog::g_instance_ = nullptr; -Lock MockLog::g_lock; - -MockLog::MockLog() : is_capturing_logs_(false) { -} - -MockLog::~MockLog() { - if (is_capturing_logs_) { - StopCapturingLogs(); - } -} - -void MockLog::StartCapturingLogs() { - AutoLock scoped_lock(g_lock); - - // We don't use CHECK(), which can generate a new LOG message, and - // thus can confuse MockLog objects or other registered - // LogSinks. - RAW_CHECK(!is_capturing_logs_); - RAW_CHECK(!g_instance_); - - is_capturing_logs_ = true; - g_instance_ = this; - previous_handler_ = logging::GetLogMessageHandler(); - logging::SetLogMessageHandler(LogMessageHandler); -} - -void MockLog::StopCapturingLogs() { - AutoLock scoped_lock(g_lock); - - // We don't use CHECK(), which can generate a new LOG message, and - // thus can confuse MockLog objects or other registered - // LogSinks. - RAW_CHECK(is_capturing_logs_); - RAW_CHECK(g_instance_ == this); - - is_capturing_logs_ = false; - logging::SetLogMessageHandler(previous_handler_); - g_instance_ = nullptr; -} - -// static -bool MockLog::LogMessageHandler(int severity, - const char* file, - int line, - size_t message_start, - const std::string& str) { - // gMock guarantees thread-safety for calling a mocked method - // (https://github.com/google/googlemock/blob/master/googlemock/docs/CookBook.md#using-google-mock-and-threads) - // but we also need to make sure that Start/StopCapturingLogs are synchronized - // with LogMessageHandler. - AutoLock scoped_lock(g_lock); - - return g_instance_->Log(severity, file, line, message_start, str); -} - -} // namespace test -} // namespace base
diff --git a/base/test/mock_log.h b/base/test/mock_log.h deleted file mode 100644 index cda2fcd..0000000 --- a/base/test/mock_log.h +++ /dev/null
@@ -1,100 +0,0 @@ -// Copyright 2015 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef BASE_TEST_MOCK_LOG_H_ -#define BASE_TEST_MOCK_LOG_H_ - -#include <stddef.h> - -#include <string> - -#include "base/logging.h" -#include "base/macros.h" -#include "base/synchronization/lock.h" -#include "testing/gmock/include/gmock/gmock.h" - -namespace base { -namespace test { - -// A MockLog object intercepts LOG() messages issued during its lifespan. Using -// this together with gMock, it's very easy to test how a piece of code calls -// LOG(). The typical usage: -// -// TEST(FooTest, LogsCorrectly) { -// MockLog log; -// -// // We expect the WARNING "Something bad!" exactly twice. -// EXPECT_CALL(log, Log(WARNING, _, "Something bad!")) -// .Times(2); -// -// // We allow foo.cc to call LOG(INFO) any number of times. -// EXPECT_CALL(log, Log(INFO, HasSubstr("/foo.cc"), _)) -// .Times(AnyNumber()); -// -// log.StartCapturingLogs(); // Call this after done setting expectations. -// Foo(); // Exercises the code under test. -// } -// -// CAVEAT: base/logging does not allow a thread to call LOG() again when it's -// already inside a LOG() call. Doing so will cause a deadlock. Therefore, -// it's the user's responsibility to not call LOG() in an action triggered by -// MockLog::Log(). You may call RAW_LOG() instead. -class MockLog { - public: - // Creates a MockLog object that is not capturing logs. If it were to start - // to capture logs, it could be a problem if some other threads already exist - // and are logging, as the user hasn't had a chance to set up expectation on - // this object yet (calling a mock method before setting the expectation is - // UNDEFINED behavior). - MockLog(); - - // When the object is destructed, it stops intercepting logs. - ~MockLog(); - - // Starts log capturing if the object isn't already doing so. - // Otherwise crashes. - void StartCapturingLogs(); - - // Stops log capturing if the object is capturing logs. Otherwise crashes. - void StopCapturingLogs(); - - // Log method is invoked for every log message before it's sent to other log - // destinations (if any). The method should return true to signal that it - // handled the message and the message should not be sent to other log - // destinations. - MOCK_METHOD5(Log, - bool(int severity, - const char* file, - int line, - size_t message_start, - const std::string& str)); - - private: - // The currently active mock log. - static MockLog* g_instance_; - - // Lock protecting access to g_instance_. - static Lock g_lock; - - // Static function which is set as the logging message handler. - // Called once for each message. - static bool LogMessageHandler(int severity, - const char* file, - int line, - size_t message_start, - const std::string& str); - - // True if this object is currently capturing logs. - bool is_capturing_logs_; - - // The previous handler to restore when the MockLog is destroyed. - logging::LogMessageHandlerFunction previous_handler_; - - DISALLOW_COPY_AND_ASSIGN(MockLog); -}; - -} // namespace test -} // namespace base - -#endif // BASE_TEST_MOCK_LOG_H_
diff --git a/base/test/move_only_int.h b/base/test/move_only_int.h deleted file mode 100644 index 6e90983..0000000 --- a/base/test/move_only_int.h +++ /dev/null
@@ -1,68 +0,0 @@ -// Copyright 2017 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef BASE_TEST_MOVE_ONLY_INT_H_ -#define BASE_TEST_MOVE_ONLY_INT_H_ - -#include "base/macros.h" - -namespace base { - -// A move-only class that holds an integer. This is designed for testing -// containers. See also CopyOnlyInt. -class MoveOnlyInt { - public: - explicit MoveOnlyInt(int data = 1) : data_(data) {} - MoveOnlyInt(MoveOnlyInt&& other) : data_(other.data_) { other.data_ = 0; } - ~MoveOnlyInt() { data_ = 0; } - - MoveOnlyInt& operator=(MoveOnlyInt&& other) { - data_ = other.data_; - other.data_ = 0; - return *this; - } - - friend bool operator==(const MoveOnlyInt& lhs, const MoveOnlyInt& rhs) { - return lhs.data_ == rhs.data_; - } - - friend bool operator!=(const MoveOnlyInt& lhs, const MoveOnlyInt& rhs) { - return !operator==(lhs, rhs); - } - - friend bool operator<(const MoveOnlyInt& lhs, int rhs) { - return lhs.data_ < rhs; - } - - friend bool operator<(int lhs, const MoveOnlyInt& rhs) { - return lhs < rhs.data_; - } - - friend bool operator<(const MoveOnlyInt& lhs, const MoveOnlyInt& rhs) { - return lhs.data_ < rhs.data_; - } - - friend bool operator>(const MoveOnlyInt& lhs, const MoveOnlyInt& rhs) { - return rhs < lhs; - } - - friend bool operator<=(const MoveOnlyInt& lhs, const MoveOnlyInt& rhs) { - return !(rhs < lhs); - } - - friend bool operator>=(const MoveOnlyInt& lhs, const MoveOnlyInt& rhs) { - return !(lhs < rhs); - } - - int data() const { return data_; } - - private: - volatile int data_; - - DISALLOW_COPY_AND_ASSIGN(MoveOnlyInt); -}; - -} // namespace base - -#endif // BASE_TEST_MOVE_ONLY_INT_H_
diff --git a/base/test/multiprocess_test.cc b/base/test/multiprocess_test.cc deleted file mode 100644 index 7bc26e3..0000000 --- a/base/test/multiprocess_test.cc +++ /dev/null
@@ -1,74 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "base/test/multiprocess_test.h" - -#include "base/base_switches.h" -#include "base/command_line.h" -#include "base/files/file_path.h" -#include "base/files/file_util.h" -#include "base/threading/thread_restrictions.h" -#include "build_config.h" - -namespace base { - -#if !defined(OS_ANDROID) -Process SpawnMultiProcessTestChild(const std::string& procname, - const CommandLine& base_command_line, - const LaunchOptions& options) { - CommandLine command_line(base_command_line); - // TODO(viettrungluu): See comment above |MakeCmdLine()| in the header file. - // This is a temporary hack, since |MakeCmdLine()| has to provide a full - // command line. - if (!command_line.HasSwitch(switches::kTestChildProcess)) - command_line.AppendSwitchASCII(switches::kTestChildProcess, procname); - - return LaunchProcess(command_line, options); -} - -bool WaitForMultiprocessTestChildExit(const Process& process, - TimeDelta timeout, - int* exit_code) { - return process.WaitForExitWithTimeout(timeout, exit_code); -} - -bool TerminateMultiProcessTestChild(const Process& process, - int exit_code, - bool wait) { - return process.Terminate(exit_code, wait); -} - -#endif // !defined(OS_ANDROID) - -CommandLine GetMultiProcessTestChildBaseCommandLine() { - base::ScopedAllowBlockingForTesting allow_blocking; - CommandLine cmd_line = *CommandLine::ForCurrentProcess(); - cmd_line.SetProgram(MakeAbsoluteFilePath(cmd_line.GetProgram())); - return cmd_line; -} - -// MultiProcessTest ------------------------------------------------------------ - -MultiProcessTest::MultiProcessTest() = default; - -Process MultiProcessTest::SpawnChild(const std::string& procname) { - LaunchOptions options; -#if defined(OS_WIN) - options.start_hidden = true; -#endif - return SpawnChildWithOptions(procname, options); -} - -Process MultiProcessTest::SpawnChildWithOptions(const std::string& procname, - const LaunchOptions& options) { - return SpawnMultiProcessTestChild(procname, MakeCmdLine(procname), options); -} - -CommandLine MultiProcessTest::MakeCmdLine(const std::string& procname) { - CommandLine command_line = GetMultiProcessTestChildBaseCommandLine(); - command_line.AppendSwitchASCII(switches::kTestChildProcess, procname); - return command_line; -} - -} // namespace base
diff --git a/base/test/multiprocess_test.h b/base/test/multiprocess_test.h deleted file mode 100644 index 3fc0b61..0000000 --- a/base/test/multiprocess_test.h +++ /dev/null
@@ -1,146 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef BASE_TEST_MULTIPROCESS_TEST_H_ -#define BASE_TEST_MULTIPROCESS_TEST_H_ - -#include <string> - -#include "base/macros.h" -#include "base/process/launch.h" -#include "base/process/process.h" -#include "build_config.h" -#include "testing/platform_test.h" - -namespace base { - -class CommandLine; - -// Helpers to spawn a child for a multiprocess test and execute a designated -// function. Use these when you already have another base class for your test -// fixture, but you want (some) of your tests to be multiprocess (otherwise you -// may just want to derive your fixture from |MultiProcessTest|, below). -// -// Use these helpers as follows: -// -// TEST_F(MyTest, ATest) { -// CommandLine command_line( -// base::GetMultiProcessTestChildBaseCommandLine()); -// // Maybe add our own switches to |command_line|.... -// -// LaunchOptions options; -// // Maybe set some options (e.g., |start_hidden| on Windows).... -// -// // Start a child process and run |a_test_func|. -// base::Process test_child_process = -// base::SpawnMultiProcessTestChild("a_test_func", command_line, -// options); -// -// // Do stuff involving |test_child_process| and the child process.... -// -// int rv = -1; -// ASSERT_TRUE(base::WaitForMultiprocessTestChildExit(test_child_process, -// TestTimeouts::action_timeout(), &rv)); -// EXPECT_EQ(0, rv); -// } -// -// // Note: |MULTIPROCESS_TEST_MAIN()| is defined in -// // testing/multi_process_function_list.h. -// MULTIPROCESS_TEST_MAIN(a_test_func) { -// // Code here runs in a child process.... -// return 0; -// } -// -// If you need to terminate the child process, use the -// TerminateMultiProcessTestChild method to ensure that test will work on -// Android. - -// Spawns a child process and executes the function |procname| declared using -// |MULTIPROCESS_TEST_MAIN()| or |MULTIPROCESS_TEST_MAIN_WITH_SETUP()|. -// |command_line| should be as provided by -// |GetMultiProcessTestChildBaseCommandLine()| (below), possibly with arguments -// added. Note: On Windows, you probably want to set |options.start_hidden|. -Process SpawnMultiProcessTestChild(const std::string& procname, - const CommandLine& command_line, - const LaunchOptions& options); - -// Gets the base command line for |SpawnMultiProcessTestChild()|. To this, you -// may add any flags needed for your child process. -CommandLine GetMultiProcessTestChildBaseCommandLine(); - -// Waits for the child process to exit. Returns true if the process exited -// within |timeout| and sets |exit_code| if non null. -bool WaitForMultiprocessTestChildExit(const Process& process, - TimeDelta timeout, - int* exit_code); - -// Terminates |process| with |exit_code|. If |wait| is true, this call blocks -// until the process actually terminates. -bool TerminateMultiProcessTestChild(const Process& process, - int exit_code, - bool wait); - -// MultiProcessTest ------------------------------------------------------------ - -// A MultiProcessTest is a test class which makes it easier to -// write a test which requires code running out of process. -// -// To create a multiprocess test simply follow these steps: -// -// 1) Derive your test from MultiProcessTest. Example: -// -// class MyTest : public MultiProcessTest { -// }; -// -// TEST_F(MyTest, TestCaseName) { -// ... -// } -// -// 2) Create a mainline function for the child processes and include -// testing/multiprocess_func_list.h. -// See the declaration of the MULTIPROCESS_TEST_MAIN macro -// in that file for an example. -// 3) Call SpawnChild("foo"), where "foo" is the name of -// the function you wish to run in the child processes. -// That's it! -class MultiProcessTest : public PlatformTest { - public: - MultiProcessTest(); - - protected: - // Run a child process. - // 'procname' is the name of a function which the child will - // execute. It must be exported from this library in order to - // run. - // - // Example signature: - // extern "C" int __declspec(dllexport) FooBar() { - // // do client work here - // } - // - // Returns the child process. - Process SpawnChild(const std::string& procname); - - // Run a child process using the given launch options. - // - // Note: On Windows, you probably want to set |options.start_hidden|. - Process SpawnChildWithOptions(const std::string& procname, - const LaunchOptions& options); - - // Set up the command line used to spawn the child process. - // Override this to add things to the command line (calling this first in the - // override). - // Note that currently some tests rely on this providing a full command line, - // which they then use directly with |LaunchProcess()|. - // TODO(viettrungluu): Remove this and add a virtual - // |ModifyChildCommandLine()|; make the two divergent uses more sane. - virtual CommandLine MakeCmdLine(const std::string& procname); - - private: - DISALLOW_COPY_AND_ASSIGN(MultiProcessTest); -}; - -} // namespace base - -#endif // BASE_TEST_MULTIPROCESS_TEST_H_
diff --git a/base/test/native_library_test_utils.cc b/base/test/native_library_test_utils.cc deleted file mode 100644 index adcb1b0..0000000 --- a/base/test/native_library_test_utils.cc +++ /dev/null
@@ -1,19 +0,0 @@ -// Copyright 2016 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "base/test/native_library_test_utils.h" - -namespace { - -int g_static_value = 0; - -} // namespace - -extern "C" { - -int g_native_library_exported_value = 0; - -int NativeLibraryTestIncrement() { return ++g_static_value; } - -} // extern "C"
diff --git a/base/test/native_library_test_utils.h b/base/test/native_library_test_utils.h deleted file mode 100644 index c6c46ff..0000000 --- a/base/test/native_library_test_utils.h +++ /dev/null
@@ -1,26 +0,0 @@ -// Copyright 2016 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef BASE_TEST_NATIVE_LIBRARY_TEST_UTILS_H_ -#define BASE_TEST_NATIVE_LIBRARY_TEST_UTILS_H_ - -#include "build_config.h" - -#if defined(OS_WIN) -#define NATIVE_LIBRARY_TEST_ALWAYS_EXPORT __declspec(dllexport) -#else -#define NATIVE_LIBRARY_TEST_ALWAYS_EXPORT __attribute__((visibility("default"))) -#endif - -extern "C" { - -extern NATIVE_LIBRARY_TEST_ALWAYS_EXPORT int g_native_library_exported_value; - -// A function which increments an internal counter value and returns its value. -// The first call returns 1, then 2, etc. -NATIVE_LIBRARY_TEST_ALWAYS_EXPORT int NativeLibraryTestIncrement(); - -} // extern "C" - -#endif // BASE_TEST_NATIVE_LIBRARY_TEST_UTILS_H_
diff --git a/base/test/null_task_runner.cc b/base/test/null_task_runner.cc deleted file mode 100644 index dfa26fa..0000000 --- a/base/test/null_task_runner.cc +++ /dev/null
@@ -1,29 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "base/test/null_task_runner.h" - -namespace base { - -NullTaskRunner::NullTaskRunner() = default; - -NullTaskRunner::~NullTaskRunner() = default; - -bool NullTaskRunner::PostDelayedTask(const Location& from_here, - OnceClosure task, - base::TimeDelta delay) { - return false; -} - -bool NullTaskRunner::PostNonNestableDelayedTask(const Location& from_here, - OnceClosure task, - base::TimeDelta delay) { - return false; -} - -bool NullTaskRunner::RunsTasksInCurrentSequence() const { - return true; -} - -} // namespace base
diff --git a/base/test/null_task_runner.h b/base/test/null_task_runner.h deleted file mode 100644 index c11ab6b..0000000 --- a/base/test/null_task_runner.h +++ /dev/null
@@ -1,39 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef BASE_TEST_NULL_TASK_RUNNER_H_ -#define BASE_TEST_NULL_TASK_RUNNER_H_ - -#include "base/callback.h" -#include "base/compiler_specific.h" -#include "base/macros.h" -#include "base/single_thread_task_runner.h" - -namespace base { - -// Helper class for tests that need to provide an implementation of a -// *TaskRunner class but don't actually care about tasks being run. - -class NullTaskRunner : public base::SingleThreadTaskRunner { - public: - NullTaskRunner(); - - bool PostDelayedTask(const Location& from_here, - base::OnceClosure task, - base::TimeDelta delay) override; - bool PostNonNestableDelayedTask(const Location& from_here, - base::OnceClosure task, - base::TimeDelta delay) override; - // Always returns true to avoid triggering DCHECKs. - bool RunsTasksInCurrentSequence() const override; - - protected: - ~NullTaskRunner() override; - - DISALLOW_COPY_AND_ASSIGN(NullTaskRunner); -}; - -} // namespace base - -#endif // BASE_TEST_NULL_TASK_RUNNER_H_
diff --git a/base/test/perf_log.cc b/base/test/perf_log.cc deleted file mode 100644 index 9212f4b..0000000 --- a/base/test/perf_log.cc +++ /dev/null
@@ -1,45 +0,0 @@ -// Copyright 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "base/test/perf_log.h" - -#include "base/files/file_util.h" -#include "base/logging.h" - -namespace base { - -static FILE* perf_log_file = nullptr; - -bool InitPerfLog(const FilePath& log_file) { - if (perf_log_file) { - // trying to initialize twice - NOTREACHED(); - return false; - } - - perf_log_file = OpenFile(log_file, "w"); - return perf_log_file != nullptr; -} - -void FinalizePerfLog() { - if (!perf_log_file) { - // trying to cleanup without initializing - NOTREACHED(); - return; - } - base::CloseFile(perf_log_file); -} - -void LogPerfResult(const char* test_name, double value, const char* units) { - if (!perf_log_file) { - NOTREACHED(); - return; - } - - fprintf(perf_log_file, "%s\t%g\t%s\n", test_name, value, units); - printf("%s\t%g\t%s\n", test_name, value, units); - fflush(stdout); -} - -} // namespace base
diff --git a/base/test/perf_log.h b/base/test/perf_log.h deleted file mode 100644 index 5d6ed9f..0000000 --- a/base/test/perf_log.h +++ /dev/null
@@ -1,24 +0,0 @@ -// Copyright 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef BASE_TEST_PERF_LOG_H_ -#define BASE_TEST_PERF_LOG_H_ - -namespace base { - -class FilePath; - -// Initializes and finalizes the perf log. These functions should be -// called at the beginning and end (respectively) of running all the -// performance tests. The init function returns true on success. -bool InitPerfLog(const FilePath& log_path); -void FinalizePerfLog(); - -// Writes to the perf result log the given 'value' resulting from the -// named 'test'. The units are to aid in reading the log by people. -void LogPerfResult(const char* test_name, double value, const char* units); - -} // namespace base - -#endif // BASE_TEST_PERF_LOG_H_
diff --git a/base/test/perf_test_suite.cc b/base/test/perf_test_suite.cc deleted file mode 100644 index e789883..0000000 --- a/base/test/perf_test_suite.cc +++ /dev/null
@@ -1,50 +0,0 @@ -// Copyright (c) 2010 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "base/test/perf_test_suite.h" - -#include "base/command_line.h" -#include "base/debug/debugger.h" -#include "base/files/file_path.h" -#include "base/path_service.h" -#include "base/process/launch.h" -#include "base/strings/string_util.h" -#include "base/test/perf_log.h" -#include "build_config.h" -#include "testing/gtest/include/gtest/gtest.h" - -namespace base { - -PerfTestSuite::PerfTestSuite(int argc, char** argv) : TestSuite(argc, argv) {} - -void PerfTestSuite::Initialize() { - TestSuite::Initialize(); - - // Initialize the perf timer log - FilePath log_path = - CommandLine::ForCurrentProcess()->GetSwitchValuePath("log-file"); - if (log_path.empty()) { - PathService::Get(FILE_EXE, &log_path); -#if defined(OS_ANDROID) || defined(OS_FUCHSIA) - base::FilePath tmp_dir; - PathService::Get(base::DIR_CACHE, &tmp_dir); - log_path = tmp_dir.Append(log_path.BaseName()); -#endif - log_path = log_path.ReplaceExtension(FILE_PATH_LITERAL("log")); - log_path = log_path.InsertBeforeExtension(FILE_PATH_LITERAL("_perf")); - } - ASSERT_TRUE(InitPerfLog(log_path)); - - // Raise to high priority to have more precise measurements. Since we don't - // aim at 1% precision, it is not necessary to run at realtime level. - if (!debug::BeingDebugged()) - RaiseProcessToHighPriority(); -} - -void PerfTestSuite::Shutdown() { - TestSuite::Shutdown(); - FinalizePerfLog(); -} - -} // namespace base
diff --git a/base/test/perf_test_suite.h b/base/test/perf_test_suite.h deleted file mode 100644 index 52528f0..0000000 --- a/base/test/perf_test_suite.h +++ /dev/null
@@ -1,22 +0,0 @@ -// Copyright (c) 2011 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef BASE_TEST_PERF_TEST_SUITE_H_ -#define BASE_TEST_PERF_TEST_SUITE_H_ - -#include "base/test/test_suite.h" - -namespace base { - -class PerfTestSuite : public TestSuite { - public: - PerfTestSuite(int argc, char** argv); - - void Initialize() override; - void Shutdown() override; -}; - -} // namespace base - -#endif // BASE_TEST_PERF_TEST_SUITE_H_
diff --git a/base/test/perf_time_logger.cc b/base/test/perf_time_logger.cc deleted file mode 100644 index c05ba51..0000000 --- a/base/test/perf_time_logger.cc +++ /dev/null
@@ -1,27 +0,0 @@ -// Copyright 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "base/test/perf_time_logger.h" - -#include "base/test/perf_log.h" - -namespace base { - -PerfTimeLogger::PerfTimeLogger(const char* test_name) - : logged_(false), test_name_(test_name) {} - -PerfTimeLogger::~PerfTimeLogger() { - if (!logged_) - Done(); -} - -void PerfTimeLogger::Done() { - // we use a floating-point millisecond value because it is more - // intuitive than microseconds and we want more precision than - // integer milliseconds - LogPerfResult(test_name_.c_str(), timer_.Elapsed().InMillisecondsF(), "ms"); - logged_ = true; -} - -} // namespace base
diff --git a/base/test/perf_time_logger.h b/base/test/perf_time_logger.h deleted file mode 100644 index a5f3e8a..0000000 --- a/base/test/perf_time_logger.h +++ /dev/null
@@ -1,37 +0,0 @@ -// Copyright 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef BASE_TEST_PERF_TIME_LOGGER_H_ -#define BASE_TEST_PERF_TIME_LOGGER_H_ - -#include <string> - -#include "base/macros.h" -#include "base/timer/elapsed_timer.h" - -namespace base { - -// Automates calling LogPerfResult for the common case where you want -// to measure the time that something took. Call Done() when the test -// is complete if you do extra work after the test or there are stack -// objects with potentially expensive constructors. Otherwise, this -// class with automatically log on destruction. -class PerfTimeLogger { - public: - explicit PerfTimeLogger(const char* test_name); - ~PerfTimeLogger(); - - void Done(); - - private: - bool logged_; - std::string test_name_; - ElapsedTimer timer_; - - DISALLOW_COPY_AND_ASSIGN(PerfTimeLogger); -}; - -} // namespace base - -#endif // BASE_TEST_PERF_TIME_LOGGER_H_
diff --git a/base/test/power_monitor_test_base.cc b/base/test/power_monitor_test_base.cc deleted file mode 100644 index 8c5ba86..0000000 --- a/base/test/power_monitor_test_base.cc +++ /dev/null
@@ -1,66 +0,0 @@ -// Copyright 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "base/test/power_monitor_test_base.h" - -#include "base/message_loop/message_loop.h" -#include "base/message_loop/message_loop_current.h" -#include "base/power_monitor/power_monitor.h" -#include "base/power_monitor/power_monitor_source.h" -#include "base/run_loop.h" - -namespace base { - -PowerMonitorTestSource::PowerMonitorTestSource() - : test_on_battery_power_(false) { - DCHECK(MessageLoopCurrent::Get()) - << "PowerMonitorTestSource requires a MessageLoop."; -} - -PowerMonitorTestSource::~PowerMonitorTestSource() = default; - -void PowerMonitorTestSource::GeneratePowerStateEvent(bool on_battery_power) { - test_on_battery_power_ = on_battery_power; - ProcessPowerEvent(POWER_STATE_EVENT); - RunLoop().RunUntilIdle(); -} - -void PowerMonitorTestSource::GenerateSuspendEvent() { - ProcessPowerEvent(SUSPEND_EVENT); - RunLoop().RunUntilIdle(); -} - -void PowerMonitorTestSource::GenerateResumeEvent() { - ProcessPowerEvent(RESUME_EVENT); - RunLoop().RunUntilIdle(); -} - -bool PowerMonitorTestSource::IsOnBatteryPowerImpl() { - return test_on_battery_power_; -}; - -PowerMonitorTestObserver::PowerMonitorTestObserver() - : last_power_state_(false), - power_state_changes_(0), - suspends_(0), - resumes_(0) { -} - -PowerMonitorTestObserver::~PowerMonitorTestObserver() = default; - -// PowerObserver callbacks. -void PowerMonitorTestObserver::OnPowerStateChange(bool on_battery_power) { - last_power_state_ = on_battery_power; - power_state_changes_++; -} - -void PowerMonitorTestObserver::OnSuspend() { - suspends_++; -} - -void PowerMonitorTestObserver::OnResume() { - resumes_++; -} - -} // namespace base
diff --git a/base/test/power_monitor_test_base.h b/base/test/power_monitor_test_base.h deleted file mode 100644 index 037670a..0000000 --- a/base/test/power_monitor_test_base.h +++ /dev/null
@@ -1,53 +0,0 @@ -// Copyright 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef BASE_TEST_POWER_MONITOR_TEST_BASE_H_ -#define BASE_TEST_POWER_MONITOR_TEST_BASE_H_ - -#include "base/power_monitor/power_monitor.h" -#include "base/power_monitor/power_monitor_source.h" - -namespace base { - -class PowerMonitorTestSource : public PowerMonitorSource { - public: - PowerMonitorTestSource(); - ~PowerMonitorTestSource() override; - - void GeneratePowerStateEvent(bool on_battery_power); - void GenerateSuspendEvent(); - void GenerateResumeEvent(); - - protected: - bool IsOnBatteryPowerImpl() override; - - bool test_on_battery_power_; -}; - -class PowerMonitorTestObserver : public PowerObserver { - public: - PowerMonitorTestObserver(); - ~PowerMonitorTestObserver() override; - - // PowerObserver callbacks. - void OnPowerStateChange(bool on_battery_power) override; - void OnSuspend() override; - void OnResume() override; - - // Test status counts. - bool last_power_state() { return last_power_state_; } - int power_state_changes() { return power_state_changes_; } - int suspends() { return suspends_; } - int resumes() { return resumes_; } - - private: - bool last_power_state_; // Last power state we were notified of. - int power_state_changes_; // Count of OnPowerStateChange notifications. - int suspends_; // Count of OnSuspend notifications. - int resumes_; // Count of OnResume notifications. -}; - -} // namespace base - -#endif // BASE_TEST_POWER_MONITOR_TEST_BASE_H_
diff --git a/base/test/run_all_base_unittests.cc b/base/test/run_all_base_unittests.cc deleted file mode 100644 index 5d44604..0000000 --- a/base/test/run_all_base_unittests.cc +++ /dev/null
@@ -1,15 +0,0 @@ -// Copyright 2016 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "base/bind.h" -#include "base/test/launcher/unit_test_launcher.h" -#include "base/test/test_suite.h" -#include "build_config.h" - -int main(int argc, char** argv) { - base::TestSuite test_suite(argc, argv); - return base::LaunchUnitTests( - argc, argv, - base::Bind(&base::TestSuite::Run, base::Unretained(&test_suite))); -}
diff --git a/base/test/run_all_perftests.cc b/base/test/run_all_perftests.cc deleted file mode 100644 index 6e38109..0000000 --- a/base/test/run_all_perftests.cc +++ /dev/null
@@ -1,9 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "base/test/perf_test_suite.h" - -int main(int argc, char** argv) { - return base::PerfTestSuite(argc, argv).Run(); -}
diff --git a/base/test/run_all_unittests.cc b/base/test/run_all_unittests.cc deleted file mode 100644 index dd5a0ad..0000000 --- a/base/test/run_all_unittests.cc +++ /dev/null
@@ -1,15 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "base/bind.h" -#include "base/test/launcher/unit_test_launcher.h" -#include "base/test/test_suite.h" -#include "build_config.h" - -int main(int argc, char** argv) { - base::TestSuite test_suite(argc, argv); - return base::LaunchUnitTests( - argc, argv, - base::BindOnce(&base::TestSuite::Run, base::Unretained(&test_suite))); -}
diff --git a/base/test/scoped_command_line.cc b/base/test/scoped_command_line.cc deleted file mode 100644 index c74d243..0000000 --- a/base/test/scoped_command_line.cc +++ /dev/null
@@ -1,22 +0,0 @@ -// Copyright 2016 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "base/test/scoped_command_line.h" - -namespace base { -namespace test { - -ScopedCommandLine::ScopedCommandLine() - : original_command_line_(*base::CommandLine::ForCurrentProcess()) {} - -ScopedCommandLine::~ScopedCommandLine() { - *base::CommandLine::ForCurrentProcess() = original_command_line_; -} - -CommandLine* ScopedCommandLine::GetProcessCommandLine() { - return base::CommandLine::ForCurrentProcess(); -} - -} // namespace test -} // namespace base
diff --git a/base/test/scoped_command_line.h b/base/test/scoped_command_line.h deleted file mode 100644 index dea0c6a..0000000 --- a/base/test/scoped_command_line.h +++ /dev/null
@@ -1,34 +0,0 @@ -// Copyright 2016 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef BASE_TEST_SCOPED_COMMAND_LINE_H_ -#define BASE_TEST_SCOPED_COMMAND_LINE_H_ - -#include "base/command_line.h" - -namespace base { -namespace test { - -// Helper class to restore the original command line at the end of the scope. -// NOTE: In most unit tests, the command line is automatically restored per -// test, so this class is not necessary if the command line applies to -// the entire single test. -class ScopedCommandLine final { - public: - ScopedCommandLine(); - ~ScopedCommandLine(); - - // Gets the command line for the current process. - // NOTE: Do not name this GetCommandLine as this will conflict with Windows's - // GetCommandLine and get renamed to GetCommandLineW. - CommandLine* GetProcessCommandLine(); - - private: - const CommandLine original_command_line_; -}; - -} // namespace test -} // namespace base - -#endif // BASE_TEST_SCOPED_COMMAND_LINE_H_
diff --git a/base/test/scoped_environment_variable_override.cc b/base/test/scoped_environment_variable_override.cc deleted file mode 100644 index 4b7b387..0000000 --- a/base/test/scoped_environment_variable_override.cc +++ /dev/null
@@ -1,33 +0,0 @@ -// Copyright 2017 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "base/test/scoped_environment_variable_override.h" - -#include "base/environment.h" - -namespace base { -namespace test { - -ScopedEnvironmentVariableOverride::ScopedEnvironmentVariableOverride( - const std::string& variable_name, - const std::string& value) - : environment_(Environment::Create()), - variable_name_(variable_name), - overridden_(false), - was_set_(false) { - was_set_ = environment_->GetVar(variable_name, &old_value_); - overridden_ = environment_->SetVar(variable_name, value); -} - -ScopedEnvironmentVariableOverride::~ScopedEnvironmentVariableOverride() { - if (overridden_) { - if (was_set_) - environment_->SetVar(variable_name_, old_value_); - else - environment_->UnSetVar(variable_name_); - } -} - -} // namespace test -} // namespace base
diff --git a/base/test/scoped_environment_variable_override.h b/base/test/scoped_environment_variable_override.h deleted file mode 100644 index b05b5f9..0000000 --- a/base/test/scoped_environment_variable_override.h +++ /dev/null
@@ -1,40 +0,0 @@ -// Copyright 2017 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef BASE_TEST_SCOPED_ENVIRONMENT_VARIABLE_OVERRIDE_H_ -#define BASE_TEST_SCOPED_ENVIRONMENT_VARIABLE_OVERRIDE_H_ - -#include <memory> -#include <string> - -namespace base { - -class Environment; - -namespace test { - -// Helper class to override |variable_name| environment variable to |value| for -// the lifetime of this class. Upon destruction, the previous value is restored. -class ScopedEnvironmentVariableOverride final { - public: - ScopedEnvironmentVariableOverride(const std::string& variable_name, - const std::string& value); - ~ScopedEnvironmentVariableOverride(); - - base::Environment* GetEnv() { return environment_.get(); } - bool IsOverridden() { return overridden_; } - bool WasSet() { return was_set_; } - - private: - std::unique_ptr<Environment> environment_; - std::string variable_name_; - bool overridden_; - bool was_set_; - std::string old_value_; -}; - -} // namespace test -} // namespace base - -#endif // BASE_TEST_SCOPED_ENVIRONMENT_VARIABLE_OVERRIDE_H_
diff --git a/base/test/scoped_feature_list.cc b/base/test/scoped_feature_list.cc deleted file mode 100644 index 7106c44..0000000 --- a/base/test/scoped_feature_list.cc +++ /dev/null
@@ -1,226 +0,0 @@ -// Copyright 2016 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "base/test/scoped_feature_list.h" - -#include <algorithm> -#include <utility> -#include <vector> - -#include "base/memory/ptr_util.h" -#include "base/metrics/field_trial_param_associator.h" -#include "base/stl_util.h" -#include "base/strings/string_number_conversions.h" -#include "base/strings/string_split.h" -#include "base/strings/string_util.h" - -namespace base { -namespace test { - -namespace { - -std::vector<StringPiece> GetFeatureVector( - const std::vector<Feature>& features) { - std::vector<StringPiece> output; - for (const Feature& feature : features) { - output.push_back(feature.name); - } - - return output; -} - -// Extracts a feature name from a feature state string. For example, given -// the input "*MyLovelyFeature<SomeFieldTrial", returns "MyLovelyFeature". -StringPiece GetFeatureName(StringPiece feature) { - StringPiece feature_name = feature; - - // Remove default info. - if (feature_name.starts_with("*")) - feature_name = feature_name.substr(1); - - // Remove field_trial info. - std::size_t index = feature_name.find("<"); - if (index != std::string::npos) - feature_name = feature_name.substr(0, index); - - return feature_name; -} - -struct Features { - std::vector<StringPiece> enabled_feature_list; - std::vector<StringPiece> disabled_feature_list; -}; - -// Merges previously-specified feature overrides with those passed into one of -// the Init() methods. |features| should be a list of features previously -// overridden to be in the |override_state|. |merged_features| should contain -// the enabled and disabled features passed into the Init() method, plus any -// overrides merged as a result of previous calls to this function. -void OverrideFeatures(const std::string& features, - FeatureList::OverrideState override_state, - Features* merged_features) { - std::vector<StringPiece> features_list = - SplitStringPiece(features, ",", TRIM_WHITESPACE, SPLIT_WANT_NONEMPTY); - - for (StringPiece feature : features_list) { - StringPiece feature_name = GetFeatureName(feature); - - if (ContainsValue(merged_features->enabled_feature_list, feature_name) || - ContainsValue(merged_features->disabled_feature_list, feature_name)) - continue; - - if (override_state == FeatureList::OverrideState::OVERRIDE_ENABLE_FEATURE) { - merged_features->enabled_feature_list.push_back(feature); - } else { - DCHECK_EQ(override_state, - FeatureList::OverrideState::OVERRIDE_DISABLE_FEATURE); - merged_features->disabled_feature_list.push_back(feature); - } - } -} - -} // namespace - -ScopedFeatureList::ScopedFeatureList() = default; - -ScopedFeatureList::~ScopedFeatureList() { - if (field_trial_override_) - base::FieldTrialParamAssociator::GetInstance()->ClearParamsForTesting( - field_trial_override_->trial_name(), - field_trial_override_->group_name()); - - FeatureList::ClearInstanceForTesting(); - if (original_feature_list_) - FeatureList::RestoreInstanceForTesting(std::move(original_feature_list_)); -} - -void ScopedFeatureList::Init() { - std::unique_ptr<FeatureList> feature_list(new FeatureList); - feature_list->InitializeFromCommandLine(std::string(), std::string()); - InitWithFeatureList(std::move(feature_list)); -} - -void ScopedFeatureList::InitWithFeatureList( - std::unique_ptr<FeatureList> feature_list) { - DCHECK(!original_feature_list_); - original_feature_list_ = FeatureList::ClearInstanceForTesting(); - FeatureList::SetInstance(std::move(feature_list)); -} - -void ScopedFeatureList::InitFromCommandLine( - const std::string& enable_features, - const std::string& disable_features) { - std::unique_ptr<FeatureList> feature_list(new FeatureList); - feature_list->InitializeFromCommandLine(enable_features, disable_features); - InitWithFeatureList(std::move(feature_list)); -} - -void ScopedFeatureList::InitWithFeatures( - const std::vector<Feature>& enabled_features, - const std::vector<Feature>& disabled_features) { - InitWithFeaturesAndFieldTrials(enabled_features, {}, disabled_features); -} - -void ScopedFeatureList::InitAndEnableFeature(const Feature& feature) { - InitWithFeaturesAndFieldTrials({feature}, {}, {}); -} - -void ScopedFeatureList::InitAndEnableFeatureWithFieldTrialOverride( - const Feature& feature, - FieldTrial* trial) { - InitWithFeaturesAndFieldTrials({feature}, {trial}, {}); -} - -void ScopedFeatureList::InitAndDisableFeature(const Feature& feature) { - InitWithFeaturesAndFieldTrials({}, {}, {feature}); -} - -void ScopedFeatureList::InitWithFeatureState(const Feature& feature, - bool enabled) { - if (enabled) { - InitAndEnableFeature(feature); - } else { - InitAndDisableFeature(feature); - } -} - -void ScopedFeatureList::InitWithFeaturesAndFieldTrials( - const std::vector<Feature>& enabled_features, - const std::vector<FieldTrial*>& trials_for_enabled_features, - const std::vector<Feature>& disabled_features) { - DCHECK_LE(trials_for_enabled_features.size(), enabled_features.size()); - - Features merged_features; - merged_features.enabled_feature_list = GetFeatureVector(enabled_features); - merged_features.disabled_feature_list = GetFeatureVector(disabled_features); - - FeatureList* feature_list = FeatureList::GetInstance(); - - // |current_enabled_features| and |current_disabled_features| must declare out - // of if scope to avoid them out of scope before JoinString calls because - // |merged_features| may contains StringPiece which holding pointer points to - // |current_enabled_features| and |current_disabled_features|. - std::string current_enabled_features; - std::string current_disabled_features; - if (feature_list) { - FeatureList::GetInstance()->GetFeatureOverrides(¤t_enabled_features, - ¤t_disabled_features); - OverrideFeatures(current_enabled_features, - FeatureList::OverrideState::OVERRIDE_ENABLE_FEATURE, - &merged_features); - OverrideFeatures(current_disabled_features, - FeatureList::OverrideState::OVERRIDE_DISABLE_FEATURE, - &merged_features); - } - - // Add the field trial overrides. This assumes that |enabled_features| are at - // the begining of |merged_features.enabled_feature_list|, in the same order. - std::vector<FieldTrial*>::const_iterator trial_it = - trials_for_enabled_features.begin(); - auto feature_it = merged_features.enabled_feature_list.begin(); - std::vector<std::unique_ptr<std::string>> features_with_trial; - features_with_trial.reserve(trials_for_enabled_features.size()); - while (trial_it != trials_for_enabled_features.end()) { - features_with_trial.push_back(std::make_unique<std::string>( - feature_it->as_string() + "<" + (*trial_it)->trial_name())); - // |features_with_trial| owns the string, and feature_it points to it. - *feature_it = *(features_with_trial.back()); - ++trial_it; - ++feature_it; - } - - std::string enabled = JoinString(merged_features.enabled_feature_list, ","); - std::string disabled = JoinString(merged_features.disabled_feature_list, ","); - InitFromCommandLine(enabled, disabled); -} - -void ScopedFeatureList::InitAndEnableFeatureWithParameters( - const Feature& feature, - const std::map<std::string, std::string>& feature_parameters) { - if (!FieldTrialList::IsGlobalSetForTesting()) { - field_trial_list_ = std::make_unique<base::FieldTrialList>(nullptr); - } - - // TODO(crbug.com/794021) Remove this unique field trial name hack when there - // is a cleaner solution. - // Ensure that each call to this method uses a distinct field trial name. - // Otherwise, nested calls might fail due to the shared FieldTrialList - // already having the field trial registered. - static int num_calls = 0; - ++num_calls; - std::string kTrialName = - "scoped_feature_list_trial_name" + base::NumberToString(num_calls); - std::string kTrialGroup = "scoped_feature_list_trial_group"; - - field_trial_override_ = - base::FieldTrialList::CreateFieldTrial(kTrialName, kTrialGroup); - DCHECK(field_trial_override_); - FieldTrialParamAssociator::GetInstance()->AssociateFieldTrialParams( - kTrialName, kTrialGroup, feature_parameters); - InitAndEnableFeatureWithFieldTrialOverride(feature, - field_trial_override_.get()); -} - -} // namespace test -} // namespace base
diff --git a/base/test/scoped_feature_list.h b/base/test/scoped_feature_list.h deleted file mode 100644 index d87b2d8..0000000 --- a/base/test/scoped_feature_list.h +++ /dev/null
@@ -1,123 +0,0 @@ -// Copyright 2016 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef BASE_TEST_SCOPED_FEATURE_LIST_H_ -#define BASE_TEST_SCOPED_FEATURE_LIST_H_ - -#include <map> -#include <memory> -#include <string> -#include <vector> - -#include "base/feature_list.h" -#include "base/memory/ref_counted.h" -#include "base/metrics/field_trial.h" - -namespace base { -namespace test { - -// ScopedFeatureList resets the global FeatureList instance to a new empty -// instance and restores the original instance upon destruction. -// Note: Re-using the same object is not allowed. To reset the feature -// list and initialize it anew, destroy an existing scoped list and init -// a new one. -// -// ScopedFeatureList needs to be initialized (via one of Init... methods) -// before running code that inspects the state of features. In practice this -// means: -// - In browser tests, one of Init... methods should be called from the -// overriden ::testing::Test::SetUp method. For example: -// void SetUp() override { -// scoped_feature_list_.InitAndEnableFeature(features::kMyFeatureHere); -// InProcessBrowserTest::SetUp(); -// } -class ScopedFeatureList final { - public: - ScopedFeatureList(); - ~ScopedFeatureList(); - - // WARNING: This method will reset any globally configured features to their - // default values, which can hide feature interaction bugs. Please use - // sparingly. https://crbug.com/713390 - // Initializes and registers a FeatureList instance with no overrides. - void Init(); - - // WARNING: This method will reset any globally configured features to their - // default values, which can hide feature interaction bugs. Please use - // sparingly. https://crbug.com/713390 - // Initializes and registers the given FeatureList instance. - void InitWithFeatureList(std::unique_ptr<FeatureList> feature_list); - - // WARNING: This method will reset any globally configured features to their - // default values, which can hide feature interaction bugs. Please use - // sparingly. https://crbug.com/713390 - // Initializes and registers a FeatureList instance with only the given - // enabled and disabled features (comma-separated names). - void InitFromCommandLine(const std::string& enable_features, - const std::string& disable_features); - - // Initializes and registers a FeatureList instance based on present - // FeatureList and overridden with the given enabled and disabled features. - // Any feature overrides already present in the global FeatureList will - // continue to apply, unless they conflict with the overrides passed into this - // method. This is important for testing potentially unexpected feature - // interactions. - void InitWithFeatures(const std::vector<Feature>& enabled_features, - const std::vector<Feature>& disabled_features); - - // Initializes and registers a FeatureList instance based on present - // FeatureList and overridden with single enabled feature. - void InitAndEnableFeature(const Feature& feature); - - // Initializes and registers a FeatureList instance based on present - // FeatureList and overridden with single enabled feature and associated field - // trial parameters. - // Note: this creates a scoped global field trial list if there is not - // currently one. - void InitAndEnableFeatureWithParameters( - const Feature& feature, - const std::map<std::string, std::string>& feature_parameters); - - // Initializes and registers a FeatureList instance based on present - // FeatureList and overridden with single disabled feature. - void InitAndDisableFeature(const Feature& feature); - - // Initializes and registers a FeatureList instance based on present - // FeatureList and overriden with a single feature either enabled or - // disabled depending on |enabled|. - void InitWithFeatureState(const Feature& feature, bool enabled); - - private: - // Initializes and registers a FeatureList instance based on present - // FeatureList and overridden with the given enabled and disabled features. - // Any feature overrides already present in the global FeatureList will - // continue to apply, unless they conflict with the overrides passed into this - // method. - // Field trials will apply to the enabled features, in the same order. The - // number of trials must be less (or equal) than the number of enabled - // features. - // Trials are expected to outlive the ScopedFeatureList. - void InitWithFeaturesAndFieldTrials( - const std::vector<Feature>& enabled_features, - const std::vector<FieldTrial*>& trials_for_enabled_features, - const std::vector<Feature>& disabled_features); - - // Initializes and registers a FeatureList instance based on present - // FeatureList and overridden with single enabled feature and associated field - // trial override. - // |trial| is expected to outlive the ScopedFeatureList. - void InitAndEnableFeatureWithFieldTrialOverride(const Feature& feature, - FieldTrial* trial); - - std::unique_ptr<FeatureList> original_feature_list_; - scoped_refptr<FieldTrial> field_trial_override_; - std::unique_ptr<base::FieldTrialList> field_trial_list_; - - DISALLOW_COPY_AND_ASSIGN(ScopedFeatureList); -}; - -} // namespace test -} // namespace base - -#endif // BASE_TEST_SCOPED_FEATURE_LIST_H_
diff --git a/base/test/scoped_locale.cc b/base/test/scoped_locale.cc deleted file mode 100644 index c018284..0000000 --- a/base/test/scoped_locale.cc +++ /dev/null
@@ -1,23 +0,0 @@ -// Copyright (c) 2011 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "base/test/scoped_locale.h" - -#include <locale.h> - -#include "testing/gtest/include/gtest/gtest.h" - -namespace base { - -ScopedLocale::ScopedLocale(const std::string& locale) { - prev_locale_ = setlocale(LC_ALL, nullptr); - EXPECT_TRUE(setlocale(LC_ALL, locale.c_str()) != nullptr) - << "Failed to set locale: " << locale; -} - -ScopedLocale::~ScopedLocale() { - EXPECT_STREQ(prev_locale_.c_str(), setlocale(LC_ALL, prev_locale_.c_str())); -} - -} // namespace base
diff --git a/base/test/scoped_locale.h b/base/test/scoped_locale.h deleted file mode 100644 index ef64e98..0000000 --- a/base/test/scoped_locale.h +++ /dev/null
@@ -1,29 +0,0 @@ -// Copyright (c) 2011 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef BASE_TEST_SCOPED_LOCALE_H_ -#define BASE_TEST_SCOPED_LOCALE_H_ - -#include <string> - -#include "base/macros.h" - -namespace base { - -// Sets the given |locale| on construction, and restores the previous locale -// on destruction. -class ScopedLocale { - public: - explicit ScopedLocale(const std::string& locale); - ~ScopedLocale(); - - private: - std::string prev_locale_; - - DISALLOW_COPY_AND_ASSIGN(ScopedLocale); -}; - -} // namespace base - -#endif // BASE_TEST_SCOPED_LOCALE_H_
diff --git a/base/test/scoped_mock_time_message_loop_task_runner.cc b/base/test/scoped_mock_time_message_loop_task_runner.cc deleted file mode 100644 index 8e855e5..0000000 --- a/base/test/scoped_mock_time_message_loop_task_runner.cc +++ /dev/null
@@ -1,38 +0,0 @@ -// Copyright 2015 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "base/test/scoped_mock_time_message_loop_task_runner.h" - -#include "base/bind.h" -#include "base/logging.h" -#include "base/message_loop/message_loop_current.h" -#include "base/run_loop.h" -#include "base/test/test_pending_task.h" -#include "base/threading/thread_task_runner_handle.h" -#include "base/time/time.h" - -namespace base { - -ScopedMockTimeMessageLoopTaskRunner::ScopedMockTimeMessageLoopTaskRunner() - : task_runner_(new TestMockTimeTaskRunner), - previous_task_runner_(ThreadTaskRunnerHandle::Get()) { - DCHECK(MessageLoopCurrent::Get()); - // To ensure that we process any initialization tasks posted to the - // MessageLoop by a test fixture before replacing its TaskRunner. - RunLoop().RunUntilIdle(); - MessageLoopCurrent::Get()->SetTaskRunner(task_runner_); -} - -ScopedMockTimeMessageLoopTaskRunner::~ScopedMockTimeMessageLoopTaskRunner() { - DCHECK(previous_task_runner_->RunsTasksInCurrentSequence()); - DCHECK_EQ(task_runner_, ThreadTaskRunnerHandle::Get()); - for (auto& pending_task : task_runner_->TakePendingTasks()) { - previous_task_runner_->PostDelayedTask( - pending_task.location, std::move(pending_task.task), - pending_task.GetTimeToRun() - task_runner_->NowTicks()); - } - MessageLoopCurrent::Get()->SetTaskRunner(std::move(previous_task_runner_)); -} - -} // namespace base
diff --git a/base/test/scoped_mock_time_message_loop_task_runner.h b/base/test/scoped_mock_time_message_loop_task_runner.h deleted file mode 100644 index 2a034ee..0000000 --- a/base/test/scoped_mock_time_message_loop_task_runner.h +++ /dev/null
@@ -1,45 +0,0 @@ -// Copyright 2015 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef BASE_TEST_SCOPED_MOCK_TIME_MESSAGE_LOOP_TASK_RUNNER_H_ -#define BASE_TEST_SCOPED_MOCK_TIME_MESSAGE_LOOP_TASK_RUNNER_H_ - -#include "base/macros.h" -#include "base/memory/ref_counted.h" -#include "base/test/test_mock_time_task_runner.h" - -namespace base { - -class SingleThreadTaskRunner; - -// A scoped wrapper around TestMockTimeTaskRunner that replaces -// MessageLoopCurrent::Get()'s task runner (and consequently -// ThreadTaskRunnerHandle) with a TestMockTimeTaskRunner and resets it back at -// the end of its scope. -// -// Note: RunLoop() will not work in the scope of a -// ScopedMockTimeMessageLoopTaskRunner, the underlying TestMockTimeTaskRunner's -// methods must be used instead to pump tasks. -// -// DEPRECATED: Use a TestMockTimeTaskRunner::Type::kBoundToThread instead of a -// MessageLoop + ScopedMockTimeMessageLoopTaskRunner. -// TODO(gab): Remove usage of this API and delete it. -class ScopedMockTimeMessageLoopTaskRunner { - public: - ScopedMockTimeMessageLoopTaskRunner(); - ~ScopedMockTimeMessageLoopTaskRunner(); - - TestMockTimeTaskRunner* task_runner() { return task_runner_.get(); } - TestMockTimeTaskRunner* operator->() { return task_runner_.get(); } - - private: - const scoped_refptr<TestMockTimeTaskRunner> task_runner_; - scoped_refptr<SingleThreadTaskRunner> previous_task_runner_; - - DISALLOW_COPY_AND_ASSIGN(ScopedMockTimeMessageLoopTaskRunner); -}; - -} // namespace base - -#endif // BASE_TEST_SCOPED_MOCK_TIME_MESSAGE_LOOP_TASK_RUNNER_H_
diff --git a/base/test/scoped_path_override.cc b/base/test/scoped_path_override.cc deleted file mode 100644 index b8cfd4a..0000000 --- a/base/test/scoped_path_override.cc +++ /dev/null
@@ -1,40 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "base/test/scoped_path_override.h" - -#include "base/logging.h" -#include "base/path_service.h" - -namespace base { - -ScopedPathOverride::ScopedPathOverride(int key) : key_(key) { - bool result = temp_dir_.CreateUniqueTempDir(); - CHECK(result); - result = PathService::Override(key, temp_dir_.GetPath()); - CHECK(result); -} - -ScopedPathOverride::ScopedPathOverride(int key, const base::FilePath& dir) - : key_(key) { - bool result = PathService::Override(key, dir); - CHECK(result); -} - -ScopedPathOverride::ScopedPathOverride(int key, - const FilePath& path, - bool is_absolute, - bool create) - : key_(key) { - bool result = - PathService::OverrideAndCreateIfNeeded(key, path, is_absolute, create); - CHECK(result); -} - -ScopedPathOverride::~ScopedPathOverride() { - bool result = PathService::RemoveOverride(key_); - CHECK(result) << "The override seems to have been removed already!"; -} - -} // namespace base
diff --git a/base/test/scoped_path_override.h b/base/test/scoped_path_override.h deleted file mode 100644 index f589149..0000000 --- a/base/test/scoped_path_override.h +++ /dev/null
@@ -1,43 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef BASE_TEST_SCOPED_PATH_OVERRIDE_H_ -#define BASE_TEST_SCOPED_PATH_OVERRIDE_H_ - -#include "base/files/scoped_temp_dir.h" -#include "base/macros.h" - -namespace base { - -class FilePath; - -// Sets a path override on construction, and removes it when the object goes out -// of scope. This class is intended to be used by tests that need to override -// paths to ensure their overrides are properly handled and reverted when the -// scope of the test is left. -class ScopedPathOverride { - public: - // Contructor that initializes the override to a scoped temp directory. - explicit ScopedPathOverride(int key); - - // Constructor that would use a path provided by the user. - ScopedPathOverride(int key, const FilePath& dir); - - // See PathService::OverrideAndCreateIfNeeded. - ScopedPathOverride(int key, - const FilePath& path, - bool is_absolute, - bool create); - ~ScopedPathOverride(); - - private: - int key_; - ScopedTempDir temp_dir_; - - DISALLOW_COPY_AND_ASSIGN(ScopedPathOverride); -}; - -} // namespace base - -#endif // BASE_TEST_SCOPED_PATH_OVERRIDE_H_
diff --git a/base/test/sequenced_task_runner_test_template.cc b/base/test/sequenced_task_runner_test_template.cc deleted file mode 100644 index de68492..0000000 --- a/base/test/sequenced_task_runner_test_template.cc +++ /dev/null
@@ -1,269 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "base/test/sequenced_task_runner_test_template.h" - -#include <ostream> - -#include "base/location.h" - -namespace base { - -namespace internal { - -TaskEvent::TaskEvent(int i, Type type) - : i(i), type(type) { -} - -SequencedTaskTracker::SequencedTaskTracker() - : next_post_i_(0), - task_end_count_(0), - task_end_cv_(&lock_) { -} - -void SequencedTaskTracker::PostWrappedNonNestableTask( - SequencedTaskRunner* task_runner, - const Closure& task) { - AutoLock event_lock(lock_); - const int post_i = next_post_i_++; - Closure wrapped_task = Bind(&SequencedTaskTracker::RunTask, this, - task, post_i); - task_runner->PostNonNestableTask(FROM_HERE, wrapped_task); - TaskPosted(post_i); -} - -void SequencedTaskTracker::PostWrappedNestableTask( - SequencedTaskRunner* task_runner, - const Closure& task) { - AutoLock event_lock(lock_); - const int post_i = next_post_i_++; - Closure wrapped_task = Bind(&SequencedTaskTracker::RunTask, this, - task, post_i); - task_runner->PostTask(FROM_HERE, wrapped_task); - TaskPosted(post_i); -} - -void SequencedTaskTracker::PostWrappedDelayedNonNestableTask( - SequencedTaskRunner* task_runner, - const Closure& task, - TimeDelta delay) { - AutoLock event_lock(lock_); - const int post_i = next_post_i_++; - Closure wrapped_task = Bind(&SequencedTaskTracker::RunTask, this, - task, post_i); - task_runner->PostNonNestableDelayedTask(FROM_HERE, wrapped_task, delay); - TaskPosted(post_i); -} - -void SequencedTaskTracker::PostNonNestableTasks( - SequencedTaskRunner* task_runner, - int task_count) { - for (int i = 0; i < task_count; ++i) { - PostWrappedNonNestableTask(task_runner, Closure()); - } -} - -void SequencedTaskTracker::RunTask(const Closure& task, int task_i) { - TaskStarted(task_i); - if (!task.is_null()) - task.Run(); - TaskEnded(task_i); -} - -void SequencedTaskTracker::TaskPosted(int i) { - // Caller must own |lock_|. - events_.push_back(TaskEvent(i, TaskEvent::POST)); -} - -void SequencedTaskTracker::TaskStarted(int i) { - AutoLock lock(lock_); - events_.push_back(TaskEvent(i, TaskEvent::START)); -} - -void SequencedTaskTracker::TaskEnded(int i) { - AutoLock lock(lock_); - events_.push_back(TaskEvent(i, TaskEvent::END)); - ++task_end_count_; - task_end_cv_.Signal(); -} - -const std::vector<TaskEvent>& -SequencedTaskTracker::GetTaskEvents() const { - return events_; -} - -void SequencedTaskTracker::WaitForCompletedTasks(int count) { - AutoLock lock(lock_); - while (task_end_count_ < count) - task_end_cv_.Wait(); -} - -SequencedTaskTracker::~SequencedTaskTracker() = default; - -void PrintTo(const TaskEvent& event, std::ostream* os) { - *os << "(i=" << event.i << ", type="; - switch (event.type) { - case TaskEvent::POST: *os << "POST"; break; - case TaskEvent::START: *os << "START"; break; - case TaskEvent::END: *os << "END"; break; - } - *os << ")"; -} - -namespace { - -// Returns the task ordinals for the task event type |type| in the order that -// they were recorded. -std::vector<int> GetEventTypeOrder(const std::vector<TaskEvent>& events, - TaskEvent::Type type) { - std::vector<int> tasks; - std::vector<TaskEvent>::const_iterator event; - for (event = events.begin(); event != events.end(); ++event) { - if (event->type == type) - tasks.push_back(event->i); - } - return tasks; -} - -// Returns all task events for task |task_i|. -std::vector<TaskEvent::Type> GetEventsForTask( - const std::vector<TaskEvent>& events, - int task_i) { - std::vector<TaskEvent::Type> task_event_orders; - std::vector<TaskEvent>::const_iterator event; - for (event = events.begin(); event != events.end(); ++event) { - if (event->i == task_i) - task_event_orders.push_back(event->type); - } - return task_event_orders; -} - -// Checks that the task events for each task in |events| occur in the order -// {POST, START, END}, and that there is only one instance of each event type -// per task. -::testing::AssertionResult CheckEventOrdersForEachTask( - const std::vector<TaskEvent>& events, - int task_count) { - std::vector<TaskEvent::Type> expected_order; - expected_order.push_back(TaskEvent::POST); - expected_order.push_back(TaskEvent::START); - expected_order.push_back(TaskEvent::END); - - // This is O(n^2), but it runs fast enough currently so is not worth - // optimizing. - for (int i = 0; i < task_count; ++i) { - const std::vector<TaskEvent::Type> task_events = - GetEventsForTask(events, i); - if (task_events != expected_order) { - return ::testing::AssertionFailure() - << "Events for task " << i << " are out of order; expected: " - << ::testing::PrintToString(expected_order) << "; actual: " - << ::testing::PrintToString(task_events); - } - } - return ::testing::AssertionSuccess(); -} - -// Checks that no two tasks were running at the same time. I.e. the only -// events allowed between the START and END of a task are the POSTs of other -// tasks. -::testing::AssertionResult CheckNoTaskRunsOverlap( - const std::vector<TaskEvent>& events) { - // If > -1, we're currently inside a START, END pair. - int current_task_i = -1; - - std::vector<TaskEvent>::const_iterator event; - for (event = events.begin(); event != events.end(); ++event) { - bool spurious_event_found = false; - - if (current_task_i == -1) { // Not inside a START, END pair. - switch (event->type) { - case TaskEvent::POST: - break; - case TaskEvent::START: - current_task_i = event->i; - break; - case TaskEvent::END: - spurious_event_found = true; - break; - } - - } else { // Inside a START, END pair. - bool interleaved_task_detected = false; - - switch (event->type) { - case TaskEvent::POST: - if (event->i == current_task_i) - spurious_event_found = true; - break; - case TaskEvent::START: - interleaved_task_detected = true; - break; - case TaskEvent::END: - if (event->i != current_task_i) - interleaved_task_detected = true; - else - current_task_i = -1; - break; - } - - if (interleaved_task_detected) { - return ::testing::AssertionFailure() - << "Found event " << ::testing::PrintToString(*event) - << " between START and END events for task " << current_task_i - << "; event dump: " << ::testing::PrintToString(events); - } - } - - if (spurious_event_found) { - const int event_i = event - events.begin(); - return ::testing::AssertionFailure() - << "Spurious event " << ::testing::PrintToString(*event) - << " at position " << event_i << "; event dump: " - << ::testing::PrintToString(events); - } - } - - return ::testing::AssertionSuccess(); -} - -} // namespace - -::testing::AssertionResult CheckNonNestableInvariants( - const std::vector<TaskEvent>& events, - int task_count) { - const std::vector<int> post_order = - GetEventTypeOrder(events, TaskEvent::POST); - const std::vector<int> start_order = - GetEventTypeOrder(events, TaskEvent::START); - const std::vector<int> end_order = - GetEventTypeOrder(events, TaskEvent::END); - - if (start_order != post_order) { - return ::testing::AssertionFailure() - << "Expected START order (which equals actual POST order): \n" - << ::testing::PrintToString(post_order) - << "\n Actual START order:\n" - << ::testing::PrintToString(start_order); - } - - if (end_order != post_order) { - return ::testing::AssertionFailure() - << "Expected END order (which equals actual POST order): \n" - << ::testing::PrintToString(post_order) - << "\n Actual END order:\n" - << ::testing::PrintToString(end_order); - } - - const ::testing::AssertionResult result = - CheckEventOrdersForEachTask(events, task_count); - if (!result) - return result; - - return CheckNoTaskRunsOverlap(events); -} - -} // namespace internal - -} // namespace base
diff --git a/base/test/sequenced_task_runner_test_template.h b/base/test/sequenced_task_runner_test_template.h deleted file mode 100644 index a510030..0000000 --- a/base/test/sequenced_task_runner_test_template.h +++ /dev/null
@@ -1,350 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -// SequencedTaskRunnerTest defines tests that implementations of -// SequencedTaskRunner should pass in order to be conformant. -// See task_runner_test_template.h for a description of how to use the -// constructs in this file; these work the same. - -#ifndef BASE_TEST_SEQUENCED_TASK_RUNNER_TEST_TEMPLATE_H_ -#define BASE_TEST_SEQUENCED_TASK_RUNNER_TEST_TEMPLATE_H_ - -#include <cstddef> -#include <iosfwd> -#include <vector> - -#include "base/bind.h" -#include "base/callback.h" -#include "base/macros.h" -#include "base/memory/ref_counted.h" -#include "base/sequenced_task_runner.h" -#include "base/synchronization/condition_variable.h" -#include "base/synchronization/lock.h" -#include "base/time/time.h" -#include "testing/gtest/include/gtest/gtest.h" - -namespace base { - -namespace internal { - -struct TaskEvent { - enum Type { POST, START, END }; - TaskEvent(int i, Type type); - int i; - Type type; -}; - -// Utility class used in the tests below. -class SequencedTaskTracker : public RefCountedThreadSafe<SequencedTaskTracker> { - public: - SequencedTaskTracker(); - - // Posts the non-nestable task |task|, and records its post event. - void PostWrappedNonNestableTask(SequencedTaskRunner* task_runner, - const Closure& task); - - // Posts the nestable task |task|, and records its post event. - void PostWrappedNestableTask(SequencedTaskRunner* task_runner, - const Closure& task); - - // Posts the delayed non-nestable task |task|, and records its post event. - void PostWrappedDelayedNonNestableTask(SequencedTaskRunner* task_runner, - const Closure& task, - TimeDelta delay); - - // Posts |task_count| non-nestable tasks. - void PostNonNestableTasks(SequencedTaskRunner* task_runner, int task_count); - - const std::vector<TaskEvent>& GetTaskEvents() const; - - // Returns after the tracker observes a total of |count| task completions. - void WaitForCompletedTasks(int count); - - private: - friend class RefCountedThreadSafe<SequencedTaskTracker>; - - ~SequencedTaskTracker(); - - // A task which runs |task|, recording the start and end events. - void RunTask(const Closure& task, int task_i); - - // Records a post event for task |i|. The owner is expected to be holding - // |lock_| (unlike |TaskStarted| and |TaskEnded|). - void TaskPosted(int i); - - // Records a start event for task |i|. - void TaskStarted(int i); - - // Records a end event for task |i|. - void TaskEnded(int i); - - // Protects events_, next_post_i_, task_end_count_ and task_end_cv_. - Lock lock_; - - // The events as they occurred for each task (protected by lock_). - std::vector<TaskEvent> events_; - - // The ordinal to be used for the next task-posting task (protected by - // lock_). - int next_post_i_; - - // The number of task end events we've received. - int task_end_count_; - ConditionVariable task_end_cv_; - - DISALLOW_COPY_AND_ASSIGN(SequencedTaskTracker); -}; - -void PrintTo(const TaskEvent& event, std::ostream* os); - -// Checks the non-nestable task invariants for all tasks in |events|. -// -// The invariants are: -// 1) Events started and ended in the same order that they were posted. -// 2) Events for an individual tasks occur in the order {POST, START, END}, -// and there is only one instance of each event type for a task. -// 3) The only events between a task's START and END events are the POSTs of -// other tasks. I.e. tasks were run sequentially, not interleaved. -::testing::AssertionResult CheckNonNestableInvariants( - const std::vector<TaskEvent>& events, - int task_count); - -} // namespace internal - -template <typename TaskRunnerTestDelegate> -class SequencedTaskRunnerTest : public testing::Test { - protected: - SequencedTaskRunnerTest() - : task_tracker_(new internal::SequencedTaskTracker()) {} - - const scoped_refptr<internal::SequencedTaskTracker> task_tracker_; - TaskRunnerTestDelegate delegate_; -}; - -TYPED_TEST_CASE_P(SequencedTaskRunnerTest); - -// This test posts N non-nestable tasks in sequence, and expects them to run -// in FIFO order, with no part of any two tasks' execution -// overlapping. I.e. that each task starts only after the previously-posted -// one has finished. -TYPED_TEST_P(SequencedTaskRunnerTest, SequentialNonNestable) { - const int kTaskCount = 1000; - - this->delegate_.StartTaskRunner(); - const scoped_refptr<SequencedTaskRunner> task_runner = - this->delegate_.GetTaskRunner(); - - this->task_tracker_->PostWrappedNonNestableTask( - task_runner.get(), - Bind(&PlatformThread::Sleep, TimeDelta::FromSeconds(1))); - for (int i = 1; i < kTaskCount; ++i) { - this->task_tracker_->PostWrappedNonNestableTask(task_runner.get(), - Closure()); - } - - this->delegate_.StopTaskRunner(); - - EXPECT_TRUE(CheckNonNestableInvariants(this->task_tracker_->GetTaskEvents(), - kTaskCount)); -} - -// This test posts N nestable tasks in sequence. It has the same expectations -// as SequentialNonNestable because even though the tasks are nestable, they -// will not be run nestedly in this case. -TYPED_TEST_P(SequencedTaskRunnerTest, SequentialNestable) { - const int kTaskCount = 1000; - - this->delegate_.StartTaskRunner(); - const scoped_refptr<SequencedTaskRunner> task_runner = - this->delegate_.GetTaskRunner(); - - this->task_tracker_->PostWrappedNestableTask( - task_runner.get(), - Bind(&PlatformThread::Sleep, TimeDelta::FromSeconds(1))); - for (int i = 1; i < kTaskCount; ++i) { - this->task_tracker_->PostWrappedNestableTask(task_runner.get(), Closure()); - } - - this->delegate_.StopTaskRunner(); - - EXPECT_TRUE(CheckNonNestableInvariants(this->task_tracker_->GetTaskEvents(), - kTaskCount)); -} - -// This test posts non-nestable tasks in order of increasing delay, and checks -// that that the tasks are run in FIFO order and that there is no execution -// overlap whatsoever between any two tasks. -TYPED_TEST_P(SequencedTaskRunnerTest, SequentialDelayedNonNestable) { - const int kTaskCount = 20; - const int kDelayIncrementMs = 50; - - this->delegate_.StartTaskRunner(); - const scoped_refptr<SequencedTaskRunner> task_runner = - this->delegate_.GetTaskRunner(); - - for (int i = 0; i < kTaskCount; ++i) { - this->task_tracker_->PostWrappedDelayedNonNestableTask( - task_runner.get(), Closure(), - TimeDelta::FromMilliseconds(kDelayIncrementMs * i)); - } - - this->task_tracker_->WaitForCompletedTasks(kTaskCount); - this->delegate_.StopTaskRunner(); - - EXPECT_TRUE(CheckNonNestableInvariants(this->task_tracker_->GetTaskEvents(), - kTaskCount)); -} - -// This test posts a fast, non-nestable task from within each of a number of -// slow, non-nestable tasks and checks that they all run in the sequence they -// were posted in and that there is no execution overlap whatsoever. -TYPED_TEST_P(SequencedTaskRunnerTest, NonNestablePostFromNonNestableTask) { - const int kParentCount = 10; - const int kChildrenPerParent = 10; - - this->delegate_.StartTaskRunner(); - const scoped_refptr<SequencedTaskRunner> task_runner = - this->delegate_.GetTaskRunner(); - - for (int i = 0; i < kParentCount; ++i) { - Closure task = Bind( - &internal::SequencedTaskTracker::PostNonNestableTasks, - this->task_tracker_, - RetainedRef(task_runner), - kChildrenPerParent); - this->task_tracker_->PostWrappedNonNestableTask(task_runner.get(), task); - } - - this->delegate_.StopTaskRunner(); - - EXPECT_TRUE(CheckNonNestableInvariants( - this->task_tracker_->GetTaskEvents(), - kParentCount * (kChildrenPerParent + 1))); -} - -// This test posts two tasks with the same delay, and checks that the tasks are -// run in the order in which they were posted. -// -// NOTE: This is actually an approximate test since the API only takes a -// "delay" parameter, so we are not exactly simulating two tasks that get -// posted at the exact same time. It would be nice if the API allowed us to -// specify the desired run time. -TYPED_TEST_P(SequencedTaskRunnerTest, DelayedTasksSameDelay) { - const int kTaskCount = 2; - const TimeDelta kDelay = TimeDelta::FromMilliseconds(100); - - this->delegate_.StartTaskRunner(); - const scoped_refptr<SequencedTaskRunner> task_runner = - this->delegate_.GetTaskRunner(); - - this->task_tracker_->PostWrappedDelayedNonNestableTask(task_runner.get(), - Closure(), kDelay); - this->task_tracker_->PostWrappedDelayedNonNestableTask(task_runner.get(), - Closure(), kDelay); - this->task_tracker_->WaitForCompletedTasks(kTaskCount); - this->delegate_.StopTaskRunner(); - - EXPECT_TRUE(CheckNonNestableInvariants(this->task_tracker_->GetTaskEvents(), - kTaskCount)); -} - -// This test posts a normal task and a delayed task, and checks that the -// delayed task runs after the normal task even if the normal task takes -// a long time to run. -TYPED_TEST_P(SequencedTaskRunnerTest, DelayedTaskAfterLongTask) { - const int kTaskCount = 2; - - this->delegate_.StartTaskRunner(); - const scoped_refptr<SequencedTaskRunner> task_runner = - this->delegate_.GetTaskRunner(); - - this->task_tracker_->PostWrappedNonNestableTask( - task_runner.get(), - base::Bind(&PlatformThread::Sleep, TimeDelta::FromMilliseconds(50))); - this->task_tracker_->PostWrappedDelayedNonNestableTask( - task_runner.get(), Closure(), TimeDelta::FromMilliseconds(10)); - this->task_tracker_->WaitForCompletedTasks(kTaskCount); - this->delegate_.StopTaskRunner(); - - EXPECT_TRUE(CheckNonNestableInvariants(this->task_tracker_->GetTaskEvents(), - kTaskCount)); -} - -// Test that a pile of normal tasks and a delayed task run in the -// time-to-run order. -TYPED_TEST_P(SequencedTaskRunnerTest, DelayedTaskAfterManyLongTasks) { - const int kTaskCount = 11; - - this->delegate_.StartTaskRunner(); - const scoped_refptr<SequencedTaskRunner> task_runner = - this->delegate_.GetTaskRunner(); - - for (int i = 0; i < kTaskCount - 1; i++) { - this->task_tracker_->PostWrappedNonNestableTask( - task_runner.get(), - base::Bind(&PlatformThread::Sleep, TimeDelta::FromMilliseconds(50))); - } - this->task_tracker_->PostWrappedDelayedNonNestableTask( - task_runner.get(), Closure(), TimeDelta::FromMilliseconds(10)); - this->task_tracker_->WaitForCompletedTasks(kTaskCount); - this->delegate_.StopTaskRunner(); - - EXPECT_TRUE(CheckNonNestableInvariants(this->task_tracker_->GetTaskEvents(), - kTaskCount)); -} - - -// TODO(francoisk777@gmail.com) Add a test, similiar to the above, which runs -// some tasked nestedly (which should be implemented in the test -// delegate). Also add, to the the test delegate, a predicate which checks -// whether the implementation supports nested tasks. -// - -// The SequencedTaskRunnerTest test case verifies behaviour that is expected -// from a sequenced task runner in order to be conformant. -REGISTER_TYPED_TEST_CASE_P(SequencedTaskRunnerTest, - SequentialNonNestable, - SequentialNestable, - SequentialDelayedNonNestable, - NonNestablePostFromNonNestableTask, - DelayedTasksSameDelay, - DelayedTaskAfterLongTask, - DelayedTaskAfterManyLongTasks); - -template <typename TaskRunnerTestDelegate> -class SequencedTaskRunnerDelayedTest - : public SequencedTaskRunnerTest<TaskRunnerTestDelegate> {}; - -TYPED_TEST_CASE_P(SequencedTaskRunnerDelayedTest); - -// This test posts a delayed task, and checks that the task is run later than -// the specified time. -TYPED_TEST_P(SequencedTaskRunnerDelayedTest, DelayedTaskBasic) { - const int kTaskCount = 1; - const TimeDelta kDelay = TimeDelta::FromMilliseconds(100); - - this->delegate_.StartTaskRunner(); - const scoped_refptr<SequencedTaskRunner> task_runner = - this->delegate_.GetTaskRunner(); - - Time time_before_run = Time::Now(); - this->task_tracker_->PostWrappedDelayedNonNestableTask(task_runner.get(), - Closure(), kDelay); - this->task_tracker_->WaitForCompletedTasks(kTaskCount); - this->delegate_.StopTaskRunner(); - Time time_after_run = Time::Now(); - - EXPECT_TRUE(CheckNonNestableInvariants(this->task_tracker_->GetTaskEvents(), - kTaskCount)); - EXPECT_LE(kDelay, time_after_run - time_before_run); -} - -// SequencedTaskRunnerDelayedTest tests that the |delay| parameter of -// is used to actually wait for |delay| ms before executing the task. -// This is not mandatory for a SequencedTaskRunner to be compliant. -REGISTER_TYPED_TEST_CASE_P(SequencedTaskRunnerDelayedTest, DelayedTaskBasic); - -} // namespace base - -#endif // BASE_TEST_SEQUENCED_TASK_RUNNER_TEST_TEMPLATE_H_
diff --git a/base/test/simple_test_clock.cc b/base/test/simple_test_clock.cc deleted file mode 100644 index 7486d79..0000000 --- a/base/test/simple_test_clock.cc +++ /dev/null
@@ -1,28 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "base/test/simple_test_clock.h" - -namespace base { - -SimpleTestClock::SimpleTestClock() = default; - -SimpleTestClock::~SimpleTestClock() = default; - -Time SimpleTestClock::Now() const { - AutoLock lock(lock_); - return now_; -} - -void SimpleTestClock::Advance(TimeDelta delta) { - AutoLock lock(lock_); - now_ += delta; -} - -void SimpleTestClock::SetNow(Time now) { - AutoLock lock(lock_); - now_ = now; -} - -} // namespace base
diff --git a/base/test/simple_test_clock.h b/base/test/simple_test_clock.h deleted file mode 100644 index 0cbcf08..0000000 --- a/base/test/simple_test_clock.h +++ /dev/null
@@ -1,41 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef BASE_TEST_SIMPLE_TEST_CLOCK_H_ -#define BASE_TEST_SIMPLE_TEST_CLOCK_H_ - -#include "base/compiler_specific.h" -#include "base/synchronization/lock.h" -#include "base/time/clock.h" -#include "base/time/time.h" - -namespace base { - -// SimpleTestClock is a Clock implementation that gives control over -// the returned Time objects. All methods may be called from any -// thread. -class SimpleTestClock : public Clock { - public: - // Starts off with a clock set to Time(). - SimpleTestClock(); - ~SimpleTestClock() override; - - Time Now() const override; - - // Advances the clock by |delta|. - void Advance(TimeDelta delta); - - // Sets the clock to the given time. - void SetNow(Time now); - - private: - // Protects |now_|. - mutable Lock lock_; - - Time now_; -}; - -} // namespace base - -#endif // BASE_TEST_SIMPLE_TEST_CLOCK_H_
diff --git a/base/test/simple_test_tick_clock.cc b/base/test/simple_test_tick_clock.cc deleted file mode 100644 index 7ee3401..0000000 --- a/base/test/simple_test_tick_clock.cc +++ /dev/null
@@ -1,31 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "base/test/simple_test_tick_clock.h" - -#include "base/logging.h" - -namespace base { - -SimpleTestTickClock::SimpleTestTickClock() = default; - -SimpleTestTickClock::~SimpleTestTickClock() = default; - -TimeTicks SimpleTestTickClock::NowTicks() const { - AutoLock lock(lock_); - return now_ticks_; -} - -void SimpleTestTickClock::Advance(TimeDelta delta) { - AutoLock lock(lock_); - DCHECK(delta >= TimeDelta()); - now_ticks_ += delta; -} - -void SimpleTestTickClock::SetNowTicks(TimeTicks ticks) { - AutoLock lock(lock_); - now_ticks_ = ticks; -} - -} // namespace base
diff --git a/base/test/simple_test_tick_clock.h b/base/test/simple_test_tick_clock.h deleted file mode 100644 index 923eba4..0000000 --- a/base/test/simple_test_tick_clock.h +++ /dev/null
@@ -1,41 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef BASE_TEST_SIMPLE_TEST_TICK_CLOCK_H_ -#define BASE_TEST_SIMPLE_TEST_TICK_CLOCK_H_ - -#include "base/compiler_specific.h" -#include "base/synchronization/lock.h" -#include "base/time/tick_clock.h" -#include "base/time/time.h" - -namespace base { - -// SimpleTestTickClock is a TickClock implementation that gives -// control over the returned TimeTicks objects. All methods may be -// called from any thread. -class SimpleTestTickClock : public TickClock { - public: - // Starts off with a clock set to TimeTicks(). - SimpleTestTickClock(); - ~SimpleTestTickClock() override; - - TimeTicks NowTicks() const override; - - // Advances the clock by |delta|, which must not be negative. - void Advance(TimeDelta delta); - - // Sets the clock to the given time. - void SetNowTicks(TimeTicks ticks); - - private: - // Protects |now_ticks_|. - mutable Lock lock_; - - TimeTicks now_ticks_; -}; - -} // namespace base - -#endif // BASE_TEST_SIMPLE_TEST_TICK_CLOCK_H_
diff --git a/base/test/task_runner_test_template.cc b/base/test/task_runner_test_template.cc deleted file mode 100644 index fe70247..0000000 --- a/base/test/task_runner_test_template.cc +++ /dev/null
@@ -1,47 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "base/test/task_runner_test_template.h" - -namespace base { - -namespace test { - -TaskTracker::TaskTracker() : task_runs_(0), task_runs_cv_(&lock_) {} - -TaskTracker::~TaskTracker() = default; - -Closure TaskTracker::WrapTask(const Closure& task, int i) { - return Bind(&TaskTracker::RunTask, this, task, i); -} - -void TaskTracker::RunTask(const Closure& task, int i) { - AutoLock lock(lock_); - if (!task.is_null()) { - task.Run(); - } - ++task_run_counts_[i]; - ++task_runs_; - task_runs_cv_.Signal(); -} - -std::map<int, int> TaskTracker::GetTaskRunCounts() const { - AutoLock lock(lock_); - return task_run_counts_; -} - -void TaskTracker::WaitForCompletedTasks(int count) { - AutoLock lock(lock_); - while (task_runs_ < count) - task_runs_cv_.Wait(); -} - -void ExpectRunsTasksInCurrentSequence(bool expected_value, - TaskRunner* task_runner) { - EXPECT_EQ(expected_value, task_runner->RunsTasksInCurrentSequence()); -} - -} // namespace test - -} // namespace base
diff --git a/base/test/task_runner_test_template.h b/base/test/task_runner_test_template.h deleted file mode 100644 index 4670522..0000000 --- a/base/test/task_runner_test_template.h +++ /dev/null
@@ -1,230 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -// This file defines tests that implementations of TaskRunner should -// pass in order to be conformant, as well as test cases for optional behavior. -// Here's how you use it to test your implementation. -// -// Say your class is called MyTaskRunner. Then you need to define a -// class called MyTaskRunnerTestDelegate in my_task_runner_unittest.cc -// like this: -// -// class MyTaskRunnerTestDelegate { -// public: -// // Tasks posted to the task runner after this and before -// // StopTaskRunner() is called is called should run successfully. -// void StartTaskRunner() { -// ... -// } -// -// // Should return the task runner implementation. Only called -// // after StartTaskRunner and before StopTaskRunner. -// scoped_refptr<MyTaskRunner> GetTaskRunner() { -// ... -// } -// -// // Stop the task runner and make sure all tasks posted before -// // this is called are run. Caveat: delayed tasks are not run, - // they're simply deleted. -// void StopTaskRunner() { -// ... -// } -// }; -// -// The TaskRunnerTest test harness will have a member variable of -// this delegate type and will call its functions in the various -// tests. -// -// Then you simply #include this file as well as gtest.h and add the -// following statement to my_task_runner_unittest.cc: -// -// INSTANTIATE_TYPED_TEST_CASE_P( -// MyTaskRunner, TaskRunnerTest, MyTaskRunnerTestDelegate); -// -// Easy! -// -// The optional test harnesses TaskRunnerAffinityTest can be -// instanciated in the same way, using the same delegate: -// -// INSTANTIATE_TYPED_TEST_CASE_P( -// MyTaskRunner, TaskRunnerAffinityTest, MyTaskRunnerTestDelegate); - - -#ifndef BASE_TEST_TASK_RUNNER_TEST_TEMPLATE_H_ -#define BASE_TEST_TASK_RUNNER_TEST_TEMPLATE_H_ - -#include <cstddef> -#include <map> - -#include "base/bind.h" -#include "base/callback.h" -#include "base/location.h" -#include "base/macros.h" -#include "base/memory/ref_counted.h" -#include "base/single_thread_task_runner.h" -#include "base/synchronization/condition_variable.h" -#include "base/synchronization/lock.h" -#include "base/task_runner.h" -#include "base/threading/thread.h" -#include "testing/gtest/include/gtest/gtest.h" - -namespace base { - -namespace test { - -// Utility class that keeps track of how many times particular tasks -// are run. -class TaskTracker : public RefCountedThreadSafe<TaskTracker> { - public: - TaskTracker(); - - // Returns a closure that runs the given task and increments the run - // count of |i| by one. |task| may be null. It is guaranteed that - // only one task wrapped by a given tracker will be run at a time. - Closure WrapTask(const Closure& task, int i); - - std::map<int, int> GetTaskRunCounts() const; - - // Returns after the tracker observes a total of |count| task completions. - void WaitForCompletedTasks(int count); - - private: - friend class RefCountedThreadSafe<TaskTracker>; - - ~TaskTracker(); - - void RunTask(const Closure& task, int i); - - mutable Lock lock_; - std::map<int, int> task_run_counts_; - int task_runs_; - ConditionVariable task_runs_cv_; - - DISALLOW_COPY_AND_ASSIGN(TaskTracker); -}; - -} // namespace test - -template <typename TaskRunnerTestDelegate> -class TaskRunnerTest : public testing::Test { - protected: - TaskRunnerTest() : task_tracker_(new test::TaskTracker()) {} - - const scoped_refptr<test::TaskTracker> task_tracker_; - TaskRunnerTestDelegate delegate_; -}; - -TYPED_TEST_CASE_P(TaskRunnerTest); - -// We can't really test much, since TaskRunner provides very few -// guarantees. - -// Post a bunch of tasks to the task runner. They should all -// complete. -TYPED_TEST_P(TaskRunnerTest, Basic) { - std::map<int, int> expected_task_run_counts; - - this->delegate_.StartTaskRunner(); - scoped_refptr<TaskRunner> task_runner = this->delegate_.GetTaskRunner(); - // Post each ith task i+1 times. - for (int i = 0; i < 20; ++i) { - const Closure& ith_task = this->task_tracker_->WrapTask(Closure(), i); - for (int j = 0; j < i + 1; ++j) { - task_runner->PostTask(FROM_HERE, ith_task); - ++expected_task_run_counts[i]; - } - } - this->delegate_.StopTaskRunner(); - - EXPECT_EQ(expected_task_run_counts, - this->task_tracker_->GetTaskRunCounts()); -} - -// Post a bunch of delayed tasks to the task runner. They should all -// complete. -TYPED_TEST_P(TaskRunnerTest, Delayed) { - std::map<int, int> expected_task_run_counts; - int expected_total_tasks = 0; - - this->delegate_.StartTaskRunner(); - scoped_refptr<TaskRunner> task_runner = this->delegate_.GetTaskRunner(); - // Post each ith task i+1 times with delays from 0-i. - for (int i = 0; i < 20; ++i) { - const Closure& ith_task = this->task_tracker_->WrapTask(Closure(), i); - for (int j = 0; j < i + 1; ++j) { - task_runner->PostDelayedTask( - FROM_HERE, ith_task, base::TimeDelta::FromMilliseconds(j)); - ++expected_task_run_counts[i]; - ++expected_total_tasks; - } - } - this->task_tracker_->WaitForCompletedTasks(expected_total_tasks); - this->delegate_.StopTaskRunner(); - - EXPECT_EQ(expected_task_run_counts, - this->task_tracker_->GetTaskRunCounts()); -} - -// The TaskRunnerTest test case verifies behaviour that is expected from a -// task runner in order to be conformant. -REGISTER_TYPED_TEST_CASE_P(TaskRunnerTest, Basic, Delayed); - -namespace test { - -// Calls RunsTasksInCurrentSequence() on |task_runner| and expects it to -// equal |expected_value|. -void ExpectRunsTasksInCurrentSequence(bool expected_value, - TaskRunner* task_runner); - -} // namespace test - -template <typename TaskRunnerTestDelegate> -class TaskRunnerAffinityTest : public TaskRunnerTest<TaskRunnerTestDelegate> {}; - -TYPED_TEST_CASE_P(TaskRunnerAffinityTest); - -// Post a bunch of tasks to the task runner as well as to a separate -// thread, each checking the value of RunsTasksInCurrentSequence(), -// which should return true for the tasks posted on the task runner -// and false for the tasks posted on the separate thread. -TYPED_TEST_P(TaskRunnerAffinityTest, RunsTasksInCurrentSequence) { - std::map<int, int> expected_task_run_counts; - - Thread thread("Non-task-runner thread"); - ASSERT_TRUE(thread.Start()); - this->delegate_.StartTaskRunner(); - - scoped_refptr<TaskRunner> task_runner = this->delegate_.GetTaskRunner(); - // Post each ith task i+1 times on the task runner and i+1 times on - // the non-task-runner thread. - for (int i = 0; i < 20; ++i) { - const Closure& ith_task_runner_task = this->task_tracker_->WrapTask( - Bind(&test::ExpectRunsTasksInCurrentSequence, true, - base::RetainedRef(task_runner)), - i); - const Closure& ith_non_task_runner_task = this->task_tracker_->WrapTask( - Bind(&test::ExpectRunsTasksInCurrentSequence, false, - base::RetainedRef(task_runner)), - i); - for (int j = 0; j < i + 1; ++j) { - task_runner->PostTask(FROM_HERE, ith_task_runner_task); - thread.task_runner()->PostTask(FROM_HERE, ith_non_task_runner_task); - expected_task_run_counts[i] += 2; - } - } - - this->delegate_.StopTaskRunner(); - thread.Stop(); - - EXPECT_EQ(expected_task_run_counts, - this->task_tracker_->GetTaskRunCounts()); -} - -// TaskRunnerAffinityTest tests that the TaskRunner implementation -// can determine if tasks will never be run on a specific thread. -REGISTER_TYPED_TEST_CASE_P(TaskRunnerAffinityTest, RunsTasksInCurrentSequence); - -} // namespace base - -#endif // BASE_TEST_TASK_RUNNER_TEST_TEMPLATE_H_
diff --git a/base/test/test_child_process.cc b/base/test/test_child_process.cc deleted file mode 100644 index ce15856..0000000 --- a/base/test/test_child_process.cc +++ /dev/null
@@ -1,43 +0,0 @@ -// Copyright 2018 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include <stdio.h> -#include <stdlib.h> -#include <string.h> - -// Simple testing command, used to exercise child process launcher calls. -// -// Usage: -// echo_test_helper [-x exit_code] arg0 arg1 arg2... -// Prints arg0..n to stdout with space delimiters between args, -// returning "exit_code" if -x is specified. -// -// echo_test_helper -e env_var -// Prints the environmental variable |env_var| to stdout. -int main(int argc, char** argv) { - if (strcmp(argv[1], "-e") == 0) { - if (argc != 3) { - return 1; - } - - const char* env = getenv(argv[2]); - if (env != NULL) { - printf("%s", env); - } - } else { - int return_code = 0; - int start_idx = 1; - - if (strcmp(argv[1], "-x") == 0) { - return_code = atoi(argv[2]); - start_idx = 3; - } - - for (int i = start_idx; i < argc; ++i) { - printf((i < argc - 1 ? "%s " : "%s"), argv[i]); - } - - return return_code; - } -}
diff --git a/base/test/test_discardable_memory_allocator.cc b/base/test/test_discardable_memory_allocator.cc deleted file mode 100644 index a9bd097..0000000 --- a/base/test/test_discardable_memory_allocator.cc +++ /dev/null
@@ -1,61 +0,0 @@ -// Copyright 2015 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "base/test/test_discardable_memory_allocator.h" - -#include <cstdint> -#include <cstring> - -#include "base/logging.h" -#include "base/memory/discardable_memory.h" -#include "base/memory/ptr_util.h" - -namespace base { -namespace { - -class DiscardableMemoryImpl : public DiscardableMemory { - public: - explicit DiscardableMemoryImpl(size_t size) - : data_(new uint8_t[size]), size_(size) {} - - // Overridden from DiscardableMemory: - bool Lock() override { - DCHECK(!is_locked_); - is_locked_ = true; - return false; - } - - void Unlock() override { - DCHECK(is_locked_); - is_locked_ = false; - // Force eviction to catch clients not correctly checking the return value - // of Lock(). - memset(data_.get(), 0, size_); - } - - void* data() const override { - DCHECK(is_locked_); - return data_.get(); - } - - trace_event::MemoryAllocatorDump* CreateMemoryAllocatorDump( - const char* name, - trace_event::ProcessMemoryDump* pmd) const override { - return nullptr; - } - - private: - bool is_locked_ = true; - std::unique_ptr<uint8_t[]> data_; - size_t size_; -}; - -} // namespace - -std::unique_ptr<DiscardableMemory> -TestDiscardableMemoryAllocator::AllocateLockedDiscardableMemory(size_t size) { - return std::make_unique<DiscardableMemoryImpl>(size); -} - -} // namespace base
diff --git a/base/test/test_discardable_memory_allocator.h b/base/test/test_discardable_memory_allocator.h deleted file mode 100644 index 87436e3..0000000 --- a/base/test/test_discardable_memory_allocator.h +++ /dev/null
@@ -1,32 +0,0 @@ -// Copyright 2015 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef BASE_TEST_TEST_DISCARDABLE_MEMORY_ALLOCATOR_H_ -#define BASE_TEST_TEST_DISCARDABLE_MEMORY_ALLOCATOR_H_ - -#include <stddef.h> - -#include "base/macros.h" -#include "base/memory/discardable_memory_allocator.h" - -namespace base { - -// TestDiscardableMemoryAllocator is a simple DiscardableMemoryAllocator -// implementation that can be used for testing. It allocates one-shot -// DiscardableMemory instances backed by heap memory. -class TestDiscardableMemoryAllocator : public DiscardableMemoryAllocator { - public: - constexpr TestDiscardableMemoryAllocator() = default; - - // Overridden from DiscardableMemoryAllocator: - std::unique_ptr<DiscardableMemory> AllocateLockedDiscardableMemory( - size_t size) override; - - private: - DISALLOW_COPY_AND_ASSIGN(TestDiscardableMemoryAllocator); -}; - -} // namespace base - -#endif // BASE_TEST_TEST_DISCARDABLE_MEMORY_ALLOCATOR_H_
diff --git a/base/test/test_file_util.cc b/base/test/test_file_util.cc deleted file mode 100644 index 8dafc58..0000000 --- a/base/test/test_file_util.cc +++ /dev/null
@@ -1,23 +0,0 @@ -// Copyright (c) 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "base/test/test_file_util.h" - -#include "base/test/test_timeouts.h" -#include "base/threading/platform_thread.h" - -namespace base { - -bool EvictFileFromSystemCacheWithRetry(const FilePath& path) { - const int kCycles = 10; - const TimeDelta kDelay = TestTimeouts::action_timeout() / kCycles; - for (int i = 0; i < kCycles; i++) { - if (EvictFileFromSystemCache(path)) - return true; - PlatformThread::Sleep(kDelay); - } - return false; -} - -} // namespace base
diff --git a/base/test/test_file_util.h b/base/test/test_file_util.h deleted file mode 100644 index f167ca7..0000000 --- a/base/test/test_file_util.h +++ /dev/null
@@ -1,82 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef BASE_TEST_TEST_FILE_UTIL_H_ -#define BASE_TEST_TEST_FILE_UTIL_H_ - -// File utility functions used only by tests. - -#include <stddef.h> - -#include <string> - -#include "base/compiler_specific.h" -#include "base/files/file_path.h" -#include "base/macros.h" -#include "build_config.h" - -#if defined(OS_ANDROID) -#include <jni.h> -#endif - -#if defined(OS_WIN) -#include <windows.h> -#endif - -namespace base { - -class FilePath; - -// Clear a specific file from the system cache like EvictFileFromSystemCache, -// but on failure it will sleep and retry. On the Windows buildbots, eviction -// can fail if the file is marked in use, and this will throw off timings that -// rely on uncached files. -bool EvictFileFromSystemCacheWithRetry(const FilePath& file); - -// Wrapper over base::Delete. On Windows repeatedly invokes Delete in case -// of failure to workaround Windows file locking semantics. Returns true on -// success. -bool DieFileDie(const FilePath& file, bool recurse); - -// Clear a specific file from the system cache. After this call, trying -// to access this file will result in a cold load from the hard drive. -bool EvictFileFromSystemCache(const FilePath& file); - -#if defined(OS_WIN) -// Deny |permission| on the file |path| for the current user. |permission| is an -// ACCESS_MASK structure which is defined in -// https://msdn.microsoft.com/en-us/library/windows/desktop/aa374892.aspx -// Refer to https://msdn.microsoft.com/en-us/library/aa822867.aspx for a list of -// possible values. -bool DenyFilePermission(const FilePath& path, DWORD permission); -#endif // defined(OS_WIN) - -// For testing, make the file unreadable or unwritable. -// In POSIX, this does not apply to the root user. -bool MakeFileUnreadable(const FilePath& path) WARN_UNUSED_RESULT; -bool MakeFileUnwritable(const FilePath& path) WARN_UNUSED_RESULT; - -// Saves the current permissions for a path, and restores it on destruction. -class FilePermissionRestorer { - public: - explicit FilePermissionRestorer(const FilePath& path); - ~FilePermissionRestorer(); - - private: - const FilePath path_; - void* info_; // The opaque stored permission information. - size_t length_; // The length of the stored permission information. - - DISALLOW_COPY_AND_ASSIGN(FilePermissionRestorer); -}; - -#if defined(OS_ANDROID) -// Insert an image file into the MediaStore, and retrieve the content URI for -// testing purpose. -FilePath InsertImageIntoMediaStore(const FilePath& path); -#endif // defined(OS_ANDROID) - -} // namespace base - -#endif // BASE_TEST_TEST_FILE_UTIL_H_
diff --git a/base/test/test_file_util_linux.cc b/base/test/test_file_util_linux.cc deleted file mode 100644 index cf8b056..0000000 --- a/base/test/test_file_util_linux.cc +++ /dev/null
@@ -1,59 +0,0 @@ -// Copyright (c) 2011 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "base/test/test_file_util.h" - -#include <fcntl.h> -#include <sys/stat.h> -#include <sys/types.h> -#include <unistd.h> - -#if defined(OS_ANDROID) -#include <asm/unistd.h> -#include <errno.h> -#include <linux/fadvise.h> -#include <sys/syscall.h> -#endif - -#include "base/files/file_path.h" -#include "base/files/scoped_file.h" - -namespace base { - -// Inconveniently, the NDK doesn't provide for posix_fadvise -// until native API level = 21, which we don't use yet, so provide a wrapper, at -// least on ARM32 -#if defined(OS_ANDROID) && __ANDROID_API__ < 21 - -namespace { -int posix_fadvise(int fd, off_t offset, off_t len, int advice) { -#if defined(ARCH_CPU_ARMEL) - // Note that the syscall argument order on ARM is different from the C - // function; this is helpfully documented in the Linux posix_fadvise manpage. - return syscall(__NR_arm_fadvise64_64, fd, advice, - 0, // Upper 32-bits for offset - offset, - 0, // Upper 32-bits for length - len); -#endif - NOTIMPLEMENTED(); - return ENOSYS; -} - -} // namespace - -#endif // OS_ANDROID - -bool EvictFileFromSystemCache(const FilePath& file) { - ScopedFD fd(open(file.value().c_str(), O_RDONLY)); - if (!fd.is_valid()) - return false; - if (fdatasync(fd.get()) != 0) - return false; - if (posix_fadvise(fd.get(), 0, 0, POSIX_FADV_DONTNEED) != 0) - return false; - return true; -} - -} // namespace base
diff --git a/base/test/test_file_util_mac.cc b/base/test/test_file_util_mac.cc deleted file mode 100644 index 174a31d..0000000 --- a/base/test/test_file_util_mac.cc +++ /dev/null
@@ -1,52 +0,0 @@ -// Copyright (c) 2011 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "base/test/test_file_util.h" - -#include <sys/mman.h> -#include <errno.h> -#include <stdint.h> - -#include "base/files/file_util.h" -#include "base/files/memory_mapped_file.h" -#include "base/logging.h" - -namespace base { - -bool EvictFileFromSystemCache(const FilePath& file) { - // There aren't any really direct ways to purge a file from the UBC. From - // talking with Amit Singh, the safest is to mmap the file with MAP_FILE (the - // default) + MAP_SHARED, then do an msync to invalidate the memory. The next - // open should then have to load the file from disk. - - int64_t length; - if (!GetFileSize(file, &length)) { - DLOG(ERROR) << "failed to get size of " << file.value(); - return false; - } - - // When a file is empty, we do not need to evict it from cache. - // In fact, an attempt to map it to memory will result in error. - if (length == 0) { - DLOG(WARNING) << "file size is zero, will not attempt to map to memory"; - return true; - } - - MemoryMappedFile mapped_file; - if (!mapped_file.Initialize(file)) { - DLOG(WARNING) << "failed to memory map " << file.value(); - return false; - } - - if (msync(const_cast<uint8_t*>(mapped_file.data()), mapped_file.length(), - MS_INVALIDATE) != 0) { - DLOG(WARNING) << "failed to invalidate memory map of " << file.value() - << ", errno: " << errno; - return false; - } - - return true; -} - -} // namespace base
diff --git a/base/test/test_file_util_posix.cc b/base/test/test_file_util_posix.cc deleted file mode 100644 index 2082709..0000000 --- a/base/test/test_file_util_posix.cc +++ /dev/null
@@ -1,110 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "base/test/test_file_util.h" - -#include <errno.h> -#include <fcntl.h> -#include <stddef.h> -#include <sys/stat.h> -#include <sys/types.h> - -#include <string> - -#include "base/files/file_path.h" -#include "base/files/file_util.h" -#include "base/logging.h" -#include "base/strings/string_util.h" -#include "base/strings/utf_string_conversions.h" -#include "build_config.h" - -namespace base { - -namespace { - -// Deny |permission| on the file |path|. -bool DenyFilePermission(const FilePath& path, mode_t permission) { - struct stat stat_buf; - if (stat(path.value().c_str(), &stat_buf) != 0) - return false; - stat_buf.st_mode &= ~permission; - - int rv = HANDLE_EINTR(chmod(path.value().c_str(), stat_buf.st_mode)); - return rv == 0; -} - -// Gets a blob indicating the permission information for |path|. -// |length| is the length of the blob. Zero on failure. -// Returns the blob pointer, or NULL on failure. -void* GetPermissionInfo(const FilePath& path, size_t* length) { - DCHECK(length); - *length = 0; - - struct stat stat_buf; - if (stat(path.value().c_str(), &stat_buf) != 0) - return nullptr; - - *length = sizeof(mode_t); - mode_t* mode = new mode_t; - *mode = stat_buf.st_mode & ~S_IFMT; // Filter out file/path kind. - - return mode; -} - -// Restores the permission information for |path|, given the blob retrieved -// using |GetPermissionInfo()|. -// |info| is the pointer to the blob. -// |length| is the length of the blob. -// Either |info| or |length| may be NULL/0, in which case nothing happens. -bool RestorePermissionInfo(const FilePath& path, void* info, size_t length) { - if (!info || (length == 0)) - return false; - - DCHECK_EQ(sizeof(mode_t), length); - mode_t* mode = reinterpret_cast<mode_t*>(info); - - int rv = HANDLE_EINTR(chmod(path.value().c_str(), *mode)); - - delete mode; - - return rv == 0; -} - -} // namespace - -bool DieFileDie(const FilePath& file, bool recurse) { - // There is no need to workaround Windows problems on POSIX. - // Just pass-through. - return DeleteFile(file, recurse); -} - -#if !defined(OS_LINUX) && !defined(OS_MACOSX) && !defined(OS_ANDROID) -bool EvictFileFromSystemCache(const FilePath& file) { - // There doesn't seem to be a POSIX way to cool the disk cache. - NOTIMPLEMENTED(); - return false; -} -#endif - -bool MakeFileUnreadable(const FilePath& path) { - return DenyFilePermission(path, S_IRUSR | S_IRGRP | S_IROTH); -} - -bool MakeFileUnwritable(const FilePath& path) { - return DenyFilePermission(path, S_IWUSR | S_IWGRP | S_IWOTH); -} - -FilePermissionRestorer::FilePermissionRestorer(const FilePath& path) - : path_(path), info_(nullptr), length_(0) { - info_ = GetPermissionInfo(path_, &length_); - DCHECK(info_ != nullptr); - DCHECK_NE(0u, length_); -} - -FilePermissionRestorer::~FilePermissionRestorer() { - if (!RestorePermissionInfo(path_, info_, length_)) - NOTREACHED(); -} - -} // namespace base
diff --git a/base/test/test_file_util_win.cc b/base/test/test_file_util_win.cc deleted file mode 100644 index da596bb..0000000 --- a/base/test/test_file_util_win.cc +++ /dev/null
@@ -1,182 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "base/test/test_file_util.h" - -#include <aclapi.h> -#include <shlwapi.h> -#include <stddef.h> -#include <wchar.h> -#include <windows.h> - -#include <memory> -#include <vector> - -#include "base/files/file_path.h" -#include "base/files/file_util.h" -#include "base/logging.h" -#include "base/memory/ptr_util.h" -#include "base/strings/string_split.h" -#include "base/threading/platform_thread.h" -#include "base/win/scoped_handle.h" - -namespace base { - -namespace { - -struct PermissionInfo { - PSECURITY_DESCRIPTOR security_descriptor; - ACL dacl; -}; - -// Gets a blob indicating the permission information for |path|. -// |length| is the length of the blob. Zero on failure. -// Returns the blob pointer, or NULL on failure. -void* GetPermissionInfo(const FilePath& path, size_t* length) { - DCHECK(length != NULL); - *length = 0; - PACL dacl = NULL; - PSECURITY_DESCRIPTOR security_descriptor; - if (GetNamedSecurityInfo(const_cast<wchar_t*>(path.value().c_str()), - SE_FILE_OBJECT, - DACL_SECURITY_INFORMATION, NULL, NULL, &dacl, - NULL, &security_descriptor) != ERROR_SUCCESS) { - return NULL; - } - DCHECK(dacl != NULL); - - *length = sizeof(PSECURITY_DESCRIPTOR) + dacl->AclSize; - PermissionInfo* info = reinterpret_cast<PermissionInfo*>(new char[*length]); - info->security_descriptor = security_descriptor; - memcpy(&info->dacl, dacl, dacl->AclSize); - - return info; -} - -// Restores the permission information for |path|, given the blob retrieved -// using |GetPermissionInfo()|. -// |info| is the pointer to the blob. -// |length| is the length of the blob. -// Either |info| or |length| may be NULL/0, in which case nothing happens. -bool RestorePermissionInfo(const FilePath& path, void* info, size_t length) { - if (!info || !length) - return false; - - PermissionInfo* perm = reinterpret_cast<PermissionInfo*>(info); - - DWORD rc = SetNamedSecurityInfo(const_cast<wchar_t*>(path.value().c_str()), - SE_FILE_OBJECT, DACL_SECURITY_INFORMATION, - NULL, NULL, &perm->dacl, NULL); - LocalFree(perm->security_descriptor); - - char* char_array = reinterpret_cast<char*>(info); - delete [] char_array; - - return rc == ERROR_SUCCESS; -} - -std::unique_ptr<wchar_t[]> ToCStr(const std::basic_string<wchar_t>& str) { - size_t size = str.size() + 1; - std::unique_ptr<wchar_t[]> ptr = std::make_unique<wchar_t[]>(size); - wcsncpy(ptr.get(), str.c_str(), size); - return ptr; -} - -} // namespace - -bool DieFileDie(const FilePath& file, bool recurse) { - // It turns out that to not induce flakiness a long timeout is needed. - const int kIterations = 25; - const TimeDelta kTimeout = TimeDelta::FromSeconds(10) / kIterations; - - if (!PathExists(file)) - return true; - - // Sometimes Delete fails, so try a few more times. Divide the timeout - // into short chunks, so that if a try succeeds, we won't delay the test - // for too long. - for (int i = 0; i < kIterations; ++i) { - if (DeleteFile(file, recurse)) - return true; - PlatformThread::Sleep(kTimeout); - } - return false; -} - -bool EvictFileFromSystemCache(const FilePath& file) { - base::win::ScopedHandle file_handle( - CreateFile(file.value().c_str(), GENERIC_READ | GENERIC_WRITE, 0, NULL, - OPEN_EXISTING, FILE_FLAG_NO_BUFFERING, NULL)); - if (!file_handle.IsValid()) - return false; - - // Re-write the file time information to trigger cache eviction for the file. - // This function previously overwrote the entire file without buffering, but - // local experimentation validates this simplified and *much* faster approach: - // [1] Sysinternals RamMap no longer lists these files as cached afterwards. - // [2] Telemetry performance test startup.cold.blank_page reports sane values. - BY_HANDLE_FILE_INFORMATION bhi = {0}; - CHECK(::GetFileInformationByHandle(file_handle.Get(), &bhi)); - CHECK(::SetFileTime(file_handle.Get(), &bhi.ftCreationTime, - &bhi.ftLastAccessTime, &bhi.ftLastWriteTime)); - return true; -} - -// Deny |permission| on the file |path|, for the current user. -bool DenyFilePermission(const FilePath& path, DWORD permission) { - PACL old_dacl; - PSECURITY_DESCRIPTOR security_descriptor; - - std::unique_ptr<TCHAR[]> path_ptr = ToCStr(path.value()); - if (GetNamedSecurityInfo(path_ptr.get(), SE_FILE_OBJECT, - DACL_SECURITY_INFORMATION, nullptr, nullptr, - &old_dacl, nullptr, - &security_descriptor) != ERROR_SUCCESS) { - return false; - } - - std::unique_ptr<TCHAR[]> current_user = ToCStr(std::wstring(L"CURRENT_USER")); - EXPLICIT_ACCESS new_access = { - permission, - DENY_ACCESS, - 0, - {nullptr, NO_MULTIPLE_TRUSTEE, TRUSTEE_IS_NAME, TRUSTEE_IS_USER, - current_user.get()}}; - - PACL new_dacl; - if (SetEntriesInAcl(1, &new_access, old_dacl, &new_dacl) != ERROR_SUCCESS) { - LocalFree(security_descriptor); - return false; - } - - DWORD rc = SetNamedSecurityInfo(path_ptr.get(), SE_FILE_OBJECT, - DACL_SECURITY_INFORMATION, nullptr, nullptr, - new_dacl, nullptr); - LocalFree(security_descriptor); - LocalFree(new_dacl); - - return rc == ERROR_SUCCESS; -} - -bool MakeFileUnreadable(const FilePath& path) { - return DenyFilePermission(path, GENERIC_READ); -} - -bool MakeFileUnwritable(const FilePath& path) { - return DenyFilePermission(path, GENERIC_WRITE); -} - -FilePermissionRestorer::FilePermissionRestorer(const FilePath& path) - : path_(path), info_(NULL), length_(0) { - info_ = GetPermissionInfo(path_, &length_); - DCHECK(info_ != NULL); - DCHECK_NE(0u, length_); -} - -FilePermissionRestorer::~FilePermissionRestorer() { - if (!RestorePermissionInfo(path_, info_, length_)) - NOTREACHED(); -} - -} // namespace base
diff --git a/base/test/test_io_thread.cc b/base/test/test_io_thread.cc deleted file mode 100644 index 1b20658..0000000 --- a/base/test/test_io_thread.cc +++ /dev/null
@@ -1,45 +0,0 @@ -// Copyright 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "base/test/test_io_thread.h" - -#include "base/logging.h" -#include "base/message_loop/message_loop.h" - -namespace base { - -TestIOThread::TestIOThread(Mode mode) - : io_thread_("test_io_thread"), io_thread_started_(false) { - switch (mode) { - case kAutoStart: - Start(); - return; - case kManualStart: - return; - } - CHECK(false) << "Invalid mode"; -} - -TestIOThread::~TestIOThread() { - Stop(); -} - -void TestIOThread::Start() { - CHECK(!io_thread_started_); - io_thread_started_ = true; - CHECK(io_thread_.StartWithOptions( - base::Thread::Options(base::MessageLoop::TYPE_IO, 0))); -} - -void TestIOThread::Stop() { - // Note: It's okay to call |Stop()| even if the thread isn't running. - io_thread_.Stop(); - io_thread_started_ = false; -} - -void TestIOThread::PostTask(const Location& from_here, base::OnceClosure task) { - task_runner()->PostTask(from_here, std::move(task)); -} - -} // namespace base
diff --git a/base/test/test_io_thread.h b/base/test/test_io_thread.h deleted file mode 100644 index a55a063..0000000 --- a/base/test/test_io_thread.h +++ /dev/null
@@ -1,60 +0,0 @@ -// Copyright 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef BASE_TEST_TEST_IO_THREAD_H_ -#define BASE_TEST_TEST_IO_THREAD_H_ - -#include "base/callback_forward.h" -#include "base/compiler_specific.h" -#include "base/macros.h" -#include "base/memory/ref_counted.h" -#include "base/task_runner.h" -#include "base/threading/thread.h" -#include "base/time/time.h" - -namespace base { - -// Create and run an IO thread with a MessageLoop, and -// making the MessageLoop accessible from its client. -// It also provides some ideomatic API like PostTaskAndWait(). -// -// This API is not thread-safe: -// - Start()/Stop() should only be called from the main (creation) thread. -// - PostTask()/message_loop()/task_runner() are also safe to call from the -// underlying thread itself (to post tasks from other threads: get the -// task_runner() from the main thread first, it is then safe to pass _it_ -// around). -class TestIOThread { - public: - enum Mode { kAutoStart, kManualStart }; - explicit TestIOThread(Mode mode); - // Stops the I/O thread if necessary. - ~TestIOThread(); - - // After Stop(), Start() may be called again to start a new I/O thread. - // Stop() may be called even when the I/O thread is not started. - void Start(); - void Stop(); - - // Post |task| to the IO thread. - void PostTask(const Location& from_here, base::OnceClosure task); - - base::MessageLoopForIO* message_loop() { - return static_cast<base::MessageLoopForIO*>(io_thread_.message_loop()); - } - - scoped_refptr<SingleThreadTaskRunner> task_runner() { - return message_loop()->task_runner(); - } - - private: - base::Thread io_thread_; - bool io_thread_started_; - - DISALLOW_COPY_AND_ASSIGN(TestIOThread); -}; - -} // namespace base - -#endif // BASE_TEST_TEST_IO_THREAD_H_
diff --git a/base/test/test_message_loop.cc b/base/test/test_message_loop.cc deleted file mode 100644 index bd3610f..0000000 --- a/base/test/test_message_loop.cc +++ /dev/null
@@ -1,18 +0,0 @@ -// Copyright 2016 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "base/run_loop.h" -#include "base/test/test_message_loop.h" - -namespace base { - -TestMessageLoop::TestMessageLoop() = default; - -TestMessageLoop::TestMessageLoop(MessageLoop::Type type) : loop_(type) {} - -TestMessageLoop::~TestMessageLoop() { - RunLoop().RunUntilIdle(); -} - -} // namespace base
diff --git a/base/test/test_message_loop.h b/base/test/test_message_loop.h deleted file mode 100644 index 9c0aed8..0000000 --- a/base/test/test_message_loop.h +++ /dev/null
@@ -1,34 +0,0 @@ -// Copyright 2016 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef BASE_TEST_TEST_MESSAGE_LOOP_H_ -#define BASE_TEST_TEST_MESSAGE_LOOP_H_ - -#include "base/message_loop/message_loop.h" - -namespace base { - -// TestMessageLoop is a convenience class for unittests that need to create a -// message loop without a real thread backing it. For most tests, -// it is sufficient to just instantiate TestMessageLoop as a member variable. -// -// TestMessageLoop will attempt to drain the underlying MessageLoop on -// destruction for clean teardown of tests. -class TestMessageLoop { - public: - TestMessageLoop(); - explicit TestMessageLoop(MessageLoop::Type type); - ~TestMessageLoop(); - - const scoped_refptr<SingleThreadTaskRunner>& task_runner() { - return loop_.task_runner(); - } - - private: - MessageLoop loop_; -}; - -} // namespace base - -#endif // BASE_TEST_TEST_MESSAGE_LOOP_H_
diff --git a/base/test/test_reg_util_win.cc b/base/test/test_reg_util_win.cc deleted file mode 100644 index 9ce4ad1..0000000 --- a/base/test/test_reg_util_win.cc +++ /dev/null
@@ -1,122 +0,0 @@ -// Copyright (c) 2011 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "base/test/test_reg_util_win.h" - -#include <stdint.h> - -#include "base/guid.h" -#include "base/logging.h" -#include "base/memory/ptr_util.h" -#include "base/strings/string_number_conversions.h" -#include "base/strings/string_split.h" -#include "base/strings/string_util.h" -#include "base/strings/utf_string_conversions.h" -#include "testing/gtest/include/gtest/gtest.h" - -#include <windows.h> - -namespace registry_util { - -namespace { - -const wchar_t kTimestampDelimiter[] = L"$"; -const wchar_t kTempTestKeyPath[] = L"Software\\Chromium\\TempTestKeys"; - -void DeleteStaleTestKeys(const base::Time& now, - const base::string16& test_key_root) { - base::win::RegKey test_root_key; - if (test_root_key.Open(HKEY_CURRENT_USER, - test_key_root.c_str(), - KEY_ALL_ACCESS) != ERROR_SUCCESS) { - // This will occur on first-run, but is harmless. - return; - } - - base::win::RegistryKeyIterator iterator_test_root_key(HKEY_CURRENT_USER, - test_key_root.c_str()); - for (; iterator_test_root_key.Valid(); ++iterator_test_root_key) { - base::string16 key_name = iterator_test_root_key.Name(); - std::vector<base::string16> tokens = base::SplitString( - key_name, kTimestampDelimiter, base::KEEP_WHITESPACE, - base::SPLIT_WANT_NONEMPTY); - if (tokens.empty()) - continue; - int64_t key_name_as_number = 0; - - if (!base::StringToInt64(tokens[0], &key_name_as_number)) { - test_root_key.DeleteKey(key_name.c_str()); - continue; - } - - base::Time key_time = base::Time::FromInternalValue(key_name_as_number); - base::TimeDelta age = now - key_time; - - if (age > base::TimeDelta::FromHours(24)) - test_root_key.DeleteKey(key_name.c_str()); - } -} - -base::string16 GenerateTempKeyPath(const base::string16& test_key_root, - const base::Time& timestamp) { - base::string16 key_path = test_key_root; - key_path += L"\\" + base::Int64ToString16(timestamp.ToInternalValue()); - key_path += kTimestampDelimiter + base::ASCIIToUTF16(base::GenerateGUID()); - - return key_path; -} - -} // namespace - -RegistryOverrideManager::ScopedRegistryKeyOverride::ScopedRegistryKeyOverride( - HKEY override, - const base::string16& key_path) - : override_(override), key_path_(key_path) {} - -RegistryOverrideManager:: - ScopedRegistryKeyOverride::~ScopedRegistryKeyOverride() { - ::RegOverridePredefKey(override_, NULL); - base::win::RegKey(HKEY_CURRENT_USER, L"", KEY_QUERY_VALUE) - .DeleteKey(key_path_.c_str()); -} - -RegistryOverrideManager::RegistryOverrideManager() - : timestamp_(base::Time::Now()), test_key_root_(kTempTestKeyPath) { - DeleteStaleTestKeys(timestamp_, test_key_root_); -} - -RegistryOverrideManager::RegistryOverrideManager( - const base::Time& timestamp, - const base::string16& test_key_root) - : timestamp_(timestamp), test_key_root_(test_key_root) { - DeleteStaleTestKeys(timestamp_, test_key_root_); -} - -RegistryOverrideManager::~RegistryOverrideManager() {} - -void RegistryOverrideManager::OverrideRegistry(HKEY override) { - OverrideRegistry(override, nullptr); -} - -void RegistryOverrideManager::OverrideRegistry(HKEY override, - base::string16* override_path) { - base::string16 key_path = GenerateTempKeyPath(test_key_root_, timestamp_); - - base::win::RegKey temp_key; - ASSERT_EQ(ERROR_SUCCESS, temp_key.Create(HKEY_CURRENT_USER, key_path.c_str(), - KEY_ALL_ACCESS)); - ASSERT_EQ(ERROR_SUCCESS, ::RegOverridePredefKey(override, temp_key.Handle())); - - overrides_.push_back( - std::make_unique<ScopedRegistryKeyOverride>(override, key_path)); - if (override_path) - override_path->assign(key_path); -} - -base::string16 GenerateTempKeyPath() { - return GenerateTempKeyPath(base::string16(kTempTestKeyPath), - base::Time::Now()); -} - -} // namespace registry_util
diff --git a/base/test/test_reg_util_win.h b/base/test/test_reg_util_win.h deleted file mode 100644 index d74028a..0000000 --- a/base/test/test_reg_util_win.h +++ /dev/null
@@ -1,82 +0,0 @@ -// Copyright (c) 2011 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef BASE_TEST_TEST_REG_UTIL_WIN_H_ -#define BASE_TEST_TEST_REG_UTIL_WIN_H_ - -// Registry utility functions used only by tests. -#include <memory> -#include <vector> - -#include "base/macros.h" -#include "base/strings/string16.h" -#include "base/time/time.h" -#include "base/win/registry.h" - -namespace registry_util { - -// Allows a test to easily override registry hives so that it can start from a -// known good state, or make sure to not leave any side effects once the test -// completes. This supports parallel tests. All the overrides are scoped to the -// lifetime of the override manager. Destroy the manager to undo the overrides. -// -// Overridden hives use keys stored at, for instance: -// HKCU\Software\Chromium\TempTestKeys\ -// 13028145911617809$02AB211C-CF73-478D-8D91-618E11998AED -// The key path are comprises of: -// - The test key root, HKCU\Software\Chromium\TempTestKeys\ -// - The base::Time::ToInternalValue of the creation time. This is used to -// delete stale keys left over from crashed tests. -// - A GUID used for preventing name collisions (although unlikely) between -// two RegistryOverrideManagers created with the same timestamp. -class RegistryOverrideManager { - public: - RegistryOverrideManager(); - ~RegistryOverrideManager(); - - // Override the given registry hive using a randomly generated temporary key. - // Multiple overrides to the same hive are not supported and lead to undefined - // behavior. - // Optional return of the registry override path. - // Calls to these functions must be wrapped in ASSERT_NO_FATAL_FAILURE to - // ensure that tests do not proceeed in case of failure to override. - void OverrideRegistry(HKEY override); - void OverrideRegistry(HKEY override, base::string16* override_path); - - private: - friend class RegistryOverrideManagerTest; - - // Keeps track of one override. - class ScopedRegistryKeyOverride { - public: - ScopedRegistryKeyOverride(HKEY override, const base::string16& key_path); - ~ScopedRegistryKeyOverride(); - - private: - HKEY override_; - base::string16 key_path_; - - DISALLOW_COPY_AND_ASSIGN(ScopedRegistryKeyOverride); - }; - - // Used for testing only. - RegistryOverrideManager(const base::Time& timestamp, - const base::string16& test_key_root); - - base::Time timestamp_; - base::string16 guid_; - - base::string16 test_key_root_; - std::vector<std::unique_ptr<ScopedRegistryKeyOverride>> overrides_; - - DISALLOW_COPY_AND_ASSIGN(RegistryOverrideManager); -}; - -// Generates a temporary key path that will be eventually deleted -// automatically if the process crashes. -base::string16 GenerateTempKeyPath(); - -} // namespace registry_util - -#endif // BASE_TEST_TEST_REG_UTIL_WIN_H_
diff --git a/base/test/test_shared_library.cc b/base/test/test_shared_library.cc deleted file mode 100644 index 99c0467..0000000 --- a/base/test/test_shared_library.cc +++ /dev/null
@@ -1,30 +0,0 @@ -// Copyright 2016 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "base/test/native_library_test_utils.h" - -extern "C" { - -int NATIVE_LIBRARY_TEST_ALWAYS_EXPORT GetExportedValue() { - return g_native_library_exported_value; -} - -void NATIVE_LIBRARY_TEST_ALWAYS_EXPORT SetExportedValue(int value) { - g_native_library_exported_value = value; -} - -// A test function used only to verify basic dynamic symbol resolution. -int NATIVE_LIBRARY_TEST_ALWAYS_EXPORT GetSimpleTestValue() { - return 5; -} - -// When called by |NativeLibraryTest.LoadLibraryPreferOwnSymbols|, this should -// forward to the local definition of NativeLibraryTestIncrement(), even though -// the test module also links in the native_library_test_utils source library -// which exports it. -int NATIVE_LIBRARY_TEST_ALWAYS_EXPORT GetIncrementValue() { - return NativeLibraryTestIncrement(); -} - -} // extern "C"
diff --git a/base/test/test_shared_memory_util.cc b/base/test/test_shared_memory_util.cc deleted file mode 100644 index 5cde5b1..0000000 --- a/base/test/test_shared_memory_util.cc +++ /dev/null
@@ -1,187 +0,0 @@ -// Copyright 2017 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "base/test/test_shared_memory_util.h" - -#include <gtest/gtest.h> - -#include <stddef.h> -#include <stdint.h> - -#include "base/logging.h" -#include "build_config.h" - -#if defined(OS_POSIX) && !defined(OS_NACL) -#include <errno.h> -#include <string.h> -#include <sys/mman.h> -#include <unistd.h> -#endif - -#if defined(OS_FUCHSIA) -#include <zircon/process.h> -#include <zircon/rights.h> -#include <zircon/syscalls.h> -#endif - -#if defined(OS_MACOSX) && !defined(OS_IOS) -#include <mach/mach_vm.h> -#endif - -#if defined(OS_WIN) -#include <aclapi.h> -#endif - -namespace base { - -#if !defined(OS_NACL) - -static const size_t kDataSize = 1024; - -// Common routine used with Posix file descriptors. Check that shared memory -// file descriptor |fd| does not allow writable mappings. Return true on -// success, false otherwise. -#if defined(OS_POSIX) && !defined(OS_FUCHSIA) -static bool CheckReadOnlySharedMemoryFdPosix(int fd) { -// Note that the error on Android is EPERM, unlike other platforms where -// it will be EACCES. -#if defined(OS_ANDROID) - const int kExpectedErrno = EPERM; -#else - const int kExpectedErrno = EACCES; -#endif - errno = 0; - void* address = - mmap(nullptr, kDataSize, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0); - const bool success = (address != nullptr) && (address != MAP_FAILED); - if (success) { - LOG(ERROR) << "mmap() should have failed!"; - munmap(address, kDataSize); // Cleanup. - return false; - } - if (errno != kExpectedErrno) { - LOG(ERROR) << "Expected mmap() to return " << kExpectedErrno - << " but returned " << errno << ": " << strerror(errno) << "\n"; - return false; - } - return true; -} -#endif // OS_POSIX && !OS_FUCHSIA - -#if defined(OS_FUCHSIA) -// Fuchsia specific implementation. -bool CheckReadOnlySharedMemoryFuchsiaHandle(zx_handle_t handle) { - const uint32_t flags = ZX_VM_FLAG_PERM_READ | ZX_VM_FLAG_PERM_WRITE; - uintptr_t addr; - const zx_handle_t root = zx_vmar_root_self(); - const zx_status_t status = - zx_vmar_map(root, 0, handle, 0U, kDataSize, flags, &addr); - if (status == ZX_OK) { - LOG(ERROR) << "zx_vmar_map() should have failed!"; - zx_vmar_unmap(root, addr, kDataSize); - return false; - } - if (status != ZX_ERR_ACCESS_DENIED) { - LOG(ERROR) << "Expected zx_vmar_map() to return " << ZX_ERR_ACCESS_DENIED - << " (ZX_ERR_ACCESS_DENIED) but returned " << status << "\n"; - return false; - } - return true; -} - -#elif defined(OS_MACOSX) && !defined(OS_IOS) -bool CheckReadOnlySharedMemoryMachPort(mach_port_t memory_object) { - mach_vm_address_t memory; - const kern_return_t kr = mach_vm_map( - mach_task_self(), &memory, kDataSize, 0, VM_FLAGS_ANYWHERE, memory_object, - 0, FALSE, VM_PROT_READ | VM_PROT_WRITE, - VM_PROT_READ | VM_PROT_WRITE | VM_PROT_IS_MASK, VM_INHERIT_NONE); - if (kr == KERN_SUCCESS) { - LOG(ERROR) << "mach_vm_map() should have failed!"; - mach_vm_deallocate(mach_task_self(), memory, kDataSize); // Cleanup. - return false; - } - return true; -} - -#elif defined(OS_WIN) -bool CheckReadOnlySharedMemoryWindowsHandle(HANDLE handle) { - void* memory = - MapViewOfFile(handle, FILE_MAP_READ | FILE_MAP_WRITE, 0, 0, kDataSize); - if (memory != nullptr) { - LOG(ERROR) << "MapViewOfFile() should have failed!"; - UnmapViewOfFile(memory); - return false; - } - return true; -} -#endif - -bool CheckReadOnlySharedMemoryHandleForTesting(SharedMemoryHandle handle) { -#if defined(OS_MACOSX) && !defined(OS_IOS) - // For OSX, the code has to deal with both POSIX and MACH handles. - if (handle.type_ == SharedMemoryHandle::POSIX) - return CheckReadOnlySharedMemoryFdPosix(handle.file_descriptor_.fd); - else - return CheckReadOnlySharedMemoryMachPort(handle.memory_object_); -#elif defined(OS_FUCHSIA) - return CheckReadOnlySharedMemoryFuchsiaHandle(handle.GetHandle()); -#elif defined(OS_WIN) - return CheckReadOnlySharedMemoryWindowsHandle(handle.GetHandle()); -#else - return CheckReadOnlySharedMemoryFdPosix(handle.GetHandle()); -#endif -} - -bool CheckReadOnlyPlatformSharedMemoryRegionForTesting( - subtle::PlatformSharedMemoryRegion region) { - if (region.GetMode() != subtle::PlatformSharedMemoryRegion::Mode::kReadOnly) { - LOG(ERROR) << "Expected region mode is " - << static_cast<int>( - subtle::PlatformSharedMemoryRegion::Mode::kReadOnly) - << " but actual is " << static_cast<int>(region.GetMode()); - return false; - } - -#if defined(OS_MACOSX) && !defined(OS_IOS) - return CheckReadOnlySharedMemoryMachPort(region.GetPlatformHandle()); -#elif defined(OS_FUCHSIA) - return CheckReadOnlySharedMemoryFuchsiaHandle(region.GetPlatformHandle()); -#elif defined(OS_WIN) - return CheckReadOnlySharedMemoryWindowsHandle(region.GetPlatformHandle()); -#elif defined(OS_ANDROID) - return CheckReadOnlySharedMemoryFdPosix(region.GetPlatformHandle()); -#else - return CheckReadOnlySharedMemoryFdPosix(region.GetPlatformHandle().fd); -#endif -} - -#endif // !OS_NACL - -WritableSharedMemoryMapping MapForTesting( - subtle::PlatformSharedMemoryRegion* region) { - return MapAtForTesting(region, 0, region->GetSize()); -} - -WritableSharedMemoryMapping MapAtForTesting( - subtle::PlatformSharedMemoryRegion* region, - off_t offset, - size_t size) { - void* memory = nullptr; - size_t mapped_size = 0; - if (!region->MapAt(offset, size, &memory, &mapped_size)) - return {}; - - return WritableSharedMemoryMapping(memory, size, mapped_size, - region->GetGUID()); -} - -template <> -std::pair<ReadOnlySharedMemoryRegion, WritableSharedMemoryMapping> -CreateMappedRegion(size_t size) { - MappedReadOnlyRegion mapped_region = ReadOnlySharedMemoryRegion::Create(size); - return {std::move(mapped_region.region), std::move(mapped_region.mapping)}; -} - -} // namespace base
diff --git a/base/test/test_shared_memory_util.h b/base/test/test_shared_memory_util.h deleted file mode 100644 index d89f11d..0000000 --- a/base/test/test_shared_memory_util.h +++ /dev/null
@@ -1,56 +0,0 @@ -// Copyright 2017 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef BASE_TEST_TEST_SHARED_MEMORY_UTIL_H_ -#define BASE_TEST_TEST_SHARED_MEMORY_UTIL_H_ - -#include "base/memory/platform_shared_memory_region.h" -#include "base/memory/read_only_shared_memory_region.h" -#include "base/memory/shared_memory_handle.h" -#include "base/memory/shared_memory_mapping.h" -#include "testing/gtest/include/gtest/gtest.h" - -namespace base { - -// Check that the shared memory |handle| cannot be used to perform -// a writable mapping with low-level system APIs like mmap(). Return true -// in case of success (i.e. writable mappings are _not_ allowed), or false -// otherwise. -bool CheckReadOnlySharedMemoryHandleForTesting(SharedMemoryHandle handle); - -bool CheckReadOnlyPlatformSharedMemoryRegionForTesting( - subtle::PlatformSharedMemoryRegion region); - -// Creates a scoped mapping from a PlatformSharedMemoryRegion. It's useful for -// PlatformSharedMemoryRegion testing to not leak mapped memory. -// WritableSharedMemoryMapping is used for wrapping because it has max -// capabilities but the actual permission depends on the |region|'s mode. -// This must not be used in production where PlatformSharedMemoryRegion should -// be wrapped with {Writable,Unsafe,ReadOnly}SharedMemoryRegion. -WritableSharedMemoryMapping MapAtForTesting( - subtle::PlatformSharedMemoryRegion* region, - off_t offset, - size_t size); - -WritableSharedMemoryMapping MapForTesting( - subtle::PlatformSharedMemoryRegion* region); - -template <typename SharedMemoryRegionType> -std::pair<SharedMemoryRegionType, WritableSharedMemoryMapping> -CreateMappedRegion(size_t size) { - SharedMemoryRegionType region = SharedMemoryRegionType::Create(size); - WritableSharedMemoryMapping mapping = region.Map(); - return {std::move(region), std::move(mapping)}; -} - -// Template specialization of CreateMappedRegion<>() for -// the ReadOnlySharedMemoryRegion. We need this because -// ReadOnlySharedMemoryRegion::Create() has a different return type. -template <> -std::pair<ReadOnlySharedMemoryRegion, WritableSharedMemoryMapping> -CreateMappedRegion(size_t size); - -} // namespace base - -#endif // BASE_TEST_TEST_SHARED_MEMORY_UTIL_H_
diff --git a/base/test/test_shortcut_win.cc b/base/test/test_shortcut_win.cc deleted file mode 100644 index 70cb35b..0000000 --- a/base/test/test_shortcut_win.cc +++ /dev/null
@@ -1,156 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "base/test/test_shortcut_win.h" - -#include <windows.h> -#include <objbase.h> -#include <shlobj.h> -#include <propkey.h> -#include <wrl/client.h> - -#include "base/files/file_path.h" -#include "base/strings/string16.h" -#include "base/strings/utf_string_conversions.h" -#include "base/win/scoped_propvariant.h" -#include "testing/gtest/include/gtest/gtest.h" - -namespace base { -namespace win { - -void ValidatePathsAreEqual(const base::FilePath& expected_path, - const base::FilePath& actual_path) { - wchar_t long_expected_path_chars[MAX_PATH] = {0}; - wchar_t long_actual_path_chars[MAX_PATH] = {0}; - - // If |expected_path| is empty confirm immediately that |actual_path| is also - // empty. - if (expected_path.empty()) { - EXPECT_TRUE(actual_path.empty()); - return; - } - - // Proceed with LongPathName matching which will also confirm the paths exist. - EXPECT_NE(0U, ::GetLongPathName( - expected_path.value().c_str(), long_expected_path_chars, MAX_PATH)) - << "Failed to get LongPathName of " << expected_path.value(); - EXPECT_NE(0U, ::GetLongPathName( - actual_path.value().c_str(), long_actual_path_chars, MAX_PATH)) - << "Failed to get LongPathName of " << actual_path.value(); - - base::FilePath long_expected_path(long_expected_path_chars); - base::FilePath long_actual_path(long_actual_path_chars); - EXPECT_FALSE(long_expected_path.empty()); - EXPECT_FALSE(long_actual_path.empty()); - - EXPECT_EQ(long_expected_path, long_actual_path); -} - -void ValidateShortcut(const base::FilePath& shortcut_path, - const ShortcutProperties& properties) { - Microsoft::WRL::ComPtr<IShellLink> i_shell_link; - Microsoft::WRL::ComPtr<IPersistFile> i_persist_file; - - wchar_t read_target[MAX_PATH] = {0}; - wchar_t read_working_dir[MAX_PATH] = {0}; - wchar_t read_arguments[MAX_PATH] = {0}; - wchar_t read_description[MAX_PATH] = {0}; - wchar_t read_icon[MAX_PATH] = {0}; - int read_icon_index = 0; - - HRESULT hr; - - // Initialize the shell interfaces. - EXPECT_TRUE(SUCCEEDED(hr = ::CoCreateInstance(CLSID_ShellLink, NULL, - CLSCTX_INPROC_SERVER, - IID_PPV_ARGS(&i_shell_link)))); - if (FAILED(hr)) - return; - - EXPECT_TRUE( - SUCCEEDED(hr = i_shell_link.CopyTo(i_persist_file.GetAddressOf()))); - if (FAILED(hr)) - return; - - // Load the shortcut. - EXPECT_TRUE(SUCCEEDED(hr = i_persist_file->Load( - shortcut_path.value().c_str(), 0))) << "Failed to load shortcut at " - << shortcut_path.value(); - if (FAILED(hr)) - return; - - if (properties.options & ShortcutProperties::PROPERTIES_TARGET) { - EXPECT_TRUE(SUCCEEDED( - i_shell_link->GetPath(read_target, MAX_PATH, NULL, SLGP_SHORTPATH))); - ValidatePathsAreEqual(properties.target, base::FilePath(read_target)); - } - - if (properties.options & ShortcutProperties::PROPERTIES_WORKING_DIR) { - EXPECT_TRUE(SUCCEEDED( - i_shell_link->GetWorkingDirectory(read_working_dir, MAX_PATH))); - ValidatePathsAreEqual(properties.working_dir, - base::FilePath(read_working_dir)); - } - - if (properties.options & ShortcutProperties::PROPERTIES_ARGUMENTS) { - EXPECT_TRUE(SUCCEEDED( - i_shell_link->GetArguments(read_arguments, MAX_PATH))); - EXPECT_EQ(properties.arguments, read_arguments); - } - - if (properties.options & ShortcutProperties::PROPERTIES_DESCRIPTION) { - EXPECT_TRUE(SUCCEEDED( - i_shell_link->GetDescription(read_description, MAX_PATH))); - EXPECT_EQ(properties.description, read_description); - } - - if (properties.options & ShortcutProperties::PROPERTIES_ICON) { - EXPECT_TRUE(SUCCEEDED( - i_shell_link->GetIconLocation(read_icon, MAX_PATH, &read_icon_index))); - ValidatePathsAreEqual(properties.icon, base::FilePath(read_icon)); - EXPECT_EQ(properties.icon_index, read_icon_index); - } - - Microsoft::WRL::ComPtr<IPropertyStore> property_store; - EXPECT_TRUE( - SUCCEEDED(hr = i_shell_link.CopyTo(property_store.GetAddressOf()))); - if (FAILED(hr)) - return; - - if (properties.options & ShortcutProperties::PROPERTIES_APP_ID) { - ScopedPropVariant pv_app_id; - EXPECT_EQ(S_OK, property_store->GetValue(PKEY_AppUserModel_ID, - pv_app_id.Receive())); - switch (pv_app_id.get().vt) { - case VT_EMPTY: - EXPECT_TRUE(properties.app_id.empty()); - break; - case VT_LPWSTR: - EXPECT_EQ(properties.app_id, pv_app_id.get().pwszVal); - break; - default: - ADD_FAILURE() << "Unexpected variant type: " << pv_app_id.get().vt; - } - } - - if (properties.options & ShortcutProperties::PROPERTIES_DUAL_MODE) { - ScopedPropVariant pv_dual_mode; - EXPECT_EQ(S_OK, property_store->GetValue(PKEY_AppUserModel_IsDualMode, - pv_dual_mode.Receive())); - switch (pv_dual_mode.get().vt) { - case VT_EMPTY: - EXPECT_FALSE(properties.dual_mode); - break; - case VT_BOOL: - EXPECT_EQ(properties.dual_mode, - static_cast<bool>(pv_dual_mode.get().boolVal)); - break; - default: - ADD_FAILURE() << "Unexpected variant type: " << pv_dual_mode.get().vt; - } - } -} - -} // namespace win -} // namespace base
diff --git a/base/test/test_shortcut_win.h b/base/test/test_shortcut_win.h deleted file mode 100644 index b828e8b..0000000 --- a/base/test/test_shortcut_win.h +++ /dev/null
@@ -1,30 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef BASE_TEST_TEST_SHORTCUT_WIN_H_ -#define BASE_TEST_TEST_SHORTCUT_WIN_H_ - -#include "base/files/file_path.h" -#include "base/win/shortcut.h" - -// Windows shortcut functions used only by tests. - -namespace base { -namespace win { - -// Validates |actual_path|'s LongPathName case-insensitively matches -// |expected_path|'s LongPathName. -void ValidatePathsAreEqual(const base::FilePath& expected_path, - const base::FilePath& actual_path); - -// Validates that a shortcut exists at |shortcut_path| with the expected -// |properties|. -// Logs gtest failures on failed verifications. -void ValidateShortcut(const FilePath& shortcut_path, - const ShortcutProperties& properties); - -} // namespace win -} // namespace base - -#endif // BASE_TEST_TEST_SHORTCUT_WIN_H_
diff --git a/base/test/test_simple_task_runner.cc b/base/test/test_simple_task_runner.cc deleted file mode 100644 index 91c6861..0000000 --- a/base/test/test_simple_task_runner.cc +++ /dev/null
@@ -1,103 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "base/test/test_simple_task_runner.h" - -#include <utility> - -#include "base/logging.h" -#include "base/memory/ptr_util.h" -#include "base/threading/thread_task_runner_handle.h" - -namespace base { - -TestSimpleTaskRunner::TestSimpleTaskRunner() = default; - -TestSimpleTaskRunner::~TestSimpleTaskRunner() = default; - -bool TestSimpleTaskRunner::PostDelayedTask(const Location& from_here, - OnceClosure task, - TimeDelta delay) { - AutoLock auto_lock(lock_); - pending_tasks_.push_back(TestPendingTask(from_here, std::move(task), - TimeTicks(), delay, - TestPendingTask::NESTABLE)); - return true; -} - -bool TestSimpleTaskRunner::PostNonNestableDelayedTask(const Location& from_here, - OnceClosure task, - TimeDelta delay) { - AutoLock auto_lock(lock_); - pending_tasks_.push_back(TestPendingTask(from_here, std::move(task), - TimeTicks(), delay, - TestPendingTask::NON_NESTABLE)); - return true; -} - -// TODO(gab): Use SequenceToken here to differentiate between tasks running in -// the scope of this TestSimpleTaskRunner and other task runners sharing this -// thread. http://crbug.com/631186 -bool TestSimpleTaskRunner::RunsTasksInCurrentSequence() const { - return thread_ref_ == PlatformThread::CurrentRef(); -} - -base::circular_deque<TestPendingTask> TestSimpleTaskRunner::TakePendingTasks() { - AutoLock auto_lock(lock_); - return std::move(pending_tasks_); -} - -size_t TestSimpleTaskRunner::NumPendingTasks() const { - AutoLock auto_lock(lock_); - return pending_tasks_.size(); -} - -bool TestSimpleTaskRunner::HasPendingTask() const { - AutoLock auto_lock(lock_); - return !pending_tasks_.empty(); -} - -base::TimeDelta TestSimpleTaskRunner::NextPendingTaskDelay() const { - AutoLock auto_lock(lock_); - return pending_tasks_.front().GetTimeToRun() - base::TimeTicks(); -} - -base::TimeDelta TestSimpleTaskRunner::FinalPendingTaskDelay() const { - AutoLock auto_lock(lock_); - return pending_tasks_.back().GetTimeToRun() - base::TimeTicks(); -} - -void TestSimpleTaskRunner::ClearPendingTasks() { - AutoLock auto_lock(lock_); - pending_tasks_.clear(); -} - -void TestSimpleTaskRunner::RunPendingTasks() { - DCHECK(RunsTasksInCurrentSequence()); - - // Swap with a local variable to avoid re-entrancy problems. - base::circular_deque<TestPendingTask> tasks_to_run; - { - AutoLock auto_lock(lock_); - tasks_to_run.swap(pending_tasks_); - } - - // Multiple test task runners can share the same thread for determinism in - // unit tests. Make sure this TestSimpleTaskRunner's tasks run in its scope. - ScopedClosureRunner undo_override; - if (!ThreadTaskRunnerHandle::IsSet() || - ThreadTaskRunnerHandle::Get() != this) { - undo_override = ThreadTaskRunnerHandle::OverrideForTesting(this); - } - - for (auto& task : tasks_to_run) - std::move(task.task).Run(); -} - -void TestSimpleTaskRunner::RunUntilIdle() { - while (HasPendingTask()) - RunPendingTasks(); -} - -} // namespace base
diff --git a/base/test/test_simple_task_runner.h b/base/test/test_simple_task_runner.h deleted file mode 100644 index bff8ee5..0000000 --- a/base/test/test_simple_task_runner.h +++ /dev/null
@@ -1,89 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef BASE_TEST_TEST_SIMPLE_TASK_RUNNER_H_ -#define BASE_TEST_TEST_SIMPLE_TASK_RUNNER_H_ - -#include "base/callback.h" -#include "base/compiler_specific.h" -#include "base/containers/circular_deque.h" -#include "base/macros.h" -#include "base/single_thread_task_runner.h" -#include "base/synchronization/lock.h" -#include "base/test/test_pending_task.h" -#include "base/threading/platform_thread.h" - -namespace base { - -class TimeDelta; - -// TestSimpleTaskRunner is a simple TaskRunner implementation that can -// be used for testing. It implements SingleThreadTaskRunner as that -// interface implements SequencedTaskRunner, which in turn implements -// TaskRunner, so TestSimpleTaskRunner can be passed in to a function -// that accepts any *TaskRunner object. -// -// TestSimpleTaskRunner has the following properties which make it simple: -// -// - Tasks are simply stored in a queue in FIFO order, ignoring delay -// and nestability. -// - Tasks aren't guaranteed to be destroyed immediately after -// they're run. -// -// However, TestSimpleTaskRunner allows for reentrancy, in that it -// handles the running of tasks that in turn call back into itself -// (e.g., to post more tasks). -// -// Note that, like any TaskRunner, TestSimpleTaskRunner is -// ref-counted. -class TestSimpleTaskRunner : public SingleThreadTaskRunner { - public: - TestSimpleTaskRunner(); - - // SingleThreadTaskRunner implementation. - bool PostDelayedTask(const Location& from_here, - OnceClosure task, - TimeDelta delay) override; - bool PostNonNestableDelayedTask(const Location& from_here, - OnceClosure task, - TimeDelta delay) override; - - bool RunsTasksInCurrentSequence() const override; - - base::circular_deque<TestPendingTask> TakePendingTasks(); - size_t NumPendingTasks() const; - bool HasPendingTask() const; - base::TimeDelta NextPendingTaskDelay() const; - base::TimeDelta FinalPendingTaskDelay() const; - - // Clears the queue of pending tasks without running them. - void ClearPendingTasks(); - - // Runs each current pending task in order and clears the queue. Tasks posted - // by the tasks that run within this call do not run within this call. Can - // only be called on the thread that created this TestSimpleTaskRunner. - void RunPendingTasks(); - - // Runs pending tasks until the queue is empty. Can only be called on the - // thread that created this TestSimpleTaskRunner. - void RunUntilIdle(); - - protected: - ~TestSimpleTaskRunner() override; - - private: - // Thread on which this was instantiated. - const PlatformThreadRef thread_ref_ = PlatformThread::CurrentRef(); - - // Synchronizes access to |pending_tasks_|. - mutable Lock lock_; - - base::circular_deque<TestPendingTask> pending_tasks_; - - DISALLOW_COPY_AND_ASSIGN(TestSimpleTaskRunner); -}; - -} // namespace base - -#endif // BASE_TEST_TEST_SIMPLE_TASK_RUNNER_H_
diff --git a/base/test/test_suite.cc b/base/test/test_suite.cc deleted file mode 100644 index 3bbb983..0000000 --- a/base/test/test_suite.cc +++ /dev/null
@@ -1,484 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "base/test/test_suite.h" - -#include <signal.h> - -#include <memory> - -#include "base/at_exit.h" -#include "base/base_paths.h" -#include "base/base_switches.h" -#include "base/bind.h" -#include "base/command_line.h" -#include "base/debug/debugger.h" -#include "base/debug/profiler.h" -#include "base/debug/stack_trace.h" -#include "base/feature_list.h" -#include "base/files/file_path.h" -#include "base/files/file_util.h" -#include "base/i18n/icu_util.h" -#include "base/logging.h" -#include "base/macros.h" -#include "base/memory/ptr_util.h" -#include "base/path_service.h" -#include "base/process/launch.h" -#include "base/process/memory.h" -#include "base/test/gtest_xml_unittest_result_printer.h" -#include "base/test/gtest_xml_util.h" -#include "base/test/icu_test_util.h" -#include "base/test/launcher/unit_test_launcher.h" -#include "base/test/multiprocess_test.h" -#include "base/test/test_switches.h" -#include "base/test/test_timeouts.h" -#include "base/time/time.h" -#include "build_config.h" -#include "testing/gmock/include/gmock/gmock.h" -#include "testing/gtest/include/gtest/gtest.h" -#include "testing/multiprocess_func_list.h" - -#if defined(OS_MACOSX) -#include "base/mac/scoped_nsautorelease_pool.h" -#if defined(OS_IOS) -#include "base/test/test_listener_ios.h" -#endif // OS_IOS -#endif // OS_MACOSX - -#if !defined(OS_WIN) -#include "base/i18n/rtl.h" -#if !defined(OS_IOS) -#include "base/strings/string_util.h" -#include "third_party/icu/source/common/unicode/uloc.h" -#endif -#endif - -#if defined(OS_ANDROID) -#include "base/test/test_support_android.h" -#endif - -#if defined(OS_IOS) -#include "base/test/test_support_ios.h" -#endif - -#if defined(OS_LINUX) -#include "base/test/fontconfig_util_linux.h" -#endif - -namespace base { - -namespace { - -class MaybeTestDisabler : public testing::EmptyTestEventListener { - public: - void OnTestStart(const testing::TestInfo& test_info) override { - ASSERT_FALSE(TestSuite::IsMarkedMaybe(test_info)) - << "Probably the OS #ifdefs don't include all of the necessary " - "platforms.\nPlease ensure that no tests have the MAYBE_ prefix " - "after the code is preprocessed."; - } -}; - -class TestClientInitializer : public testing::EmptyTestEventListener { - public: - TestClientInitializer() - : old_command_line_(CommandLine::NO_PROGRAM) { - } - - void OnTestStart(const testing::TestInfo& test_info) override { - old_command_line_ = *CommandLine::ForCurrentProcess(); - } - - void OnTestEnd(const testing::TestInfo& test_info) override { - *CommandLine::ForCurrentProcess() = old_command_line_; - } - - private: - CommandLine old_command_line_; - - DISALLOW_COPY_AND_ASSIGN(TestClientInitializer); -}; - -std::string GetProfileName() { - static const char kDefaultProfileName[] = "test-profile-{pid}"; - CR_DEFINE_STATIC_LOCAL(std::string, profile_name, ()); - if (profile_name.empty()) { - const base::CommandLine& command_line = - *base::CommandLine::ForCurrentProcess(); - if (command_line.HasSwitch(switches::kProfilingFile)) - profile_name = command_line.GetSwitchValueASCII(switches::kProfilingFile); - else - profile_name = std::string(kDefaultProfileName); - } - return profile_name; -} - -void InitializeLogging() { -#if defined(OS_ANDROID) - InitAndroidTestLogging(); -#else - FilePath exe; - PathService::Get(FILE_EXE, &exe); - FilePath log_filename = exe.ReplaceExtension(FILE_PATH_LITERAL("log")); - logging::LoggingSettings settings; - settings.logging_dest = logging::LOG_TO_ALL; - settings.log_file = log_filename.value().c_str(); - settings.delete_old = logging::DELETE_OLD_LOG_FILE; - logging::InitLogging(settings); - // We want process and thread IDs because we may have multiple processes. - // Note: temporarily enabled timestamps in an effort to catch bug 6361. - logging::SetLogItems(true, true, true, true); -#endif // !defined(OS_ANDROID) -} - -} // namespace - -int RunUnitTestsUsingBaseTestSuite(int argc, char **argv) { - TestSuite test_suite(argc, argv); - return LaunchUnitTests(argc, argv, - Bind(&TestSuite::Run, Unretained(&test_suite))); -} - -TestSuite::TestSuite(int argc, char** argv) : initialized_command_line_(false) { - PreInitialize(); - InitializeFromCommandLine(argc, argv); - // Logging must be initialized before any thread has a chance to call logging - // functions. - InitializeLogging(); -} - -#if defined(OS_WIN) -TestSuite::TestSuite(int argc, wchar_t** argv) - : initialized_command_line_(false) { - PreInitialize(); - InitializeFromCommandLine(argc, argv); - // Logging must be initialized before any thread has a chance to call logging - // functions. - InitializeLogging(); -} -#endif // defined(OS_WIN) - -TestSuite::~TestSuite() { - if (initialized_command_line_) - CommandLine::Reset(); -} - -void TestSuite::InitializeFromCommandLine(int argc, char** argv) { - initialized_command_line_ = CommandLine::Init(argc, argv); - testing::InitGoogleTest(&argc, argv); - testing::InitGoogleMock(&argc, argv); - -#if defined(OS_IOS) - InitIOSRunHook(this, argc, argv); -#endif -} - -#if defined(OS_WIN) -void TestSuite::InitializeFromCommandLine(int argc, wchar_t** argv) { - // Windows CommandLine::Init ignores argv anyway. - initialized_command_line_ = CommandLine::Init(argc, NULL); - testing::InitGoogleTest(&argc, argv); - testing::InitGoogleMock(&argc, argv); -} -#endif // defined(OS_WIN) - -void TestSuite::PreInitialize() { -#if defined(OS_WIN) - testing::GTEST_FLAG(catch_exceptions) = false; -#endif - EnableTerminationOnHeapCorruption(); -#if defined(OS_LINUX) && defined(USE_AURA) - // When calling native char conversion functions (e.g wrctomb) we need to - // have the locale set. In the absence of such a call the "C" locale is the - // default. In the gtk code (below) gtk_init() implicitly sets a locale. - setlocale(LC_ALL, ""); -#endif // defined(OS_LINUX) && defined(USE_AURA) - - // On Android, AtExitManager is created in - // testing/android/native_test_wrapper.cc before main() is called. -#if !defined(OS_ANDROID) - at_exit_manager_.reset(new AtExitManager); -#endif - - // Don't add additional code to this function. Instead add it to - // Initialize(). See bug 6436. -} - - -// static -bool TestSuite::IsMarkedMaybe(const testing::TestInfo& test) { - return strncmp(test.name(), "MAYBE_", 6) == 0; -} - -void TestSuite::CatchMaybeTests() { - testing::TestEventListeners& listeners = - testing::UnitTest::GetInstance()->listeners(); - listeners.Append(new MaybeTestDisabler); -} - -void TestSuite::ResetCommandLine() { - testing::TestEventListeners& listeners = - testing::UnitTest::GetInstance()->listeners(); - listeners.Append(new TestClientInitializer); -} - -void TestSuite::AddTestLauncherResultPrinter() { - // Only add the custom printer if requested. - if (!CommandLine::ForCurrentProcess()->HasSwitch( - switches::kTestLauncherOutput)) { - return; - } - - FilePath output_path(CommandLine::ForCurrentProcess()->GetSwitchValuePath( - switches::kTestLauncherOutput)); - - // Do not add the result printer if output path already exists. It's an - // indicator there is a process printing to that file, and we're likely - // its child. Do not clobber the results in that case. - if (PathExists(output_path)) { - LOG(WARNING) << "Test launcher output path " << output_path.AsUTF8Unsafe() - << " exists. Not adding test launcher result printer."; - return; - } - - printer_ = new XmlUnitTestResultPrinter; - CHECK(printer_->Initialize(output_path)); - testing::TestEventListeners& listeners = - testing::UnitTest::GetInstance()->listeners(); - listeners.Append(printer_); -} - -// Don't add additional code to this method. Instead add it to -// Initialize(). See bug 6436. -int TestSuite::Run() { -#if defined(OS_IOS) - RunTestsFromIOSApp(); -#endif - -#if defined(OS_MACOSX) - mac::ScopedNSAutoreleasePool scoped_pool; -#endif - - Initialize(); - std::string client_func = - CommandLine::ForCurrentProcess()->GetSwitchValueASCII( - switches::kTestChildProcess); - - // Check to see if we are being run as a client process. - if (!client_func.empty()) - return multi_process_function_list::InvokeChildProcessTest(client_func); -#if defined(OS_IOS) - test_listener_ios::RegisterTestEndListener(); -#endif - - int result = RUN_ALL_TESTS(); - -#if defined(OS_MACOSX) - // This MUST happen before Shutdown() since Shutdown() tears down - // objects (such as NotificationService::current()) that Cocoa - // objects use to remove themselves as observers. - scoped_pool.Recycle(); -#endif - - Shutdown(); - - return result; -} - -void TestSuite::UnitTestAssertHandler(const char* file, - int line, - const base::StringPiece summary, - const base::StringPiece stack_trace) { -#if defined(OS_ANDROID) - // Correlating test stdio with logcat can be difficult, so we emit this - // helpful little hint about what was running. Only do this for Android - // because other platforms don't separate out the relevant logs in the same - // way. - const ::testing::TestInfo* const test_info = - ::testing::UnitTest::GetInstance()->current_test_info(); - if (test_info) { - LOG(ERROR) << "Currently running: " << test_info->test_case_name() << "." - << test_info->name(); - fflush(stderr); - } -#endif // defined(OS_ANDROID) - - // XmlUnitTestResultPrinter inherits gtest format, where assert has summary - // and message. In GTest, summary is just a logged text, and message is a - // logged text, concatenated with stack trace of assert. - // Concatenate summary and stack_trace here, to pass it as a message. - if (printer_) { - const std::string summary_str = summary.as_string(); - const std::string stack_trace_str = summary_str + stack_trace.as_string(); - printer_->OnAssert(file, line, summary_str, stack_trace_str); - } - - // The logging system actually prints the message before calling the assert - // handler. Just exit now to avoid printing too many stack traces. - _exit(1); -} - -#if defined(OS_WIN) -namespace { - -// Disable optimizations to prevent function folding or other transformations -// that will make the call stacks on failures more confusing. -#pragma optimize("", off) -// Handlers for invalid parameter, pure call, and abort. They generate a -// breakpoint to ensure that we get a call stack on these failures. -void InvalidParameter(const wchar_t* expression, - const wchar_t* function, - const wchar_t* file, - unsigned int line, - uintptr_t reserved) { - // CRT printed message is sufficient. - __debugbreak(); - _exit(1); -} - -void PureCall() { - fprintf(stderr, "Pure-virtual function call. Terminating.\n"); - __debugbreak(); - _exit(1); -} - -void AbortHandler(int signal) { - // Print EOL after the CRT abort message. - fprintf(stderr, "\n"); - __debugbreak(); -} -#pragma optimize("", on) - -} // namespace -#endif - -void TestSuite::SuppressErrorDialogs() { -#if defined(OS_WIN) - UINT new_flags = SEM_FAILCRITICALERRORS | - SEM_NOGPFAULTERRORBOX | - SEM_NOOPENFILEERRORBOX; - - // Preserve existing error mode, as discussed at - // http://blogs.msdn.com/oldnewthing/archive/2004/07/27/198410.aspx - UINT existing_flags = SetErrorMode(new_flags); - SetErrorMode(existing_flags | new_flags); - -#if defined(_DEBUG) - // Suppress the "Debug Assertion Failed" dialog. - // TODO(hbono): remove this code when gtest has it. - // http://groups.google.com/d/topic/googletestframework/OjuwNlXy5ac/discussion - _CrtSetReportFile(_CRT_ASSERT, _CRTDBG_FILE_STDERR); - _CrtSetReportMode(_CRT_ASSERT, _CRTDBG_MODE_FILE | _CRTDBG_MODE_DEBUG); - _CrtSetReportFile(_CRT_ERROR, _CRTDBG_FILE_STDERR); - _CrtSetReportMode(_CRT_ERROR, _CRTDBG_MODE_FILE | _CRTDBG_MODE_DEBUG); -#endif // defined(_DEBUG) - - // See crbug.com/783040 for test code to trigger all of these failures. - _set_invalid_parameter_handler(InvalidParameter); - _set_purecall_handler(PureCall); - signal(SIGABRT, AbortHandler); -#endif // defined(OS_WIN) -} - -void TestSuite::Initialize() { - const CommandLine* command_line = CommandLine::ForCurrentProcess(); -#if !defined(OS_IOS) - if (command_line->HasSwitch(switches::kWaitForDebugger)) { - debug::WaitForDebugger(60, true); - } -#endif - // Set up a FeatureList instance, so that code using that API will not hit a - // an error that it's not set. It will be cleared automatically. - // TestFeatureForBrowserTest1 and TestFeatureForBrowserTest2 used in - // ContentBrowserTestScopedFeatureListTest to ensure ScopedFeatureList keeps - // features from command line. - std::string enabled = - command_line->GetSwitchValueASCII(switches::kEnableFeatures); - std::string disabled = - command_line->GetSwitchValueASCII(switches::kDisableFeatures); - enabled += ",TestFeatureForBrowserTest1"; - disabled += ",TestFeatureForBrowserTest2"; - scoped_feature_list_.InitFromCommandLine(enabled, disabled); - - // The enable-features and disable-features flags were just slurped into a - // FeatureList, so remove them from the command line. Tests should enable and - // disable features via the ScopedFeatureList API rather than command-line - // flags. - CommandLine new_command_line(command_line->GetProgram()); - CommandLine::SwitchMap switches = command_line->GetSwitches(); - - switches.erase(switches::kEnableFeatures); - switches.erase(switches::kDisableFeatures); - - for (const auto& iter : switches) - new_command_line.AppendSwitchNative(iter.first, iter.second); - - *CommandLine::ForCurrentProcess() = new_command_line; - -#if defined(OS_IOS) - InitIOSTestMessageLoop(); -#endif // OS_IOS - -#if defined(OS_ANDROID) - InitAndroidTestMessageLoop(); -#endif // else defined(OS_ANDROID) - - CHECK(debug::EnableInProcessStackDumping()); -#if defined(OS_WIN) - RouteStdioToConsole(true); - // Make sure we run with high resolution timer to minimize differences - // between production code and test code. - Time::EnableHighResolutionTimer(true); -#endif // defined(OS_WIN) - - // In some cases, we do not want to see standard error dialogs. - if (!debug::BeingDebugged() && - !command_line->HasSwitch("show-error-dialogs")) { - SuppressErrorDialogs(); - debug::SetSuppressDebugUI(true); - assert_handler_ = std::make_unique<logging::ScopedLogAssertHandler>( - base::Bind(&TestSuite::UnitTestAssertHandler, base::Unretained(this))); - } - - base::test::InitializeICUForTesting(); - - // On the Mac OS X command line, the default locale is *_POSIX. In Chromium, - // the locale is set via an OS X locale API and is never *_POSIX. - // Some tests (such as those involving word break iterator) will behave - // differently and fail if we use *POSIX locale. Setting it to en_US here - // does not affect tests that explicitly overrides the locale for testing. - // This can be an issue on all platforms other than Windows. - // TODO(jshin): Should we set the locale via an OS X locale API here? -#if !defined(OS_WIN) -#if defined(OS_IOS) - i18n::SetICUDefaultLocale("en_US"); -#else - std::string default_locale(uloc_getDefault()); - if (EndsWith(default_locale, "POSIX", CompareCase::INSENSITIVE_ASCII)) - i18n::SetICUDefaultLocale("en_US"); -#endif -#endif - -#if defined(OS_LINUX) - // TODO(thomasanderson): Call TearDownFontconfig() in Shutdown(). It would - // currently crash because of leaked FcFontSet's in font_fallback_linux.cc. - SetUpFontconfig(); -#endif - - CatchMaybeTests(); - ResetCommandLine(); - AddTestLauncherResultPrinter(); - - TestTimeouts::Initialize(); - - trace_to_file_.BeginTracingFromCommandLineOptions(); - - base::debug::StartProfiling(GetProfileName()); -} - -void TestSuite::Shutdown() { - base::debug::StopProfiling(); -} - -} // namespace base
diff --git a/base/test/test_suite.h b/base/test/test_suite.h deleted file mode 100644 index 3547acf..0000000 --- a/base/test/test_suite.h +++ /dev/null
@@ -1,103 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef BASE_TEST_TEST_SUITE_H_ -#define BASE_TEST_TEST_SUITE_H_ - -// Defines a basic test suite framework for running gtest based tests. You can -// instantiate this class in your main function and call its Run method to run -// any gtest based tests that are linked into your executable. - -#include <memory> -#include <string> - -#include "base/at_exit.h" -#include "base/logging.h" -#include "base/macros.h" -#include "base/test/scoped_feature_list.h" -#include "base/test/trace_to_file.h" -#include "build_config.h" - -namespace testing { -class TestInfo; -} - -namespace base { - -class XmlUnitTestResultPrinter; - -// Instantiates TestSuite, runs it and returns exit code. -int RunUnitTestsUsingBaseTestSuite(int argc, char **argv); - -class TestSuite { - public: - // Match function used by the GetTestCount method. - typedef bool (*TestMatch)(const testing::TestInfo&); - - TestSuite(int argc, char** argv); -#if defined(OS_WIN) - TestSuite(int argc, wchar_t** argv); -#endif // defined(OS_WIN) - virtual ~TestSuite(); - - // Returns true if the test is marked as "MAYBE_". - // When using different prefixes depending on platform, we use MAYBE_ and - // preprocessor directives to replace MAYBE_ with the target prefix. - static bool IsMarkedMaybe(const testing::TestInfo& test); - - void CatchMaybeTests(); - - void ResetCommandLine(); - - void AddTestLauncherResultPrinter(); - - int Run(); - - protected: - // By default fatal log messages (e.g. from DCHECKs) result in error dialogs - // which gum up buildbots. Use a minimalistic assert handler which just - // terminates the process. - void UnitTestAssertHandler(const char* file, - int line, - const base::StringPiece summary, - const base::StringPiece stack_trace); - - // Disable crash dialogs so that it doesn't gum up the buildbot - virtual void SuppressErrorDialogs(); - - // Override these for custom initialization and shutdown handling. Use these - // instead of putting complex code in your constructor/destructor. - - virtual void Initialize(); - virtual void Shutdown(); - - // Make sure that we setup an AtExitManager so Singleton objects will be - // destroyed. - std::unique_ptr<base::AtExitManager> at_exit_manager_; - - private: - void InitializeFromCommandLine(int argc, char** argv); -#if defined(OS_WIN) - void InitializeFromCommandLine(int argc, wchar_t** argv); -#endif // defined(OS_WIN) - - // Basic initialization for the test suite happens here. - void PreInitialize(); - - test::TraceToFile trace_to_file_; - - bool initialized_command_line_; - - test::ScopedFeatureList scoped_feature_list_; - - XmlUnitTestResultPrinter* printer_ = nullptr; - - std::unique_ptr<logging::ScopedLogAssertHandler> assert_handler_; - - DISALLOW_COPY_AND_ASSIGN(TestSuite); -}; - -} // namespace base - -#endif // BASE_TEST_TEST_SUITE_H_
diff --git a/base/test/test_switches.cc b/base/test/test_switches.cc deleted file mode 100644 index a35bdd8..0000000 --- a/base/test/test_switches.cc +++ /dev/null
@@ -1,81 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "base/test/test_switches.h" - -// Maximum number of tests to run in a single batch. -const char switches::kTestLauncherBatchLimit[] = "test-launcher-batch-limit"; - -// Sets defaults desirable for the continuous integration bots, e.g. parallel -// test execution and test retries. -const char switches::kTestLauncherBotMode[] = - "test-launcher-bot-mode"; - -// Makes it possible to debug the launcher itself. By default the launcher -// automatically switches to single process mode when it detects presence -// of debugger. -const char switches::kTestLauncherDebugLauncher[] = - "test-launcher-debug-launcher"; - -// Force running all requested tests and retries even if too many test errors -// occur. -const char switches::kTestLauncherForceRunBrokenTests[] = - "test-launcher-force-run-broken-tests"; - -// Path to file containing test filter (one pattern per line). -const char switches::kTestLauncherFilterFile[] = "test-launcher-filter-file"; - -// Whether the test launcher should launch in "interactive mode", which disables -// timeouts (and may have other effects for specific test types). -const char switches::kTestLauncherInteractive[] = "test-launcher-interactive"; - -// Number of parallel test launcher jobs. -const char switches::kTestLauncherJobs[] = "test-launcher-jobs"; - -// Path to list of compiled in tests. -const char switches::kTestLauncherListTests[] = "test-launcher-list-tests"; - -// Path to test results file in our custom test launcher format. -const char switches::kTestLauncherOutput[] = "test-launcher-output"; - -// Maximum number of times to retry a test after failure. -const char switches::kTestLauncherRetryLimit[] = "test-launcher-retry-limit"; - -// Path to test results file with all the info from the test launcher. -const char switches::kTestLauncherSummaryOutput[] = - "test-launcher-summary-output"; - -// Flag controlling when test stdio is displayed as part of the launcher's -// standard output. -const char switches::kTestLauncherPrintTestStdio[] = - "test-launcher-print-test-stdio"; - -// Print a writable path and exit (for internal use). -const char switches::kTestLauncherPrintWritablePath[] = - "test-launcher-print-writable-path"; - -// Index of the test shard to run, starting from 0 (first shard) to total shards -// minus one (last shard). -const char switches::kTestLauncherShardIndex[] = - "test-launcher-shard-index"; - -// Limit of test part results in the output. Default limit is 10. -// Negative value will completely disable limit. -const char switches::kTestLauncherTestPartResultsLimit[] = - "test-launcher-test-part-results-limit"; - -// Total number of shards. Must be the same for all shards. -const char switches::kTestLauncherTotalShards[] = - "test-launcher-total-shards"; - -// Time (in milliseconds) that the tests should wait before timing out. -const char switches::kTestLauncherTimeout[] = "test-launcher-timeout"; - -// Path where to save a trace of test launcher's execution. -const char switches::kTestLauncherTrace[] = "test-launcher-trace"; - -// TODO(phajdan.jr): Clean up the switch names. -const char switches::kTestTinyTimeout[] = "test-tiny-timeout"; -const char switches::kUiTestActionTimeout[] = "ui-test-action-timeout"; -const char switches::kUiTestActionMaxTimeout[] = "ui-test-action-max-timeout";
diff --git a/base/test/test_switches.h b/base/test/test_switches.h deleted file mode 100644 index 6baba30..0000000 --- a/base/test/test_switches.h +++ /dev/null
@@ -1,36 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef BASE_TEST_TEST_SWITCHES_H_ -#define BASE_TEST_TEST_SWITCHES_H_ - -namespace switches { - -// All switches in alphabetical order. The switches should be documented -// alongside the definition of their values in the .cc file. -extern const char kTestLauncherBatchLimit[]; -extern const char kTestLauncherBotMode[]; -extern const char kTestLauncherDebugLauncher[]; -extern const char kTestLauncherForceRunBrokenTests[]; -extern const char kTestLauncherFilterFile[]; -extern const char kTestLauncherInteractive[]; -extern const char kTestLauncherJobs[]; -extern const char kTestLauncherListTests[]; -extern const char kTestLauncherOutput[]; -extern const char kTestLauncherRetryLimit[]; -extern const char kTestLauncherSummaryOutput[]; -extern const char kTestLauncherPrintTestStdio[]; -extern const char kTestLauncherPrintWritablePath[]; -extern const char kTestLauncherShardIndex[]; -extern const char kTestLauncherTestPartResultsLimit[]; -extern const char kTestLauncherTotalShards[]; -extern const char kTestLauncherTimeout[]; -extern const char kTestLauncherTrace[]; -extern const char kTestTinyTimeout[]; -extern const char kUiTestActionTimeout[]; -extern const char kUiTestActionMaxTimeout[]; - -} // namespace switches - -#endif // BASE_TEST_TEST_SWITCHES_H_
diff --git a/base/test/test_timeouts.cc b/base/test/test_timeouts.cc deleted file mode 100644 index 4c8b4ab..0000000 --- a/base/test/test_timeouts.cc +++ /dev/null
@@ -1,117 +0,0 @@ -// Copyright (c) 2011 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "base/test/test_timeouts.h" - -#include <algorithm> - -#include "base/command_line.h" -#include "base/debug/debugger.h" -#include "base/logging.h" -#include "base/strings/string_number_conversions.h" -#include "base/test/test_switches.h" -#include "build_config.h" - -namespace { - -// Sets value to the greatest of: -// 1) value's current value multiplied by kTimeoutMultiplier (assuming -// InitializeTimeout is called only once per value). -// 2) min_value. -// 3) the numerical value given by switch_name on the command line multiplied -// by kTimeoutMultiplier. -void InitializeTimeout(const char* switch_name, int min_value, int* value) { - DCHECK(value); - int command_line_timeout = 0; - if (base::CommandLine::ForCurrentProcess()->HasSwitch(switch_name)) { - std::string string_value(base::CommandLine::ForCurrentProcess()-> - GetSwitchValueASCII(switch_name)); - if (!base::StringToInt(string_value, &command_line_timeout)) { - LOG(FATAL) << "Timeout value \"" << string_value << "\" was parsed as " - << command_line_timeout; - } - } - -#if defined(MEMORY_SANITIZER) - // ASan/TSan/MSan instrument each memory access. This may slow the execution - // down significantly. - // For MSan the slowdown depends heavily on the value of msan_track_origins - // build flag. The multiplier below corresponds to msan_track_origins = 1. - constexpr int kTimeoutMultiplier = 6; -#elif defined(ADDRESS_SANITIZER) && defined(OS_WIN) - // ASan/Win has not been optimized yet, give it a higher - // timeout multiplier. See http://crbug.com/412471 - constexpr int kTimeoutMultiplier = 3; -#elif defined(ADDRESS_SANITIZER) || defined(THREAD_SANITIZER) - constexpr int kTimeoutMultiplier = 2; -#else - constexpr int kTimeoutMultiplier = 1; -#endif - - *value = std::max(std::max(*value, command_line_timeout) * kTimeoutMultiplier, - min_value); -} - -} // namespace - -// static -bool TestTimeouts::initialized_ = false; - -// The timeout values should increase in the order they appear in this block. -// static -int TestTimeouts::tiny_timeout_ms_ = 100; -int TestTimeouts::action_timeout_ms_ = 10000; -#ifndef NDEBUG -int TestTimeouts::action_max_timeout_ms_ = 45000; -#else -int TestTimeouts::action_max_timeout_ms_ = 30000; -#endif // NDEBUG - -int TestTimeouts::test_launcher_timeout_ms_ = 45000; - -// static -void TestTimeouts::Initialize() { - DCHECK(!initialized_); - initialized_ = true; - - if (base::debug::BeingDebugged()) { - fprintf(stdout, - "Detected presence of a debugger, running without test timeouts.\n"); - } - - // Note that these timeouts MUST be initialized in the correct order as - // per the CHECKS below. - - InitializeTimeout(switches::kTestTinyTimeout, 0, &tiny_timeout_ms_); - - // All timeouts other than the "tiny" one should be set to very large values - // when in a debugger or when run interactively, so that tests will not get - // auto-terminated. By setting the UI test action timeout to at least this - // value, we guarantee the subsequent timeouts will be this large also. - // Setting the "tiny" timeout to a large value as well would make some tests - // hang (because it's used as a task-posting delay). In particular this - // causes problems for some iOS device tests, which are always run inside a - // debugger (thus BeingDebugged() is true even on the bots). - int min_ui_test_action_timeout = tiny_timeout_ms_; - if (base::debug::BeingDebugged() || - base::CommandLine::ForCurrentProcess()->HasSwitch( - switches::kTestLauncherInteractive)) { - constexpr int kVeryLargeTimeoutMs = 100'000'000; - min_ui_test_action_timeout = kVeryLargeTimeoutMs; - } - - InitializeTimeout(switches::kUiTestActionTimeout, min_ui_test_action_timeout, - &action_timeout_ms_); - InitializeTimeout(switches::kUiTestActionMaxTimeout, action_timeout_ms_, - &action_max_timeout_ms_); - - // Test launcher timeout is independent from anything above action timeout. - InitializeTimeout(switches::kTestLauncherTimeout, action_timeout_ms_, - &test_launcher_timeout_ms_); - - // The timeout values should be increasing in the right order. - CHECK_LE(tiny_timeout_ms_, action_timeout_ms_); - CHECK_LE(action_timeout_ms_, action_max_timeout_ms_); - CHECK_LE(action_timeout_ms_, test_launcher_timeout_ms_); -}
diff --git a/base/test/test_timeouts.h b/base/test/test_timeouts.h deleted file mode 100644 index 71983ed..0000000 --- a/base/test/test_timeouts.h +++ /dev/null
@@ -1,61 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef BASE_TEST_TEST_TIMEOUTS_H_ -#define BASE_TEST_TEST_TIMEOUTS_H_ - -#include "base/logging.h" -#include "base/macros.h" -#include "base/time/time.h" - -// Returns common timeouts to use in tests. Makes it possible to adjust -// the timeouts for different environments (like TSan). -class TestTimeouts { - public: - // Initializes the timeouts. Non thread-safe. Should be called exactly once - // by the test suite. - static void Initialize(); - - // Timeout for actions that are expected to finish "almost instantly". This - // is used in various tests to post delayed tasks and usually functions more - // like a delay value than a timeout. - static base::TimeDelta tiny_timeout() { - DCHECK(initialized_); - return base::TimeDelta::FromMilliseconds(tiny_timeout_ms_); - } - - // Timeout to wait for something to happen. If you are not sure - // which timeout to use, this is the one you want. - static base::TimeDelta action_timeout() { - DCHECK(initialized_); - return base::TimeDelta::FromMilliseconds(action_timeout_ms_); - } - - // Timeout longer than the above, but still suitable to use - // multiple times in a single test. Use if the timeout above - // is not sufficient. - static base::TimeDelta action_max_timeout() { - DCHECK(initialized_); - return base::TimeDelta::FromMilliseconds(action_max_timeout_ms_); - } - - // Timeout for a single test launched used built-in test launcher. - // Do not use outside of the test launcher. - static base::TimeDelta test_launcher_timeout() { - DCHECK(initialized_); - return base::TimeDelta::FromMilliseconds(test_launcher_timeout_ms_); - } - - private: - static bool initialized_; - - static int tiny_timeout_ms_; - static int action_timeout_ms_; - static int action_max_timeout_ms_; - static int test_launcher_timeout_ms_; - - DISALLOW_IMPLICIT_CONSTRUCTORS(TestTimeouts); -}; - -#endif // BASE_TEST_TEST_TIMEOUTS_H_
diff --git a/base/test/thread_test_helper.cc b/base/test/thread_test_helper.cc deleted file mode 100644 index f3ca780..0000000 --- a/base/test/thread_test_helper.cc +++ /dev/null
@@ -1,41 +0,0 @@ -// Copyright (c) 2011 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "base/test/thread_test_helper.h" - -#include <utility> - -#include "base/bind.h" -#include "base/location.h" -#include "base/threading/thread_restrictions.h" - -namespace base { - -ThreadTestHelper::ThreadTestHelper( - scoped_refptr<SequencedTaskRunner> target_sequence) - : test_result_(false), - target_sequence_(std::move(target_sequence)), - done_event_(WaitableEvent::ResetPolicy::AUTOMATIC, - WaitableEvent::InitialState::NOT_SIGNALED) {} - -bool ThreadTestHelper::Run() { - if (!target_sequence_->PostTask( - FROM_HERE, base::BindOnce(&ThreadTestHelper::RunOnSequence, this))) { - return false; - } - base::ThreadRestrictions::ScopedAllowWait allow_wait; - done_event_.Wait(); - return test_result_; -} - -void ThreadTestHelper::RunTest() { set_test_result(true); } - -ThreadTestHelper::~ThreadTestHelper() = default; - -void ThreadTestHelper::RunOnSequence() { - RunTest(); - done_event_.Signal(); -} - -} // namespace base
diff --git a/base/test/thread_test_helper.h b/base/test/thread_test_helper.h deleted file mode 100644 index 935e7ef..0000000 --- a/base/test/thread_test_helper.h +++ /dev/null
@@ -1,50 +0,0 @@ -// Copyright (c) 2011 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef BASE_TEST_THREAD_TEST_HELPER_H_ -#define BASE_TEST_THREAD_TEST_HELPER_H_ - -#include "base/compiler_specific.h" -#include "base/macros.h" -#include "base/memory/ref_counted.h" -#include "base/sequenced_task_runner.h" -#include "base/synchronization/waitable_event.h" - -namespace base { - -// Helper class that executes code on a given target sequence/thread while -// blocking on the invoking sequence/thread. To use, derive from this class and -// overwrite RunTest. An alternative use of this class is to use it directly. It -// will then block until all pending tasks on a given sequence/thread have been -// executed. -class ThreadTestHelper : public RefCountedThreadSafe<ThreadTestHelper> { - public: - explicit ThreadTestHelper(scoped_refptr<SequencedTaskRunner> target_sequence); - - // True if RunTest() was successfully executed on the target sequence. - bool Run() WARN_UNUSED_RESULT; - - virtual void RunTest(); - - protected: - friend class RefCountedThreadSafe<ThreadTestHelper>; - - virtual ~ThreadTestHelper(); - - // Use this method to store the result of RunTest(). - void set_test_result(bool test_result) { test_result_ = test_result; } - - private: - void RunOnSequence(); - - bool test_result_; - scoped_refptr<SequencedTaskRunner> target_sequence_; - WaitableEvent done_event_; - - DISALLOW_COPY_AND_ASSIGN(ThreadTestHelper); -}; - -} // namespace base - -#endif // BASE_TEST_THREAD_TEST_HELPER_H_
diff --git a/base/test/trace_to_file.cc b/base/test/trace_to_file.cc deleted file mode 100644 index 17aa80b..0000000 --- a/base/test/trace_to_file.cc +++ /dev/null
@@ -1,106 +0,0 @@ -// Copyright (c) 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "base/test/trace_to_file.h" - -#include "base/base_switches.h" -#include "base/bind.h" -#include "base/command_line.h" -#include "base/files/file_util.h" -#include "base/memory/ref_counted_memory.h" -#include "base/run_loop.h" -#include "base/trace_event/trace_buffer.h" -#include "base/trace_event/trace_log.h" - -namespace base { -namespace test { - -TraceToFile::TraceToFile() : started_(false) { -} - -TraceToFile::~TraceToFile() { - EndTracingIfNeeded(); -} - -void TraceToFile::BeginTracingFromCommandLineOptions() { - DCHECK(CommandLine::InitializedForCurrentProcess()); - DCHECK(!started_); - - if (!CommandLine::ForCurrentProcess()->HasSwitch(switches::kTraceToFile)) - return; - - // Empty filter (i.e. just --trace-to-file) turns into default categories in - // TraceEventImpl - std::string filter = CommandLine::ForCurrentProcess()->GetSwitchValueASCII( - switches::kTraceToFile); - - FilePath path; - if (CommandLine::ForCurrentProcess()->HasSwitch(switches::kTraceToFileName)) { - path = FilePath(CommandLine::ForCurrentProcess() - ->GetSwitchValuePath(switches::kTraceToFileName)); - } else { - path = FilePath(FILE_PATH_LITERAL("trace.json")); - } - - BeginTracing(path, filter); -} - -void TraceToFile::BeginTracing(const FilePath& path, - const std::string& categories) { - DCHECK(!started_); - started_ = true; - path_ = path; - WriteFileHeader(); - - trace_event::TraceLog::GetInstance()->SetEnabled( - trace_event::TraceConfig(categories, trace_event::RECORD_UNTIL_FULL), - trace_event::TraceLog::RECORDING_MODE); -} - -void TraceToFile::WriteFileHeader() { - const char str[] = "{\"traceEvents\": ["; - WriteFile(path_, str, static_cast<int>(strlen(str))); -} - -void TraceToFile::AppendFileFooter() { - const char str[] = "]}"; - AppendToFile(path_, str, static_cast<int>(strlen(str))); -} - -void TraceToFile::TraceOutputCallback(const std::string& data) { - bool ret = AppendToFile(path_, data.c_str(), static_cast<int>(data.size())); - DCHECK(ret); -} - -static void OnTraceDataCollected( - Closure quit_closure, - trace_event::TraceResultBuffer* buffer, - const scoped_refptr<RefCountedString>& json_events_str, - bool has_more_events) { - buffer->AddFragment(json_events_str->data()); - if (!has_more_events) - quit_closure.Run(); -} - -void TraceToFile::EndTracingIfNeeded() { - if (!started_) - return; - started_ = false; - - trace_event::TraceLog::GetInstance()->SetDisabled(); - - trace_event::TraceResultBuffer buffer; - buffer.SetOutputCallback( - Bind(&TraceToFile::TraceOutputCallback, Unretained(this))); - - RunLoop run_loop; - trace_event::TraceLog::GetInstance()->Flush( - Bind(&OnTraceDataCollected, run_loop.QuitClosure(), Unretained(&buffer))); - run_loop.Run(); - - AppendFileFooter(); -} - -} // namespace test -} // namespace base
diff --git a/base/test/trace_to_file.h b/base/test/trace_to_file.h deleted file mode 100644 index 4308736..0000000 --- a/base/test/trace_to_file.h +++ /dev/null
@@ -1,35 +0,0 @@ -// Copyright (c) 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef BASE_TEST_TRACE_TO_FILE_H_ -#define BASE_TEST_TRACE_TO_FILE_H_ - -#include "base/files/file_path.h" - -namespace base { -namespace test { - -class TraceToFile { - public: - TraceToFile(); - ~TraceToFile(); - - void BeginTracingFromCommandLineOptions(); - void BeginTracing(const base::FilePath& path, const std::string& categories); - void EndTracingIfNeeded(); - - private: - void WriteFileHeader(); - void AppendFileFooter(); - - void TraceOutputCallback(const std::string& data); - - base::FilePath path_; - bool started_; -}; - -} // namespace test -} // namespace base - -#endif // BASE_TEST_TRACE_TO_FILE_H_
diff --git a/base/test/user_action_tester.cc b/base/test/user_action_tester.cc deleted file mode 100644 index 6c3de39..0000000 --- a/base/test/user_action_tester.cc +++ /dev/null
@@ -1,38 +0,0 @@ -// Copyright 2015 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "base/test/user_action_tester.h" - -#include "base/bind.h" -#include "base/bind_helpers.h" -#include "base/test/test_simple_task_runner.h" - -namespace base { - -UserActionTester::UserActionTester() - : task_runner_(new base::TestSimpleTaskRunner), - action_callback_( - base::Bind(&UserActionTester::OnUserAction, base::Unretained(this))) { - base::SetRecordActionTaskRunner(task_runner_); - base::AddActionCallback(action_callback_); -} - -UserActionTester::~UserActionTester() { - base::RemoveActionCallback(action_callback_); -} - -int UserActionTester::GetActionCount(const std::string& user_action) const { - UserActionCountMap::const_iterator iter = count_map_.find(user_action); - return iter == count_map_.end() ? 0 : iter->second; -} - -void UserActionTester::ResetCounts() { - count_map_.clear(); -} - -void UserActionTester::OnUserAction(const std::string& user_action) { - ++(count_map_[user_action]); -} - -} // namespace base
diff --git a/base/test/user_action_tester.h b/base/test/user_action_tester.h deleted file mode 100644 index 88bc632..0000000 --- a/base/test/user_action_tester.h +++ /dev/null
@@ -1,50 +0,0 @@ -// Copyright 2015 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef BASE_TEST_USER_ACTION_TESTER_H_ -#define BASE_TEST_USER_ACTION_TESTER_H_ - -#include <map> -#include <string> - -#include "base/macros.h" -#include "base/metrics/user_metrics.h" - -namespace base { - -// This class observes and collects user action notifications that are sent -// by the tests, so that they can be examined afterwards for correctness. -// Note: This class is NOT thread-safe. -class UserActionTester { - public: - UserActionTester(); - ~UserActionTester(); - - // Returns the number of times the given |user_action| occurred. - int GetActionCount(const std::string& user_action) const; - - // Resets all user action counts to 0. - void ResetCounts(); - - private: - typedef std::map<std::string, int> UserActionCountMap; - - // The callback that is notified when a user actions occurs. - void OnUserAction(const std::string& user_action); - - // A map that tracks the number of times a user action has occurred. - UserActionCountMap count_map_; - - // A test task runner used by user metrics. - scoped_refptr<base::SingleThreadTaskRunner> task_runner_; - - // The callback that is added to the global action callback list. - base::ActionCallback action_callback_; - - DISALLOW_COPY_AND_ASSIGN(UserActionTester); -}; - -} // namespace base - -#endif // BASE_TEST_USER_ACTION_TESTER_H_
diff --git a/base/test/values_test_util.cc b/base/test/values_test_util.cc deleted file mode 100644 index a65c2c0..0000000 --- a/base/test/values_test_util.cc +++ /dev/null
@@ -1,76 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "base/test/values_test_util.h" - -#include <memory> - -#include "base/json/json_reader.h" -#include "base/memory/ptr_util.h" -#include "base/strings/string_number_conversions.h" -#include "base/values.h" -#include "testing/gtest/include/gtest/gtest.h" - -namespace base { - -void ExpectDictBooleanValue(bool expected_value, - const DictionaryValue& value, - const std::string& key) { - bool boolean_value = false; - EXPECT_TRUE(value.GetBoolean(key, &boolean_value)) << key; - EXPECT_EQ(expected_value, boolean_value) << key; -} - -void ExpectDictDictionaryValue(const DictionaryValue& expected_value, - const DictionaryValue& value, - const std::string& key) { - const DictionaryValue* dict_value = nullptr; - EXPECT_TRUE(value.GetDictionary(key, &dict_value)) << key; - EXPECT_EQ(expected_value, *dict_value) << key; -} - -void ExpectDictIntegerValue(int expected_value, - const DictionaryValue& value, - const std::string& key) { - int integer_value = 0; - EXPECT_TRUE(value.GetInteger(key, &integer_value)) << key; - EXPECT_EQ(expected_value, integer_value) << key; -} - -void ExpectDictListValue(const ListValue& expected_value, - const DictionaryValue& value, - const std::string& key) { - const ListValue* list_value = nullptr; - EXPECT_TRUE(value.GetList(key, &list_value)) << key; - EXPECT_EQ(expected_value, *list_value) << key; -} - -void ExpectDictStringValue(const std::string& expected_value, - const DictionaryValue& value, - const std::string& key) { - std::string string_value; - EXPECT_TRUE(value.GetString(key, &string_value)) << key; - EXPECT_EQ(expected_value, string_value) << key; -} - -void ExpectStringValue(const std::string& expected_str, const Value& actual) { - EXPECT_EQ(Value::Type::STRING, actual.type()); - EXPECT_EQ(expected_str, actual.GetString()); -} - -namespace test { - -std::unique_ptr<Value> ParseJson(base::StringPiece json) { - std::string error_msg; - std::unique_ptr<Value> result = base::JSONReader::ReadAndReturnError( - json, base::JSON_ALLOW_TRAILING_COMMAS, nullptr, &error_msg); - if (!result) { - ADD_FAILURE() << "Failed to parse \"" << json << "\": " << error_msg; - result = std::make_unique<Value>(); - } - return result; -} - -} // namespace test -} // namespace base
diff --git a/base/test/values_test_util.h b/base/test/values_test_util.h deleted file mode 100644 index 02ebca1..0000000 --- a/base/test/values_test_util.h +++ /dev/null
@@ -1,53 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef BASE_TEST_VALUES_TEST_UTIL_H_ -#define BASE_TEST_VALUES_TEST_UTIL_H_ - -#include <memory> -#include <string> - -#include "base/strings/string_piece.h" - -namespace base { -class DictionaryValue; -class ListValue; -class Value; - -// All the functions below expect that the value for the given key in -// the given dictionary equals the given expected value. - -void ExpectDictBooleanValue(bool expected_value, - const DictionaryValue& value, - const std::string& key); - -void ExpectDictDictionaryValue(const DictionaryValue& expected_value, - const DictionaryValue& value, - const std::string& key); - -void ExpectDictIntegerValue(int expected_value, - const DictionaryValue& value, - const std::string& key); - -void ExpectDictListValue(const ListValue& expected_value, - const DictionaryValue& value, - const std::string& key); - -void ExpectDictStringValue(const std::string& expected_value, - const DictionaryValue& value, - const std::string& key); - -void ExpectStringValue(const std::string& expected_str, const Value& actual); - -namespace test { - -// Parses |json| as JSON, allowing trailing commas, and returns the -// resulting value. If the json fails to parse, causes an EXPECT -// failure and returns the Null Value (but never a NULL pointer). -std::unique_ptr<Value> ParseJson(base::StringPiece json); - -} // namespace test -} // namespace base - -#endif // BASE_TEST_VALUES_TEST_UTIL_H_