1 // Copyright 2013 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "base/barrier_closure.h"
8 #include "base/callback_helpers.h"
9 #include "base/test/bind.h"
10 #include "base/test/gtest_util.h"
11 #include "testing/gtest/include/gtest/gtest.h"
15 TEST(BarrierClosureTest, RunImmediatelyForZeroClosures) {
17 base::RepeatingClosure barrier_closure = base::BarrierClosure(
18 0, base::BindLambdaForTesting([&count]() { ++count; }));
22 TEST(BarrierClosureTest, ChecksIfCalledForZeroClosures) {
23 base::RepeatingClosure barrier_closure =
24 base::BarrierClosure(0, base::DoNothing());
25 EXPECT_FALSE(barrier_closure.is_null());
27 EXPECT_CHECK_DEATH(barrier_closure.Run());
30 TEST(BarrierClosureTest, RunAfterNumClosures) {
32 base::RepeatingClosure barrier_closure = base::BarrierClosure(
33 2, base::BindLambdaForTesting([&count]() { ++count; }));
36 barrier_closure.Run();
39 barrier_closure.Run();
43 class DestructionIndicator {
45 // Sets |*destructed| to true in destructor.
46 DestructionIndicator(bool* destructed) : destructed_(destructed) {
50 ~DestructionIndicator() { *destructed_ = true; }
58 TEST(BarrierClosureTest, ReleasesDoneClosureWhenDone) {
59 bool done_destructed = false;
60 base::RepeatingClosure barrier_closure = base::BarrierClosure(
62 base::BindOnce(&DestructionIndicator::DoNothing,
63 base::Owned(new DestructionIndicator(&done_destructed))));
64 EXPECT_FALSE(done_destructed);
65 barrier_closure.Run();
66 EXPECT_TRUE(done_destructed);
69 // Tests a case when |done_closure| resets a |barrier_closure|.
70 // |barrier_closure| is a RepeatingClosure holding the |done_closure|.
71 // |done_closure| holds a pointer back to the |barrier_closure|. When
72 // |barrier_closure| is Run() it calls ResetBarrierClosure() which erases the
73 // |barrier_closure| while still inside of its Run(). The Run() implementation
74 // (in base::BarrierClosure) must not try use itself after executing
75 // ResetBarrierClosure() or this test would crash inside Run().
76 TEST(BarrierClosureTest, KeepingClosureAliveUntilDone) {
77 base::RepeatingClosure barrier_closure;
79 base::BarrierClosure(1, base::BindLambdaForTesting([&barrier_closure]() {
80 barrier_closure = base::RepeatingClosure();
82 barrier_closure.Run();
83 EXPECT_TRUE(barrier_closure.is_null());