Skip to content
This repository has been archived by the owner on Dec 5, 2022. It is now read-only.

Commit

Permalink
Merge pull request #45 from zalando/bugfix/GH-4-come-back-to-app
Browse files Browse the repository at this point in the history
GH-4 Added reactivation of the app after each action is generated
  • Loading branch information
DmitryBespalov authored Nov 1, 2017
2 parents dbde004 + 1f7bfbb commit 1e14f2f
Showing 1 changed file with 33 additions and 6 deletions.
39 changes: 33 additions & 6 deletions SwiftMonkey/Monkey.swift
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
//

import UIKit
import XCTest

/**
A general-purpose class for implementing randomised
Expand Down Expand Up @@ -59,13 +60,15 @@ import UIKit
```
*/
public class Monkey {
public typealias ActionClosure = () -> Void

var r: Random
let frame: CGRect

var randomActions: [(accumulatedWeight: Double, action: () -> Void)]
var randomActions: [(accumulatedWeight: Double, action: ActionClosure)]
var totalWeight: Double

var regularActions: [(interval: Int, action: () -> Void)]
var regularActions: [(interval: Int, action: ActionClosure)]
var actionCounter = 0

/**
Expand Down Expand Up @@ -191,9 +194,9 @@ public class Monkey {
- parameter action: The block to run when this event
is generated.
*/
public func addAction(weight: Double, action: @escaping () -> Void) {
public func addAction(weight: Double, action: @escaping ActionClosure) {
totalWeight += weight
randomActions.append((accumulatedWeight: totalWeight, action: action))
randomActions.append((accumulatedWeight: totalWeight, action: actInForeground(action)))
}

/**
Expand All @@ -205,8 +208,32 @@ public class Monkey {
- parameter action: The block to run when this event
is generated.
*/
public func addAction(interval: Int, action: @escaping () -> Void) {
regularActions.append((interval: interval, action: action))
public func addAction(interval: Int, action: @escaping ActionClosure) {
regularActions.append((interval: interval, action: actInForeground(action)))
}

/**
Wrap your action with this function to make sure your actions are dispatched inside the app under test
and not in some other app that the Monkey randomly opened.
*/
func actInForeground(_ action: @escaping ActionClosure) -> ActionClosure {
return {
guard #available(iOS 9.0, *) else {
action()
return
}
let closure: ActionClosure = {
if XCUIApplication().state != .runningForeground {
XCUIApplication().activate()
}
action()
}
if Thread.isMainThread {
closure()
} else {
DispatchQueue.main.async(execute: closure)
}
}
}

/**
Expand Down

0 comments on commit 1e14f2f

Please sign in to comment.