Skip to content

Commit da87008

Browse files
bsneedBrandon Sneed
andauthored
Fixed issue where context modification is affected between events. (#987)
Co-authored-by: Brandon Sneed <[email protected]>
1 parent 2cb9021 commit da87008

File tree

2 files changed

+42
-1
lines changed

2 files changed

+42
-1
lines changed

Segment/Classes/SEGPayload.m

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
#import "SEGPayload.h"
22
#import "SEGState.h"
3+
#import "SEGUtils.h"
34

45
@implementation SEGPayload
56

@@ -16,7 +17,7 @@ - (instancetype)initWithContext:(NSDictionary *)context integrations:(NSDictiona
1617
[combinedContext addEntriesFromDictionary:internalContext];
1718
[combinedContext addEntriesFromDictionary:context];
1819

19-
_context = [combinedContext copy];
20+
_context = [combinedContext serializableDeepCopy];
2021
_integrations = [integrations copy];
2122
_messageId = nil;
2223
_userId = nil;

SegmentTests/MiddlewareTests.swift

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,30 @@
1010
import Segment
1111
import XCTest
1212

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+
1337
// Changing event names and adding custom attributes
1438
let customizeAllTrackCalls = BlockMiddleware { (context, next) in
1539
if context.eventType == .track {
@@ -38,6 +62,22 @@ let eatAllCalls = BlockMiddleware { (context, next) in
3862
}
3963

4064
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+
}
4181

4282
func testReceivesEvents() {
4383
let config = AnalyticsConfiguration(writeKey: "TESTKEY")

0 commit comments

Comments
 (0)