Home | History | Annotate | Download | only in base
      1 // Copyright (c) 2006-2008 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 #ifndef NET_BASE_TEST_COMPLETION_CALLBACK_H_
      6 #define NET_BASE_TEST_COMPLETION_CALLBACK_H_
      7 
      8 #include "base/message_loop.h"
      9 #include "net/base/completion_callback.h"
     10 #include "net/base/net_errors.h"
     11 
     12 //-----------------------------------------------------------------------------
     13 // completion callback helper
     14 
     15 // A helper class for completion callbacks, designed to make it easy to run
     16 // tests involving asynchronous operations.  Just call WaitForResult to wait
     17 // for the asynchronous operation to complete.
     18 //
     19 // NOTE: Since this runs a message loop to wait for the completion callback,
     20 // there could be other side-effects resulting from WaitForResult.  For this
     21 // reason, this class is probably not ideal for a general application.
     22 //
     23 class TestCompletionCallback : public CallbackRunner< Tuple1<int> > {
     24  public:
     25   TestCompletionCallback()
     26       : result_(0),
     27         have_result_(false),
     28         waiting_for_result_(false) {
     29   }
     30 
     31   int WaitForResult() {
     32     DCHECK(!waiting_for_result_);
     33     while (!have_result_) {
     34       waiting_for_result_ = true;
     35       MessageLoop::current()->Run();
     36       waiting_for_result_ = false;
     37     }
     38     have_result_ = false;  // auto-reset for next callback
     39     return result_;
     40   }
     41 
     42   int GetResult(int result) {
     43     if (net::ERR_IO_PENDING != result)
     44       return result;
     45     return WaitForResult();
     46   }
     47 
     48   bool have_result() const { return have_result_; }
     49 
     50   virtual void RunWithParams(const Tuple1<int>& params) {
     51     result_ = params.a;
     52     have_result_ = true;
     53     if (waiting_for_result_)
     54       MessageLoop::current()->Quit();
     55   }
     56 
     57  private:
     58   int result_;
     59   bool have_result_;
     60   bool waiting_for_result_;
     61 };
     62 
     63 #endif  // NET_BASE_TEST_COMPLETION_CALLBACK_H_
     64