   }
 }
 
+/// Performs the given action on the main thread, synchronously, regardless of the current thread.
+func performOnMainThread(action: () -> ()) {
+  if NSThread.currentThread().isMainThread {
+    action()
+  } else {
+    dispatch_sync(dispatch_get_main_queue()) {
+      action()
+    }
+  }
+}
+
 /// Allows defining adversarial actions when a property is observed.
 class AdversaryObserver: FakeObserver {
   static var onNotification: Notification? = nil


/// Allows defining adversarial actions when an attribute is read.
class AdversaryWindowElement: TestWindowElement {
  static var onRead: Optional<(AdversaryWindowElement) -> ()> = nil
  static var watchAttribute: Attribute? = nil

  /// Call this in beforeEach for any tests that use this class.
  static func reset() {
    onRead = nil
    watchAttribute = nil
  }

  /// Defines code that runs on the main thread before returning the value of the attribute.
  static func onReadAttribute(attribute: Attribute, handler: (AdversaryWindowElement) -> ()) {
    AdversaryWindowElement.watchAttribute = attribute
    AdversaryWindowElement.onRead = handler
  }

  override func attribute<T>(attribute: Attribute) throws -> T? {
    let result: T? = try super.attribute(attribute)
    if attribute == AdversaryWindowElement.watchAttribute {
      AdversaryWindowElement.onRead?(self)
    }
    return result
  }
  override func getMultipleAttributes(attributes: [AXSwift.Attribute]) throws -> [Attribute : Any] {
    let result: [Attribute : Any] = try super.getMultipleAttributes(attributes)
    if let watchAttribute = AdversaryWindowElement.watchAttribute where attributes.contains(watchAttribute) {
      AdversaryWindowElement.onRead?(self)
    }
    return result
  }

    }

    describe("AXUIElement notifications") {
      var appElement: AdversaryApplicationElement!
      beforeEach {
        appElement = AdversaryApplicationElement()
      }
      beforeEach { AdversaryObserver.reset() }

      typealias AppDelegate = OSXApplicationDelegate<TestUIElement, AdversaryApplicationElement, AdversaryObserver>
      func initializeApp() -> Promise<AppDelegate> {
        return AppDelegate.initialize(axElement: appElement, notifier: notifier)
      }

      context("when a property value changes right before observing it") {

        context("for a regular property") {
          it("is read correctly") { () -> Promise<Void> in
