This source file includes following definitions.
- origin_loop_
- DoWork
- DoCallback
- DoSomething
- TEST_F
#include "base/bind.h"
#include "base/logging.h"
#include "base/message_loop/message_loop.h"
#include "base/threading/worker_pool.h"
#include "net/base/completion_callback.h"
#include "net/base/test_completion_callback.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "testing/platform_test.h"
typedef PlatformTest TestCompletionCallbackTest;
const int kMagicResult = 8888;
class ExampleEmployer {
public:
ExampleEmployer();
~ExampleEmployer();
bool DoSomething(const net::CompletionCallback& callback);
private:
class ExampleWorker;
friend class ExampleWorker;
scoped_refptr<ExampleWorker> request_;
DISALLOW_COPY_AND_ASSIGN(ExampleEmployer);
};
class ExampleEmployer::ExampleWorker
: public base::RefCountedThreadSafe<ExampleWorker> {
public:
ExampleWorker(ExampleEmployer* employer,
const net::CompletionCallback& callback)
: employer_(employer),
callback_(callback),
origin_loop_(base::MessageLoop::current()) {}
void DoWork();
void DoCallback();
private:
friend class base::RefCountedThreadSafe<ExampleWorker>;
~ExampleWorker() {}
ExampleEmployer* employer_;
net::CompletionCallback callback_;
base::Lock origin_loop_lock_;
base::MessageLoop* origin_loop_;
};
void ExampleEmployer::ExampleWorker::DoWork() {
{
base::AutoLock locked(origin_loop_lock_);
if (origin_loop_)
origin_loop_->PostTask(FROM_HERE,
base::Bind(&ExampleWorker::DoCallback, this));
}
}
void ExampleEmployer::ExampleWorker::DoCallback() {
employer_->request_ = NULL;
callback_.Run(kMagicResult);
}
ExampleEmployer::ExampleEmployer() {
}
ExampleEmployer::~ExampleEmployer() {
}
bool ExampleEmployer::DoSomething(const net::CompletionCallback& callback) {
DCHECK(!request_.get()) << "already in use";
request_ = new ExampleWorker(this, callback);
if (!base::WorkerPool::PostTask(
FROM_HERE,
base::Bind(&ExampleWorker::DoWork, request_.get()),
true)) {
NOTREACHED();
request_ = NULL;
return false;
}
return true;
}
TEST_F(TestCompletionCallbackTest, Simple) {
ExampleEmployer boss;
net::TestCompletionCallback callback;
bool queued = boss.DoSomething(callback.callback());
EXPECT_EQ(queued, true);
int result = callback.WaitForResult();
EXPECT_EQ(result, kMagicResult);
}