Make fml::ScopedCleanupClosure std::move-able and add unit tests. (flutter/engine#45772)

Fixes https://github.com/flutter/flutter/issues/134568.
This commit is contained in:
Matan Lurey
2023-09-14 11:37:49 -07:00
committed by GitHub
parent 53bcc75ea6
commit 0f4cb0b4c8
4 changed files with 83 additions and 1 deletions

View File

@@ -83,6 +83,7 @@
../../../flutter/fml/ascii_trie_unittests.cc
../../../flutter/fml/backtrace_unittests.cc
../../../flutter/fml/base32_unittest.cc
../../../flutter/fml/closure_unittests.cc
../../../flutter/fml/command_line_unittest.cc
../../../flutter/fml/container_unittests.cc
../../../flutter/fml/endianness_unittests.cc

View File

@@ -319,6 +319,7 @@ if (enable_unittests) {
"ascii_trie_unittests.cc",
"backtrace_unittests.cc",
"base32_unittest.cc",
"closure_unittests.cc",
"command_line_unittest.cc",
"container_unittests.cc",
"endianness_unittests.cc",

View File

@@ -29,10 +29,19 @@ using closure = std::function<void()>;
/// automatically at the end of the scope. This covers the cases
/// where there are early returns as well.
///
class ScopedCleanupClosure {
class ScopedCleanupClosure final {
public:
ScopedCleanupClosure() = default;
ScopedCleanupClosure(ScopedCleanupClosure&& other) {
closure_ = other.Release();
}
ScopedCleanupClosure& operator=(ScopedCleanupClosure&& other) {
closure_ = other.Release();
return *this;
}
explicit ScopedCleanupClosure(const fml::closure& closure)
: closure_(closure) {}

View File

@@ -0,0 +1,71 @@
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "fml/closure.h"
#include "gtest/gtest.h"
TEST(ScopedCleanupClosureTest, DestructorDoesNothingWhenNoClosureSet) {
fml::ScopedCleanupClosure cleanup;
// Nothing should happen.
}
TEST(ScopedCleanupClosureTest, ReleaseDoesNothingWhenNoClosureSet) {
fml::ScopedCleanupClosure cleanup;
// Nothing should happen.
EXPECT_EQ(nullptr, cleanup.Release());
}
TEST(ScopedCleanupClosureTest, ClosureInvokedOnDestructorWhenSetInConstructor) {
auto invoked = false;
{
fml::ScopedCleanupClosure cleanup([&invoked]() { invoked = true; });
EXPECT_FALSE(invoked);
}
EXPECT_TRUE(invoked);
}
TEST(ScopedCleanupClosureTest, ClosureInvokedOnDestructorWhenSet) {
auto invoked = false;
{
fml::ScopedCleanupClosure cleanup;
cleanup.SetClosure([&invoked]() { invoked = true; });
EXPECT_FALSE(invoked);
}
EXPECT_TRUE(invoked);
}
TEST(ScopedCleanupClosureTest, ClosureNotInvokedWhenMoved) {
auto invoked = 0;
{
fml::ScopedCleanupClosure cleanup([&invoked]() { invoked++; });
fml::ScopedCleanupClosure cleanup2(std::move(cleanup));
EXPECT_EQ(0, invoked);
}
EXPECT_EQ(1, invoked);
}
TEST(ScopedCleanupClosureTest, ClosureNotInvokedWhenMovedViaAssignment) {
auto invoked = 0;
{
fml::ScopedCleanupClosure cleanup([&invoked]() { invoked++; });
fml::ScopedCleanupClosure cleanup2;
cleanup2 = std::move(cleanup);
EXPECT_EQ(0, invoked);
}
EXPECT_EQ(1, invoked);
}