1// Copyright 2011 The Chromium Authors 2// Use of this source code is governed by a BSD-style license that can be 3// found in the LICENSE file. 4 5#import "base/mac/scoped_sending_event.h" 6 7#import <Foundation/Foundation.h> 8 9#include "testing/gtest/include/gtest/gtest.h" 10 11#ifdef LEAK_SANITIZER 12#include <sanitizer/lsan_interface.h> 13#endif 14 15@interface ScopedSendingEventTestCrApp : NSApplication <CrAppControlProtocol> { 16 @private 17 BOOL _handlingSendEvent; 18} 19@property(nonatomic, assign, getter=isHandlingSendEvent) BOOL handlingSendEvent; 20@end 21 22@implementation ScopedSendingEventTestCrApp 23@synthesize handlingSendEvent = _handlingSendEvent; 24@end 25 26namespace { 27 28class ScopedSendingEventTest : public testing::Test { 29 public: 30 ScopedSendingEventTest() { 31#ifdef LEAK_SANITIZER 32 // NSApplication's `init` creates a helper object and writes it to an 33 // AppKit-owned static unconditionally. This is not cleaned up on 34 // NSApplication dealloc. 35 // When we create a new NSApplication, as we do when we run multiple 36 // tests in this suite, a new object is created and stomps on the old 37 // static. 38 // This needs a scoped disabler instead of just ignoring the app 39 // object since the leak is a side-effect of object creation. 40 __lsan::ScopedDisabler disable; 41#endif 42 app_ = [[ScopedSendingEventTestCrApp alloc] init]; 43 NSApp = app_; 44 } 45 ~ScopedSendingEventTest() override { NSApp = nil; } 46 47 private: 48 ScopedSendingEventTestCrApp* __strong app_; 49}; 50 51// Sets the flag within scope, resets when leaving scope. 52TEST_F(ScopedSendingEventTest, SetHandlingSendEvent) { 53 id<CrAppProtocol> app = NSApp; 54 EXPECT_FALSE([app isHandlingSendEvent]); 55 { 56 base::mac::ScopedSendingEvent is_handling_send_event; 57 EXPECT_TRUE([app isHandlingSendEvent]); 58 } 59 EXPECT_FALSE([app isHandlingSendEvent]); 60} 61 62// Nested call restores previous value rather than resetting flag. 63TEST_F(ScopedSendingEventTest, NestedSetHandlingSendEvent) { 64 id<CrAppProtocol> app = NSApp; 65 EXPECT_FALSE([app isHandlingSendEvent]); 66 { 67 base::mac::ScopedSendingEvent is_handling_send_event; 68 EXPECT_TRUE([app isHandlingSendEvent]); 69 { 70 base::mac::ScopedSendingEvent nested_is_handling_send_event; 71 EXPECT_TRUE([app isHandlingSendEvent]); 72 } 73 EXPECT_TRUE([app isHandlingSendEvent]); 74 } 75 EXPECT_FALSE([app isHandlingSendEvent]); 76} 77 78} // namespace 79