synchronous_event_unittest.cpp 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. // Licensed to the Apache Software Foundation (ASF) under one
  2. // or more contributor license agreements. See the NOTICE file
  3. // distributed with this work for additional information
  4. // regarding copyright ownership. The ASF licenses this file
  5. // to you under the Apache License, Version 2.0 (the
  6. // "License"); you may not use this file except in compliance
  7. // with the License. You may obtain a copy of the License at
  8. //
  9. // http://www.apache.org/licenses/LICENSE-2.0
  10. //
  11. // Unless required by applicable law or agreed to in writing,
  12. // software distributed under the License is distributed on an
  13. // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  14. // KIND, either express or implied. See the License for the
  15. // specific language governing permissions and limitations
  16. // under the License.
  17. #include <gtest/gtest.h>
  18. #include "butil/synchronous_event.h"
  19. namespace {
  20. class SynchronousEventTest : public ::testing::Test{
  21. protected:
  22. SynchronousEventTest(){
  23. };
  24. virtual ~SynchronousEventTest(){};
  25. virtual void SetUp() {
  26. srand(time(0));
  27. };
  28. virtual void TearDown() {
  29. };
  30. };
  31. struct Foo {};
  32. typedef butil::SynchronousEvent<int, int*> FooEvent;
  33. FooEvent foo_event;
  34. std::vector<std::pair<int, int> > result;
  35. class FooObserver : public FooEvent::Observer {
  36. public:
  37. FooObserver() : another_ob(NULL) {}
  38. void on_event(int x, int* p) {
  39. ++*p;
  40. result.push_back(std::make_pair(x, *p));
  41. if (another_ob) {
  42. foo_event.subscribe(another_ob);
  43. }
  44. }
  45. FooObserver* another_ob;
  46. };
  47. TEST_F(SynchronousEventTest, sanity) {
  48. const size_t N = 10;
  49. FooObserver foo_observer;
  50. FooObserver foo_observer2;
  51. foo_observer.another_ob = &foo_observer2;
  52. foo_event.subscribe(&foo_observer);
  53. int v = 0;
  54. result.clear();
  55. for (size_t i = 0; i < N; ++i) {
  56. foo_event.notify(i, &v);
  57. }
  58. ASSERT_EQ(2*N, result.size());
  59. for (size_t i = 0; i < 2*N; ++i) {
  60. ASSERT_EQ((int)i/2, result[i].first);
  61. ASSERT_EQ((int)i+1, result[i].second);
  62. }
  63. }
  64. }