Skip to content

Commit

Permalink
feat(Core): bootstrap Auth configuration before other categories, and…
Browse files Browse the repository at this point in the history
… fixed analytics integration tests (#475)

* Start to debug integration test

* configure Auth before all others

* bug not fixed yet, need to verify other stuff

* fix Integration test target - add Host application

* fix README.md description and step 4

* deleted amplifyconfiguration.json fix README.md step 4, and add to ignore configuration file in gitignore

* commit

* Fixed a typo, set up array of categories to be initialised in Categories.swift

* set up array of categoried to be initialized

* move var category under var display

* fix a typo

Co-authored-by: Michael law <1365977+lawmicha@users.noreply.github.com>
  • Loading branch information
ruiguoamz and lawmicha committed May 22, 2020
1 parent c3ae896 commit c33bf1b
Show file tree
Hide file tree
Showing 11 changed files with 332 additions and 309 deletions.
2 changes: 2 additions & 0 deletions .gitignore
Expand Up @@ -45,5 +45,7 @@ Scripts/ocunit2junit
__pycache__/
*awsconfiguration.json
*amplifyconfiguration.json
awsconfiguration.json
amplifyconfiguration.json
credentials-mc.json

21 changes: 21 additions & 0 deletions Amplify/Core/Category/CategoryType.swift
Expand Up @@ -61,4 +61,25 @@ public extension CategoryType {
return "Storage"
}
}

var category: Category {
switch self {
case .analytics:
return Amplify.Analytics
case .api:
return Amplify.API
case .auth:
return Amplify.Auth
case .dataStore:
return Amplify.DataStore
case .hub:
return Amplify.Hub
case .logging:
return Amplify.Logging
case .predictions:
return Amplify.Predictions
case .storage:
return Amplify.Storage
}
}
}
15 changes: 8 additions & 7 deletions Amplify/Core/Configuration/AmplifyConfiguration.swift
Expand Up @@ -97,27 +97,28 @@ extension Amplify {

let configuration = try Amplify.resolve(configuration: configuration)

// Always configure Logging and Hub first, so they are available to other categoories.
try configure(Logging, using: configuration)
try configure(Hub, using: configuration)
// Always configure Logging, Hub and Auth first, so they are available to other categories.
// Auth is a special case for other plugins which depend on using Auth when being configured themselves.
let manuallyConfiguredCategories = [CategoryType.logging, .hub, .auth]
for categoryType in manuallyConfiguredCategories {
try configure(categoryType.category, using: configuration)
}

// Looping through all categories to ensure we don't accidentally forget a category at some point in the future
let remainingCategories = CategoryType.allCases.filter { $0 != .hub && $0 != .logging }
let remainingCategories = CategoryType.allCases.filter { !manuallyConfiguredCategories.contains($0) }
for categoryType in remainingCategories {
switch categoryType {
case .analytics:
try configure(Analytics, using: configuration)
case .api:
try configure(API, using: configuration)
case .auth:
try configure(Auth, using: configuration)
case .dataStore:
try configure(DataStore, using: configuration)
case .predictions:
try configure(Predictions, using: configuration)
case .storage:
try configure(Storage, using: configuration)
case .hub, .logging:
case .hub, .logging, .auth:
// Already configured
break
}
Expand Down
Expand Up @@ -5,135 +5,33 @@
// SPDX-License-Identifier: Apache-2.0
//

@testable import Amplify
import AWSMobileClient
import XCTest
import AmplifyPlugins
import AWSPinpoint

@testable import Amplify
@testable import AWSPinpointAnalyticsPlugin
import XCTest
@testable import AmplifyTestCommon

// swiftlint:disable:next type_name
class AWSPinpointAnalyticsPluginIntergrationTests: XCTestCase {
/*
Set up
`amplify init`
`amplify add analytics`
* Apps need authorization to send analytics events. Do you want to allow guests and unauthenticated users to send
analytics events? (we recommend you allow this when getting started) `Yes`
`amplify push`
Pinpoint URL to track events
https://us-west-2.console.aws.amazon.com/pinpoint/home/?region=us-west-2#/apps/xxx/analytics/overview

awsconfiguration.json
{
"UserAgent": "aws-amplify/cli",
"Version": "0.1.0",
"IdentityManager": {
"Default": {}
},
"CredentialsProvider": {
"CognitoIdentity": {
"Default": {
"PoolId": "us-west-2:xxx",
"Region": "us-west-2"
}
}
},
"PinpointAnalytics": {
"Default": {
"AppId": "xxx",
"Region": "us-west-2"
}
},
"PinpointTargeting": {
"Default": {
"Region": "us-west-2"
}
}
}
amplifyconfiguration.json
{
"UserAgent": "aws-amplify-cli/2.0",
"Version": "1.0",
"analytics": {
"plugins": {
"awsPinpointAnalyticsPlugin": {
"pinpointAnalytics": {
"appId": "xxxx",
"region": "us-west-2"
},
"pinpointTargeting": {
"region": "us-west-2"
}
}
}
}
}
*/
let analyticsPluginKey = "awsPinpointAnalyticsPlugin"
static let amplifyConfiguration = "AWSPinpointAnalyticsPluginIntegrationTests-amplifyconfiguration"
static let analyticsPluginKey = "awsPinpointAnalyticsPlugin"

override func setUp() {
let config = [
"CredentialsProvider": [
"CognitoIdentity": [
"Default": [
"PoolId": "us-west-2:xxx",
"Region": "us-west-2"
]
]
]
]
AWSInfo.configureDefaultAWSInfo(config)

let mobileClientIsInitialized = expectation(description: "AWSMobileClient is initialized")
AWSMobileClient.default().initialize { userState, error in
guard error == nil else {
XCTFail("Error initializing AWSMobileClient. Error: \(error!.localizedDescription)")
return
}
guard let userState = userState else {
XCTFail("userState is unexpectedly empty initializing AWSMobileClient")
return
}
if userState != UserState.signedOut {
AWSMobileClient.default().signOut()
}
mobileClientIsInitialized.fulfill()
}
wait(for: [mobileClientIsInitialized], timeout: 100)
print("AWSMobileClient Initialized")

let analyticsConfig = AnalyticsCategoryConfiguration(
plugins: [
"awsPinpointAnalyticsPlugin": [
"pinpointAnalytics": [
"appId": "xxxxx",
"region": "us-west-2"
],
"pinpointTargeting": [
"region": "us-west-2"
],
"autoFlushEventsInterval": 10,
"trackAppSessions": true,
"autoSessionTrackingInterval": 2
]
])

let amplifyConfig = AmplifyConfiguration(analytics: analyticsConfig)

do {
let config = try TestConfigHelper.retrieveAmplifyConfiguration(
forResource: AWSPinpointAnalyticsPluginIntergrationTests.amplifyConfiguration)
try Amplify.add(plugin: AWSAuthPlugin())
try Amplify.add(plugin: AWSPinpointAnalyticsPlugin())
try Amplify.configure(amplifyConfig)
try Amplify.configure(config)
} catch {
XCTFail("Failed to initialize and configure Amplify")
XCTFail("Failed to initialize and configure Amplify \(error)")
}

print("Amplify initialized")
}

override func tearDown() {
print("Amplify reset")
Amplify.reset()
}

Expand Down Expand Up @@ -171,7 +69,7 @@ class AWSPinpointAnalyticsPluginIntergrationTests: XCTestCase {
properties: properties)
Amplify.Analytics.identifyUser(userId, withProfile: userProfile)

wait(for: [identifyUserEvent], timeout: 20)
wait(for: [identifyUserEvent], timeout: TestCommonConstants.networkTimeout)
}

func testRecordEventsAreFlushed() {
Expand Down Expand Up @@ -199,12 +97,14 @@ class AWSPinpointAnalyticsPluginIntergrationTests: XCTestCase {
"eventPropertyBoolKey": true] as [String: AnalyticsPropertyValue]
let event = BasicAnalyticsEvent(name: "eventName", properties: properties)
Amplify.Analytics.record(event: event)
Amplify.Analytics.flushEvents()

wait(for: [flushEventsInvoked], timeout: 20)
wait(for: [flushEventsInvoked], timeout: TestCommonConstants.networkTimeout)
}

func testGetEscapeHatch() throws {
let plugin = try Amplify.Analytics.getPlugin(for: analyticsPluginKey)
let plugin = try Amplify.Analytics.getPlugin(
for: AWSPinpointAnalyticsPluginIntergrationTests.analyticsPluginKey)
guard let pinpointAnalyticsPlugin = plugin as? AWSPinpointAnalyticsPlugin else {
XCTFail("Could not get plugin of type AWSPinpointAnalyticsPlugin")
return
Expand Down
Expand Up @@ -13,7 +13,7 @@
<key>CFBundleName</key>
<string>$(PRODUCT_NAME)</string>
<key>CFBundlePackageType</key>
<string>BNDL</string>
<string>$(PRODUCT_BUNDLE_PACKAGE_TYPE)</string>
<key>CFBundleShortVersionString</key>
<string>1.0</string>
<key>CFBundleVersion</key>
Expand Down
@@ -0,0 +1,25 @@
## Analytics Integration Tests

The following steps demonstrate how to set up Analytics. Auth category is also required for signing with AWS Pinpoint service and requesting with IAM credentials to allow unauthenticated and authenticated access.

### Set-up

1. `amplify init`

2. `amplify add analytics`

```perl
? Select an Analytics provider: Amazon Pinpoint`
? Provide your pinpoint resource name `yourPinpointResourceName`
? Apps need autorization to send analytics events. Do you want to allow guests and unauthenticated users to send analytics events? (we recommend you allow this when getting started) `Yes`
```

3. `amplify push`

[temporary step]: Until Amplify CLI supports adding the auth section into amplifyconfiguation.json, copy `awsconfiguration.json`'s auth section over
4. Copy `amplifyconfiguration.json` over to folder `AWSPinpointAnalyticPluginIntegrationTests` as `AWSPinpointAnalyticsPluginIntegrationTests-amplifyconfiguration.json`
5. You can now run all of the integration tests.
6. You can run `amplify console analytics` to check what happens at the backend.

0 comments on commit c33bf1b

Please sign in to comment.