|
10 | 10 | import Segment |
11 | 11 | import XCTest |
12 | 12 |
|
| 13 | +// Changing existing context bits |
| 14 | +let updateContext = BlockMiddleware { (context, next) in |
| 15 | + if context.eventType == .track { |
| 16 | + next(context.modify { ctx in |
| 17 | + guard let track = ctx.payload as? TrackPayload else { |
| 18 | + return |
| 19 | + } |
| 20 | + let newEvent = "[New] \(track.event)" |
| 21 | + var newContext = track.context |
| 22 | + var device = newContext["device"] as! Dictionary<String, String> |
| 23 | + device["type"] = "mac" |
| 24 | + newContext["device"] = device |
| 25 | + ctx.payload = TrackPayload( |
| 26 | + event: newEvent, |
| 27 | + properties: track.properties, |
| 28 | + context: newContext, |
| 29 | + integrations: track.integrations |
| 30 | + ) |
| 31 | + }) |
| 32 | + } else { |
| 33 | + next(context) |
| 34 | + } |
| 35 | +} |
| 36 | + |
13 | 37 | // Changing event names and adding custom attributes |
14 | 38 | let customizeAllTrackCalls = BlockMiddleware { (context, next) in |
15 | 39 | if context.eventType == .track { |
@@ -38,6 +62,22 @@ let eatAllCalls = BlockMiddleware { (context, next) in |
38 | 62 | } |
39 | 63 |
|
40 | 64 | class SourceMiddlewareTests: XCTestCase { |
| 65 | + func testContextModification() { |
| 66 | + let config = AnalyticsConfiguration(writeKey: "TESTKEY") |
| 67 | + |
| 68 | + let passthrough = PassthroughMiddleware() |
| 69 | + config.sourceMiddleware = [ |
| 70 | + updateContext, |
| 71 | + passthrough |
| 72 | + ] |
| 73 | + let analytics = Analytics(configuration: config) |
| 74 | + analytics.track("testContext") |
| 75 | + XCTAssertEqual(passthrough.lastContext?.eventType, EventType.track) |
| 76 | + let track = passthrough.lastContext?.payload as? TrackPayload |
| 77 | + XCTAssertEqual(track?.event, "[New] testContext") |
| 78 | + let device = track?.context["device"] as? [String: Any] |
| 79 | + XCTAssertEqual(device?["type"] as? String, "mac") |
| 80 | + } |
41 | 81 |
|
42 | 82 | func testReceivesEvents() { |
43 | 83 | let config = AnalyticsConfiguration(writeKey: "TESTKEY") |
|
0 commit comments