2 * Licensed to the Apache Software Foundation (ASF) under one
3 * or more contributor license agreements. See the NOTICE file
4 * distributed with this work for additional information
5 * regarding copyright ownership. The ASF licenses this file
6 * to you under the Apache License, Version 2.0 (the
7 * "License"); you may not use this file except in compliance
8 * with the License. You may obtain a copy of the License at
10 * http://www.apache.org/licenses/LICENSE-2.0
12 * Unless required by applicable law or agreed to in writing,
13 * software distributed under the License is distributed on an
14 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15 * KIND, either express or implied. See the License for the
16 * specific language governing permissions and limitations
19 #include <gtest/gtest.h>
22 #include <folly/io/async/EventBase.h>
23 #include <folly/io/async/Request.h>
25 using namespace folly;
27 class TestData : public RequestData {
29 explicit TestData(int data) : data_(data) {}
30 ~TestData() override {}
34 TEST(RequestContext, SimpleTest) {
38 // There should always be a default context with get()
39 EXPECT_TRUE(RequestContext::get() != nullptr);
42 // but not with saveContext()
43 EXPECT_EQ(RequestContext::saveContext(), nullptr);
44 RequestContext::create();
45 EXPECT_NE(RequestContext::saveContext(), nullptr);
46 RequestContext::create();
47 EXPECT_NE(RequestContext::saveContext(), nullptr);
49 EXPECT_EQ(nullptr, RequestContext::get()->getContextData("test"));
51 RequestContext::get()->setContextData(
53 std::unique_ptr<TestData>(new TestData(10)));
54 base.runInEventBaseThread([&](){
55 EXPECT_TRUE(RequestContext::get() != nullptr);
56 auto data = dynamic_cast<TestData*>(
57 RequestContext::get()->getContextData("test"))->data_;
59 base.terminateLoopSoon();
61 auto th = std::thread([&](){
65 EXPECT_TRUE(RequestContext::get() != nullptr);
66 auto a = dynamic_cast<TestData*>(
67 RequestContext::get()->getContextData("test"));
71 RequestContext::setContext(std::shared_ptr<RequestContext>());
72 // There should always be a default context
73 EXPECT_TRUE(nullptr != RequestContext::get());
76 int main(int argc, char** argv) {
77 testing::InitGoogleTest(&argc, argv);
78 google::InitGoogleLogging(argv[0]);
79 google::ParseCommandLineFlags(&argc, &argv, true);
81 return RUN_ALL_TESTS();