Skip to content

Commit

Permalink
add unit tests
Browse files Browse the repository at this point in the history
  • Loading branch information
lawmicha committed Apr 24, 2024
1 parent e63f090 commit a8c9f5c
Show file tree
Hide file tree
Showing 5 changed files with 76 additions and 16 deletions.
5 changes: 3 additions & 2 deletions Amplify/Categories/API/Request/GraphQLRequest.swift
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,9 @@
// SPDX-License-Identifier: Apache-2.0
//

/// Empty protocol for plugins to define specific `AuthorizationMode` types for the request.
public protocol AuthorizationMode { }

/// GraphQL Request
public struct GraphQLRequest<R: Decodable> {

Expand Down Expand Up @@ -49,8 +52,6 @@ public struct GraphQLRequest<R: Decodable> {
}
}

public protocol AuthorizationMode { }

// MARK: GraphQLRequest + Options

public extension GraphQLRequest {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ final public class AWSGraphQLOperation<R: Decodable>: GraphQLOperation<R> {
}

let urlRequest = validateRequest(request).flatMap(buildURLRequest(from:))
let finalRequest = await getEndpointInterceptors(from: request).flatMapAsync { requestInterceptors in
let finalRequest = await getEndpointInterceptors().flatMapAsync { requestInterceptors in
let preludeInterceptors = requestInterceptors?.preludeInterceptors ?? []
let customerInterceptors = requestInterceptors?.interceptors ?? []
let postludeInterceptors = requestInterceptors?.postludeInterceptors ?? []
Expand Down Expand Up @@ -150,7 +150,7 @@ final public class AWSGraphQLOperation<R: Decodable>: GraphQLOperation<R> {
}
}

private func getEndpointInterceptors(from request: GraphQLOperationRequest<R>) -> Result<AWSAPIEndpointInterceptors?, APIError> {
func getEndpointInterceptors() -> Result<AWSAPIEndpointInterceptors?, APIError> {
getEndpointConfig(from: request).flatMap { endpointConfig in
do {
if let pluginOptions = request.options.pluginOptions as? AWSAPIPluginDataStoreOptions,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import XCTest
@testable import Amplify
@testable import AmplifyTestCommon
@testable import AWSAPIPlugin
@testable import AWSPluginsTestCommon

class AWSGraphQLOperationTests: AWSAPICategoryPluginTestBase {

Expand Down Expand Up @@ -37,4 +38,44 @@ class AWSGraphQLOperationTests: AWSAPICategoryPluginTestBase {
XCTAssertNil(task)
}


/// Request for `.amazonCognitoUserPool` at runtime with `request` while passing in what
/// is configured as `.apiKey`. Expect that the interceptor is the token interceptor
func testGetEndpointInterceptors() throws {
let request = GraphQLRequest<JSONValue>.appSync(apiName: apiName,
document: testDocument,
variables: nil,
responseType: JSONValue.self,
authorizationMode: .amazonCognitoUserPools)
let task = try OperationTestBase.makeSingleValueErrorMockTask()
let mockSession = MockURLSession(onTaskForRequest: { _ in task })
let pluginConfig = AWSAPICategoryPluginConfiguration(
endpoints: [
apiName: try .init(
name: apiName,
baseURL: URL(string: "url")!,
region: "us-test-1",
authorizationType: .apiKey,
endpointType: .graphQL,
apiKey: "apiKey",
apiAuthProviderFactory: .init())],
apiAuthProviderFactory: .init(),
authService: MockAWSAuthService())
let operation = AWSGraphQLOperation(request: request.toOperationRequest(operationType: .query),
session: mockSession,
mapper: OperationTaskMapper(),
pluginConfig: pluginConfig,
resultListener: { _ in })

// Act
let results = operation.getEndpointInterceptors()

// Assert
guard case let .success(interceptors) = results,
let interceptor = interceptors?.preludeInterceptors.first,
(interceptor as? AuthTokenURLRequestInterceptor) != nil else {
XCTFail("Should be token interceptor for Cognito User Pool")
return
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ class OperationTestBase: XCTestCase {
}

func setUpPluginForSingleError(for endpointType: AWSAPICategoryPluginEndpointType) throws {
let task = try makeSingleValueErrorMockTask()
let task = try Self.makeSingleValueErrorMockTask()
let mockSession = MockURLSession(onTaskForRequest: { _ in task })
let sessionFactory = MockSessionFactory(returning: mockSession)
try setUpPlugin(sessionFactory: sessionFactory, endpointType: endpointType)
Expand Down Expand Up @@ -102,7 +102,7 @@ class OperationTestBase: XCTestCase {
return task
}

func makeSingleValueErrorMockTask() throws -> MockURLSessionTask {
static func makeSingleValueErrorMockTask() throws -> MockURLSessionTask {
var mockTask: MockURLSessionTask!
mockTask = MockURLSessionTask(onResume: {
guard let mockSession = mockTask.mockSession,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,11 +29,12 @@ class GraphQLRequestModelTest: XCTestCase {
documentBuilder.add(decorator: ModelDecorator(model: post, mutationType: .create))
let document = documentBuilder.build()

let request = GraphQLRequest<Post>.create(post)
let request = GraphQLRequest<Post>.create(post, authMode: .amazonCognitoUserPools)

XCTAssertEqual(document.stringValue, request.document)
XCTAssert(request.responseType == Post.self)
XCTAssert(request.variables != nil)
assertEquals(actualAuthMode: request.authorizationMode, expectedAuthMode: .amazonCognitoUserPools)
}

func testUpdateMutationGraphQLRequest() {
Expand All @@ -43,11 +44,12 @@ class GraphQLRequestModelTest: XCTestCase {
documentBuilder.add(decorator: ModelDecorator(model: post, mutationType: .update))
let document = documentBuilder.build()

let request = GraphQLRequest<Post>.update(post)
let request = GraphQLRequest<Post>.update(post, authMode: .amazonCognitoUserPools)

XCTAssertEqual(document.stringValue, request.document)
XCTAssert(request.responseType == Post.self)
XCTAssert(request.variables != nil)
assertEquals(actualAuthMode: request.authorizationMode, expectedAuthMode: .amazonCognitoUserPools)
}

func testDeleteMutationGraphQLRequest() {
Expand All @@ -57,11 +59,12 @@ class GraphQLRequestModelTest: XCTestCase {
documentBuilder.add(decorator: ModelDecorator(model: post, mutationType: .delete))
let document = documentBuilder.build()

let request = GraphQLRequest<Post>.delete(post)
let request = GraphQLRequest<Post>.delete(post, authMode: .amazonCognitoUserPools)

XCTAssertEqual(document.stringValue, request.document)
XCTAssert(request.responseType == Post.self)
XCTAssert(request.variables != nil)
assertEquals(actualAuthMode: request.authorizationMode, expectedAuthMode: .amazonCognitoUserPools)
}

func testQueryByIdGraphQLRequest() {
Expand All @@ -70,11 +73,12 @@ class GraphQLRequestModelTest: XCTestCase {
documentBuilder.add(decorator: ModelIdDecorator(id: "id"))
let document = documentBuilder.build()

let request = GraphQLRequest<Post>.get(Post.self, byId: "id")
let request = GraphQLRequest<Post>.get(Post.self, byId: "id", authMode: .amazonCognitoUserPools)

XCTAssertEqual(document.stringValue, request.document)
XCTAssert(request.responseType == Post?.self)
XCTAssert(request.variables != nil)
assertEquals(actualAuthMode: request.authorizationMode, expectedAuthMode: .amazonCognitoUserPools)
}

func testListQueryGraphQLRequest() {
Expand All @@ -87,11 +91,12 @@ class GraphQLRequestModelTest: XCTestCase {
documentBuilder.add(decorator: PaginationDecorator())
let document = documentBuilder.build()

let request = GraphQLRequest<Post>.list(Post.self, where: predicate)
let request = GraphQLRequest<Post>.list(Post.self, where: predicate, authMode: .amazonCognitoUserPools)

XCTAssertEqual(document.stringValue, request.document)
XCTAssert(request.responseType == List<Post>.self)
XCTAssertNotNil(request.variables)
assertEquals(actualAuthMode: request.authorizationMode, expectedAuthMode: .amazonCognitoUserPools)
}

func testPaginatedListQueryGraphQLRequest() {
Expand All @@ -104,44 +109,57 @@ class GraphQLRequestModelTest: XCTestCase {
documentBuilder.add(decorator: PaginationDecorator(limit: 10))
let document = documentBuilder.build()

let request = GraphQLRequest<Post>.list(Post.self, where: predicate, limit: 10)
let request = GraphQLRequest<Post>.list(Post.self, where: predicate, limit: 10, authMode: .amazonCognitoUserPools)

XCTAssertEqual(document.stringValue, request.document)
XCTAssert(request.responseType == List<Post>.self)
XCTAssertNotNil(request.variables)
assertEquals(actualAuthMode: request.authorizationMode, expectedAuthMode: .amazonCognitoUserPools)
}

func testOnCreateSubscriptionGraphQLRequest() {
var documentBuilder = ModelBasedGraphQLDocumentBuilder(modelSchema: Post.schema, operationType: .subscription)
documentBuilder.add(decorator: DirectiveNameDecorator(type: .onCreate))
let document = documentBuilder.build()

let request = GraphQLRequest<Post>.subscription(of: Post.self, type: .onCreate)
let request = GraphQLRequest<Post>.subscription(of: Post.self, type: .onCreate, authMode: .amazonCognitoUserPools)

XCTAssertEqual(document.stringValue, request.document)
XCTAssert(request.responseType == Post.self)

assertEquals(actualAuthMode: request.authorizationMode, expectedAuthMode: .amazonCognitoUserPools)
}

func testOnUpdateSubscriptionGraphQLRequest() {
var documentBuilder = ModelBasedGraphQLDocumentBuilder(modelSchema: Post.schema, operationType: .subscription)
documentBuilder.add(decorator: DirectiveNameDecorator(type: .onUpdate))
let document = documentBuilder.build()

let request = GraphQLRequest<Post>.subscription(of: Post.self, type: .onUpdate)
let request = GraphQLRequest<Post>.subscription(of: Post.self, type: .onUpdate, authMode: .amazonCognitoUserPools)

XCTAssertEqual(document.stringValue, request.document)
XCTAssert(request.responseType == Post.self)
assertEquals(actualAuthMode: request.authorizationMode, expectedAuthMode: .amazonCognitoUserPools)
}

func testOnDeleteSubscriptionGraphQLRequest() {
var documentBuilder = ModelBasedGraphQLDocumentBuilder(modelSchema: Post.schema, operationType: .subscription)
documentBuilder.add(decorator: DirectiveNameDecorator(type: .onDelete))
let document = documentBuilder.build()

let request = GraphQLRequest<Post>.subscription(of: Post.self, type: .onDelete)
let request = GraphQLRequest<Post>.subscription(of: Post.self, type: .onDelete, authMode: .amazonCognitoUserPools)

XCTAssertEqual(document.stringValue, request.document)
XCTAssert(request.responseType == Post.self)
assertEquals(actualAuthMode: request.authorizationMode, expectedAuthMode: .amazonCognitoUserPools)
}

// MARK: - Helpers

func assertEquals(actualAuthMode: AuthorizationMode?, expectedAuthMode: AWSAuthorizationType) {
guard let authMode = actualAuthMode as? AWSAuthorizationType else {
XCTFail("Missing authorizationMode on request")
return
}
XCTAssertEqual(authMode, expectedAuthMode)
}
}

0 comments on commit a8c9f5c

Please sign in to comment.