-
Notifications
You must be signed in to change notification settings - Fork 192
/
GraphQLWithIAMIntegrationTests.swift
263 lines (225 loc) · 8.65 KB
/
GraphQLWithIAMIntegrationTests.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
//
// Copyright Amazon.com Inc. or its affiliates.
// All Rights Reserved.
//
// SPDX-License-Identifier: Apache-2.0
//
import XCTest
import AWSAPIPlugin
import AWSCognitoAuthPlugin
@testable import Amplify
@testable import APIHostApp
class GraphQLWithIAMIntegrationTests: XCTestCase {
let amplifyConfigurationFile = "testconfiguration/GraphQLWithIAMIntegrationTests-amplifyconfiguration"
let username = "integTest\(UUID().uuidString)"
let password = "P123@\(UUID().uuidString)"
override func setUp() async throws {
do {
Amplify.Logging.logLevel = .verbose
try Amplify.add(plugin: AWSAPIPlugin())
try Amplify.add(plugin: AWSCognitoAuthPlugin())
let amplifyConfig = try TestConfigHelper.retrieveAmplifyConfiguration(forResource: amplifyConfigurationFile)
try Amplify.configure(amplifyConfig)
ModelRegistry.register(modelType: Todo.self)
} catch {
XCTFail("Error during setup: \(error)")
}
}
override func tearDown() async throws {
if try await isSignedIn() {
await signOut()
}
await Amplify.reset()
}
func testSignUserOut() async throws {
if try await isSignedIn() {
print("User is signed in")
}
await signOut()
}
/// Test create mutation with a custom GraphQL Document
///
/// - Given: A custom GraphQL document containing CreateTodo mutation request, and user is signed in.
/// - When:
/// - Call mutate API
/// - Then:
/// - The operation completes successfully with no errors and todo in response
///
func testCreateTodoAuthRole() async throws {
try await createAuthenticatedUser()
try await createTodoTest()
}
/// An unauthenticated user should not fail
///
/// - Given: A CreateTodo mutation request, and user is not signed in.
/// - When:
/// - Call mutate API
/// - Then:
/// - The operation completes successfully with no errors and todo in response
///
func testCreateTodoUnauthRole() async throws {
if try await isSignedIn() {
await signOut()
}
try await createTodoTest()
}
func createTodoTest() async throws {
let expectedId = UUID().uuidString
let expectedName = "testCreateTodoMutationName"
let expectedDescription = "testCreateTodoMutationDescription"
let request = GraphQLRequest(document: CreateTodoMutation.document,
variables: CreateTodoMutation.variables(id: expectedId,
name: expectedName,
description: expectedDescription),
responseType: CreateTodoMutation.Data.self)
let event = try await Amplify.API.mutate(request: request)
switch event {
case .success(let data):
guard let todo = data.createTodo else {
XCTFail("Missing Todo")
return
}
XCTAssertEqual(todo.id, expectedId)
XCTAssertEqual(todo.name, expectedName)
XCTAssertEqual(todo.description, expectedDescription)
XCTAssertEqual(todo.typename, String(describing: Todo.self))
case .failure(let error):
XCTFail("Unexpected .failed event: \(error)")
}
}
/// A subscription to onCreate todo should receive an event for each create Todo mutation API called. User is not signed in
///
/// - Given: An onCreate Todo subscription established
/// - When:
/// - Create todo mutations API called
/// - Then:
/// - The subscription should receive mutation events corresponding to the API calls performed.
///
func testOnCreateTodoUnauthRole() async throws {
if try await isSignedIn() {
await signOut()
}
try await onCreateTodoTest()
}
/// A subscription to onCreate todo should receive an event for each create Todo mutation API called
///
/// - Given: An onCreate Todo subscription established
/// - When:
/// - Create todo mutations API called
/// - Then:
/// - The subscription should receive mutation events corresponding to the API calls performed.
///
func testOnCreateTodoAuthRole() async throws {
try await createAuthenticatedUser()
try await onCreateTodoTest()
}
func onCreateTodoTest() async throws {
let connectedInvoked = expectation(description: "Connection established")
let progressInvoked = expectation(description: "progress invoked")
progressInvoked.expectedFulfillmentCount = 2
let disconnectedInvoked = expectation(description: "Connection disconnected")
let subscription = Amplify.API.subscribe(request: .subscription(of: Todo.self, type: .onCreate))
let uuid = UUID().uuidString
let uuid2 = UUID().uuidString
let name = String("\(#function)".dropLast(2))
Task {
for try await event in subscription {
switch event {
case .connection(let state):
switch state {
case .connecting:
break
case .connected:
connectedInvoked.fulfill()
case .disconnected:
disconnectedInvoked.fulfill()
}
case .data(let result):
switch result {
case .success(let todo):
if todo.id == uuid || todo.id == uuid2 {
progressInvoked.fulfill()
}
case .failure(let error):
XCTFail("\(error)")
}
}
}
}
await fulfillment(of: [connectedInvoked], timeout: TestCommonConstants.networkTimeout)
_ = try await createTodo(id: uuid, name: name)
_ = try await createTodo(id: uuid2, name: name)
await fulfillment(of: [progressInvoked], timeout: TestCommonConstants.networkTimeout)
subscription.cancel()
await fulfillment(of: [disconnectedInvoked], timeout: TestCommonConstants.networkTimeout)
}
// MARK: - Helpers
func createTodo(id: String, name: String) async throws -> Todo {
let todo = Todo(id: id, name: name)
let event = try await Amplify.API.mutate(request: .create(todo))
switch event {
case .success(let data):
return data
case .failure(let error):
throw error
}
}
// MARK: - Auth Helpers
func createAuthenticatedUser() async throws {
if try await isSignedIn() {
await signOut()
}
try await signUp()
try await signIn()
}
func isSignedIn() async throws -> Bool {
let authSession = try await Amplify.Auth.fetchAuthSession()
return authSession.isSignedIn
}
func signUp() async throws {
let signUpResult = try await Amplify.Auth.signUp(username: username, password: password)
guard signUpResult.isSignUpComplete else {
XCTFail("Sign up successful but not complete: \(signUpResult)")
return
}
}
func signIn() async throws {
let signInResult = try await Amplify.Auth.signIn(username: username, password: password)
guard signInResult.isSignedIn else {
XCTFail("Sign in successful but not complete")
return
}
}
func signOut() async {
_ = await Amplify.Auth.signOut()
}
// MARK: - Model
struct Todo: Model {
public let id: String
public var name: String
public var description: String?
init(id: String = UUID().uuidString,
name: String,
description: String? = nil) {
self.id = id
self.name = name
self.description = description
}
enum CodingKeys: String, ModelKey {
case id
case name
case description
}
static let keys = CodingKeys.self
static let schema = defineSchema { model in
let todo = Todo.keys
model.listPluralName = "Todos"
model.syncPluralName = "Todos"
model.fields(
.id(),
.field(todo.name, is: .required, ofType: .string),
.field(todo.description, is: .optional, ofType: .string)
)
}
}
}