forked from mapbox/mapbox-directions-swift
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathVisualInstructionTests.swift
344 lines (286 loc) · 16.1 KB
/
VisualInstructionTests.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
import XCTest
#if !os(Linux)
import CoreLocation
import OHHTTPStubs
#if SWIFT_PACKAGE
import OHHTTPStubsSwift
#endif
@testable import MapboxDirections
class VisualInstructionsTests: XCTestCase {
override func tearDown() {
HTTPStubs.removeAllStubs()
super.tearDown()
}
func testCoding() {
let bannerJSON: [String: Any?] = [
"distanceAlongGeometry": 393.3,
"primary": [
"text": "Weinstock Strasse",
"components": [
[
"text": "Weinstock Strasse",
"type": "text",
],
],
"type": "turn",
"modifier": "right",
],
"secondary": nil,
"view": [
"text": "CA01610_1_E",
"components": [
[
"text": "CA01610_1_E",
"type": "guidance-view",
"imageURL": "https://www.mapbox.com/navigation"
],
],
"type": "fork",
"modifier": "right"
],
]
let bannerData = try! JSONSerialization.data(withJSONObject: bannerJSON, options: [])
var banner: VisualInstructionBanner?
XCTAssertNoThrow(banner = try JSONDecoder().decode(VisualInstructionBanner.self, from: bannerData))
XCTAssertNotNil(banner)
if let banner = banner {
XCTAssertEqual(banner.distanceAlongStep, 393.3, accuracy: 1e-1)
XCTAssertEqual(banner.primaryInstruction.text, "Weinstock Strasse")
XCTAssertEqual(banner.primaryInstruction.components.count, 1)
XCTAssertEqual(banner.primaryInstruction.maneuverType, .turn)
XCTAssertEqual(banner.primaryInstruction.maneuverDirection, .right)
XCTAssertNil(banner.secondaryInstruction)
XCTAssertNotNil(banner.quaternaryInstruction)
XCTAssertEqual(banner.quaternaryInstruction?.components.count, 1)
XCTAssertEqual(banner.drivingSide, .default)
}
let componentGuidanceViewImage = banner?.quaternaryInstruction?.components.first
XCTAssertNotNil(componentGuidanceViewImage)
let component = VisualInstruction.Component.text(text: .init(text: "Weinstock Strasse", abbreviation: nil, abbreviationPriority: nil))
let primaryInstruction = VisualInstruction(text: "Weinstock Strasse", maneuverType: .turn, maneuverDirection: .right, components: [component])
let guideViewComponent = VisualInstruction.Component.guidanceView(image: GuidanceViewImageRepresentation(imageURL: URL(string: "https://www.mapbox.com/navigation")), alternativeText: VisualInstruction.Component.TextRepresentation(text: "CA01610_1_E", abbreviation: nil, abbreviationPriority: nil))
XCTAssert(componentGuidanceViewImage == guideViewComponent)
let quaternaryInstruction = VisualInstruction(text: "CA01610_1_E", maneuverType: .reachFork, maneuverDirection: .right, components: [guideViewComponent])
banner = VisualInstructionBanner(distanceAlongStep: 393.3, primary: primaryInstruction, secondary: nil, tertiary: nil, quaternary: quaternaryInstruction, drivingSide: .right)
let encoder = JSONEncoder()
var encodedData: Data?
XCTAssertNoThrow(encodedData = try encoder.encode(banner))
XCTAssertNotNil(encodedData)
if let encodedData = encodedData {
var encodedBannerJSON: [String: Any?]?
XCTAssertNoThrow(encodedBannerJSON = try JSONSerialization.jsonObject(with: encodedData, options: []) as? [String: Any?])
XCTAssertNotNil(encodedBannerJSON)
// Verify then remove keys that wouldn’t necessarily be part of a BannerInstruction object in the Directions API response.
XCTAssertEqual(encodedBannerJSON?["drivingSide"] as? String, "right")
encodedBannerJSON?.removeValue(forKey: "drivingSide")
encodedBannerJSON?.updateValue(nil, forKey: "secondary")
XCTAssert(JSONSerialization.objectsAreEqual(bannerJSON, encodedBannerJSON, approximate: false))
}
}
func testPrimaryAndSecondaryInstructions() {
let expectation = self.expectation(description: "calculating directions with primary and secondary instructions should return results")
let queryParams: [String: String?] = [
"alternatives": "false",
"geometries": "polyline",
"overview": "full",
"steps": "true",
"continue_straight": "true",
"access_token": BogusToken,
"voice_instructions": "true",
"voice_units": "imperial",
"banner_instructions": "true",
"waypoint_names": "the hotel;the gym"
]
stub(condition: isHost("api.mapbox.com")
&& containsQueryParams(queryParams)) { _ in
let path = Bundle.module.path(forResource: "instructions", ofType: "json")
return HTTPStubsResponse(fileAtPath: path!, statusCode: 200, headers: ["Content-Type": "application/json"])
}
let startWaypoint = Waypoint(location: CLLocation(latitude: 37.780602, longitude: -122.431373), heading: nil, name: "the hotel")
let endWaypoint = Waypoint(location: CLLocation(latitude: 37.758859, longitude: -122.404058), heading: nil, name: "the gym")
let options = RouteOptions(waypoints: [startWaypoint, endWaypoint], profileIdentifier: .automobileAvoidingTraffic)
options.shapeFormat = .polyline
options.includesSteps = true
options.includesAlternativeRoutes = false
options.routeShapeResolution = .full
options.includesSpokenInstructions = true
options.distanceMeasurementSystem = .imperial
options.includesVisualInstructions = true
var response: RouteResponse!
let task = Directions(credentials: BogusCredentials).calculate(options) { (session, result) in
switch result {
case let .failure(error):
XCTFail("Error! \(error)")
case let .success(resp):
response = resp
expectation.fulfill()
}
}
XCTAssertNotNil(task)
waitForExpectations(timeout: 2) { (error) in
XCTAssertNil(error, "Error: \(error!.localizedDescription)")
XCTAssertEqual(task.state, .completed)
}
guard let route = response.routes?.first else {
XCTFail("No routes in response")
return
}
XCTAssertNotNil(route)
let leg = route.legs.first!
let step = leg.steps[1]
XCTAssertEqual(step.instructionsSpokenAlongStep!.count, 3)
let spokenInstructions = step.instructionsSpokenAlongStep!
XCTAssertEqual(spokenInstructions[0].distanceAlongStep, 1107.1)
XCTAssertEqual(spokenInstructions[0].ssmlText, "<speak><amazon:effect name=\"drc\"><prosody rate=\"1.08\">Continue on Baker Street for a half mile</prosody></amazon:effect></speak>")
XCTAssertEqual(spokenInstructions[0].text, "Continue on Baker Street for a half mile")
XCTAssertEqual(spokenInstructions[1].ssmlText, "<speak><amazon:effect name=\"drc\"><prosody rate=\"1.08\">In 900 feet, turn left onto Page Street</prosody></amazon:effect></speak>")
XCTAssertEqual(spokenInstructions[1].text, "In 900 feet, turn left onto Page Street")
XCTAssertEqual(spokenInstructions[2].ssmlText, "<speak><amazon:effect name=\"drc\"><prosody rate=\"1.08\">Turn left onto Page Street</prosody></amazon:effect></speak>")
XCTAssertEqual(spokenInstructions[2].text, "Turn left onto Page Street")
let arrivalStep = leg.steps[leg.steps.endIndex - 2]
XCTAssertEqual(arrivalStep.instructionsSpokenAlongStep!.count, 1)
let arrivalSpokenInstructions = arrivalStep.instructionsSpokenAlongStep!
XCTAssertEqual(arrivalSpokenInstructions[0].text, "You have arrived at the gym")
XCTAssertEqual(arrivalSpokenInstructions[0].ssmlText, "<speak><amazon:effect name=\"drc\"><prosody rate=\"1.08\">You have arrived at the gym</prosody></amazon:effect></speak>")
let visualInstructions = step.instructionsDisplayedAlongStep
XCTAssertNotNil(visualInstructions)
XCTAssertEqual(visualInstructions?.first?.primaryInstruction.text, "Page Street")
XCTAssertEqual(visualInstructions?.first?.distanceAlongStep, 1107.1)
XCTAssertEqual(visualInstructions?.first?.primaryInstruction.finalHeading, nil)
XCTAssertEqual(visualInstructions?.first?.primaryInstruction.maneuverType, .turn)
XCTAssertEqual(visualInstructions?.first?.primaryInstruction.maneuverDirection, .left)
if let firstComponent = visualInstructions?.first?.primaryInstruction.components.first,
case let VisualInstruction.Component.text(text) = firstComponent {
XCTAssertEqual(text.text, "Page Street")
XCTAssertEqual(text.abbreviation, "Page St")
XCTAssertEqual(text.abbreviationPriority, 0)
} else {
XCTFail("First primary component of visual instruction should be text component")
}
XCTAssertEqual(visualInstructions?.first?.drivingSide, .right)
XCTAssertNil(visualInstructions?.first?.secondaryInstruction)
let arrivalVisualInstructions = arrivalStep.instructionsDisplayedAlongStep!
XCTAssertEqual(arrivalVisualInstructions.first?.secondaryInstruction?.text, "the gym")
}
func testSubWithLaneInstructions() {
let expectation = self.expectation(description: "calculating directions with tertiary lane instructions should return results")
let queryParams: [String: String?] = [
"geometries": "polyline",
"steps": "true",
"access_token": BogusToken,
"banner_instructions": "true"
]
stub(condition: isHost("api.mapbox.com") && containsQueryParams(queryParams)) { _ in
let path = Bundle.module.path(forResource: "subLaneInstructions", ofType: "json")
return HTTPStubsResponse(fileAtPath: path!, statusCode: 200, headers: ["Content-Type": "application/json"])
}
let startWaypoint = Waypoint(coordinate: CLLocationCoordinate2D(latitude: 39.132063, longitude: -84.531074))
let endWaypoint = Waypoint(coordinate: CLLocationCoordinate2D(latitude: 39.138953, longitude: -84.532934))
let options = RouteOptions(waypoints: [startWaypoint, endWaypoint], profileIdentifier: .automobileAvoidingTraffic)
options.shapeFormat = .polyline
options.includesSteps = true
options.includesAlternativeRoutes = false
options.includesVisualInstructions = true
var response: RouteResponse!
let task = Directions(credentials: BogusCredentials).calculate(options) { (session, result) in
switch result {
case let .failure(error):
XCTFail("Error! \(error)")
case let .success(resp):
response = resp
expectation.fulfill()
}
}
XCTAssertNotNil(task)
waitForExpectations(timeout: 2) { (error) in
XCTAssertNil(error, "Error: \(error!.localizedDescription)")
XCTAssertEqual(task.state, .completed)
}
guard let route = response.routes?.first else {
XCTFail("No routes in response")
return
}
XCTAssertNotNil(route)
let step = route.legs.first!.steps.first!
let visualInstructions = step.instructionsDisplayedAlongStep
let tertiaryInstruction = visualInstructions?.first?.tertiaryInstruction
XCTAssertNotNil(tertiaryInstruction)
XCTAssertEqual(tertiaryInstruction?.text, "")
let laneIndicationComponents = tertiaryInstruction?.components.filter { (component) -> Bool in
if case VisualInstruction.Component.lane = component {
return true
}
return false
}
XCTAssertEqual(laneIndicationComponents?.count, 2)
if let laneIndicationComponents = laneIndicationComponents, laneIndicationComponents.count > 1 {
if case let VisualInstruction.Component.lane(indications, isUsable, preferredDirection) = laneIndicationComponents[0] {
XCTAssertEqual(indications, .straightAhead)
XCTAssertFalse(isUsable)
XCTAssertEqual(preferredDirection, nil)
}
if case let VisualInstruction.Component.lane(indications, isUsable, preferredDirection) = laneIndicationComponents[1] {
XCTAssertEqual(indications, .right)
XCTAssertTrue(isUsable)
XCTAssertEqual(preferredDirection, nil)
}
}
}
func testSubWithVisualInstructions() {
let expectation = self.expectation(description: "calculating directions with tertiary visual instructions should return results")
let queryParams: [String: String?] = [
"geometries": "polyline",
"steps": "true",
"access_token": BogusToken,
"banner_instructions": "true"
]
stub(condition: isHost("api.mapbox.com") && containsQueryParams(queryParams)) { _ in
let path = Bundle.module.path(forResource: "subVisualInstructions", ofType: "json")
return HTTPStubsResponse(fileAtPath: path!, statusCode: 200, headers: ["Content-Type": "application/json"])
}
let startWaypoint = Waypoint(coordinate: CLLocationCoordinate2D(latitude: 37.775469, longitude: -122.449158))
let endWaypoint = Waypoint(coordinate: CLLocationCoordinate2D(latitude: 37.347439837741376, longitude: -121.92883115196378))
let options = RouteOptions(waypoints: [startWaypoint, endWaypoint], profileIdentifier: .automobileAvoidingTraffic)
options.shapeFormat = .polyline
options.includesSteps = true
options.includesAlternativeRoutes = false
options.includesVisualInstructions = true
var response: RouteResponse!
let task = Directions(credentials: BogusCredentials).calculate(options) { (session, result) in
guard case let .success(resp) = result else {
XCTFail("Encountered unexpected error. \(result)")
return
}
response = resp
expectation.fulfill()
}
XCTAssertNotNil(task)
waitForExpectations(timeout: 2) { (error) in
XCTAssertNil(error, "Error: \(error!.localizedDescription)")
XCTAssertEqual(task.state, .completed)
}
guard let route = response.routes?.first else {
XCTFail("No routes in response")
return
}
XCTAssertNotNil(route)
let step = route.legs.first!.steps.first!
let visualInstructions = step.instructionsDisplayedAlongStep
let tertiaryInstruction = visualInstructions?.first?.tertiaryInstruction
XCTAssertNotNil(tertiaryInstruction)
XCTAssertEqual(tertiaryInstruction?.text, "Grove Street")
XCTAssertEqual(tertiaryInstruction?.maneuverType, .turn)
XCTAssertEqual(tertiaryInstruction?.maneuverDirection, .left)
let tertiaryInstructionComponent = tertiaryInstruction?.components.first { (component) -> Bool in
if case let VisualInstruction.Component.text(textRepresentation) = component {
XCTAssertEqual(textRepresentation.text, "Grove Street")
XCTAssertEqual(textRepresentation.abbreviation, "Grove St")
XCTAssertEqual(textRepresentation.abbreviationPriority, 0)
return true
}
return false
}
XCTAssertNotNil(tertiaryInstructionComponent)
}
}
#endif