Home | History | Annotate | Download | only in base
      1 // Copyright (c) 2011 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.
      4 
      5 #include "base/memory/ref_counted.h"
      6 #include "base/task.h"
      7 #include "testing/gtest/include/gtest/gtest.h"
      8 
      9 namespace {
     10 
     11 class CancelInDestructor : public base::RefCounted<CancelInDestructor> {
     12  public:
     13   CancelInDestructor() : cancelable_task_(NULL) {}
     14 
     15   void Start() {
     16     if (cancelable_task_) {
     17       ADD_FAILURE();
     18       return;
     19     }
     20     AddRef();
     21     cancelable_task_ = NewRunnableMethod(
     22         this, &CancelInDestructor::NeverIssuedCallback);
     23     Release();
     24   }
     25 
     26   CancelableTask* cancelable_task() {
     27     return cancelable_task_;
     28   }
     29 
     30  private:
     31   friend class base::RefCounted<CancelInDestructor>;
     32 
     33   ~CancelInDestructor() {
     34     if (cancelable_task_)
     35       cancelable_task_->Cancel();
     36   }
     37 
     38   void NeverIssuedCallback() { NOTREACHED(); }
     39 
     40   CancelableTask* cancelable_task_;
     41 };
     42 
     43 TEST(TaskTest, TestCancelInDestructor) {
     44   // Intentionally not using a scoped_refptr for cancel_in_destructor.
     45   CancelInDestructor* cancel_in_destructor = new CancelInDestructor();
     46   cancel_in_destructor->Start();
     47   CancelableTask* cancelable_task = cancel_in_destructor->cancelable_task();
     48   ASSERT_TRUE(cancelable_task);
     49   delete cancelable_task;
     50 }
     51 
     52 }  // namespace
     53