diff --git a/pulsar-client-cpp/tests/ClientTest.cc b/pulsar-client-cpp/tests/ClientTest.cc index cac6a81a5617c..90ece8d4bccda 100644 --- a/pulsar-client-cpp/tests/ClientTest.cc +++ b/pulsar-client-cpp/tests/ClientTest.cc @@ -20,6 +20,7 @@ #include "HttpHelper.h" #include "PulsarFriend.h" +#include "WaitUtils.h" #include #include @@ -219,9 +220,13 @@ TEST(ClientTest, testReferenceCount) { ASSERT_EQ(producers.size(), 1); ASSERT_EQ(producers[0].use_count(), 0); ASSERT_EQ(consumers.size(), 2); - ASSERT_EQ(consumers[0].use_count(), 0); - ASSERT_EQ(consumers[1].use_count(), 0); - ASSERT_EQ(readerWeakPtr.use_count(), 0); + + waitUntil(std::chrono::seconds(1), [&consumers, &readerWeakPtr] { + return consumers[0].use_count() == 0 && consumers[1].use_count() == 0 && readerWeakPtr.expired(); + }); + EXPECT_EQ(consumers[0].use_count(), 0); + EXPECT_EQ(consumers[1].use_count(), 0); + EXPECT_EQ(readerWeakPtr.use_count(), 0); client.close(); } diff --git a/pulsar-client-cpp/tests/WaitUtils.h b/pulsar-client-cpp/tests/WaitUtils.h new file mode 100644 index 0000000000000..abe3efccff488 --- /dev/null +++ b/pulsar-client-cpp/tests/WaitUtils.h @@ -0,0 +1,43 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +#pragma once + +#include +#include +#include + +namespace pulsar { + +template +inline void waitUntil(std::chrono::duration timeout, std::function condition) { + auto timeoutMs = std::chrono::duration_cast(timeout).count(); + while (timeoutMs > 0) { + auto now = std::chrono::high_resolution_clock::now(); + if (condition()) { + break; + } + std::this_thread::sleep_for(std::chrono::milliseconds(10)); + auto elapsed = std::chrono::duration_cast( + std::chrono::high_resolution_clock::now() - now) + .count(); + timeoutMs -= elapsed; + } +} + +} // namespace pulsar