Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Adds DBP pixel tests #1764

Merged
merged 11 commits into from
Oct 18, 2023
373 changes: 372 additions & 1 deletion DuckDuckGo.xcodeproj/project.pbxproj

Large diffs are not rendered by default.

Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,19 @@
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
shouldUseLaunchSchemeArgsEnv = "YES"
shouldAutocreateTestPlan = "YES">
<Testables>
<TestableReference
skipped = "NO"
parallelizable = "YES">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "7B96D0CE2ADFDA7E007E02C8"
BuildableName = "DuckDuckGoDBPTests.xctest"
BlueprintName = "DuckDuckGoDBPTests"
ReferencedContainer = "container:DuckDuckGo.xcodeproj">
</BuildableReference>
</TestableReference>
</Testables>
Comment on lines +31 to +43
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

New DBP unit tests target. I couldn't add the tests to the regular target since it doesn't include the DBP swift files.

</TestAction>
<LaunchAction
buildConfiguration = "Debug"
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
LastUpgradeVersion = "1500"
version = "1.7">
<BuildAction
parallelizeBuildables = "YES"
buildImplicitDependencies = "YES">
</BuildAction>
<TestAction
buildConfiguration = "Debug"
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
shouldUseLaunchSchemeArgsEnv = "YES"
shouldAutocreateTestPlan = "YES">
<Testables>
<TestableReference
skipped = "NO"
parallelizable = "YES">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "7B96D0CE2ADFDA7E007E02C8"
BuildableName = "DuckDuckGoDBPTests.xctest"
BlueprintName = "DuckDuckGoDBPTests"
ReferencedContainer = "container:DuckDuckGo.xcodeproj">
</BuildableReference>
</TestableReference>
</Testables>
</TestAction>
<LaunchAction
buildConfiguration = "Debug"
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
launchStyle = "0"
useCustomWorkingDirectory = "NO"
ignoresPersistentStateOnLaunch = "NO"
debugDocumentVersioning = "YES"
debugServiceExtension = "internal"
allowLocationSimulation = "YES">
</LaunchAction>
<ProfileAction
buildConfiguration = "Release"
shouldUseLaunchSchemeArgsEnv = "YES"
savedToolIdentifier = ""
useCustomWorkingDirectory = "NO"
debugDocumentVersioning = "YES">
</ProfileAction>
<AnalyzeAction
buildConfiguration = "Debug">
</AnalyzeAction>
<ArchiveAction
buildConfiguration = "Release"
revealArchiveInOrganizer = "YES">
</ArchiveAction>
</Scheme>
10 changes: 8 additions & 2 deletions DuckDuckGo/Statistics/Pixel.swift
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,13 @@ final class Pixel {
}
}

init(store: @escaping @autoclosure () -> PixelDataStore, requestSender: @escaping RequestSender) {
private let appVersion: String

init(appVersion: String = AppVersion.shared.versionNumber,
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Make the app version injectable for testing.

store: @escaping @autoclosure () -> PixelDataStore,
requestSender: @escaping RequestSender) {

self.appVersion = appVersion
self.store = store
self.sendRequest = requestSender
}
Expand Down Expand Up @@ -124,7 +130,7 @@ final class Pixel {
}

if includeAppVersionParameter {
newParams[PixelKit.Parameters.appVersion] = AppVersion.shared.versionNumber
newParams[PixelKit.Parameters.appVersion] = appVersion
}
#if DEBUG
newParams[PixelKit.Parameters.test] = PixelKit.Values.test
Expand Down
116 changes: 116 additions & 0 deletions DuckDuckGoDBPTests/DataBrokerProtectionPixelTests.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,116 @@
//
// DataBrokerProtectionPixelTests.swift
//
// Copyright © 2023 DuckDuckGo. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//

import Networking
import Foundation
import PixelKit
import PixelKitTestingUtilities
import XCTest
@testable import DuckDuckGo_DBP

/// Tests to ensure that DBP pixels sent from the main app work well
///
final class DataBrokerProtectionPixelTests: XCTestCase {
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is the test that I added for validating pixel behavior. There are no changes to the pixel logic right now, so this test is here to help me set a baseline for my upcoming changes.


struct PixelDataStoreMock: PixelDataStore {
func set(_ value: Int, forKey: String, completionHandler: ((Error?) -> Void)?) {
completionHandler?(nil)
}

Check failure on line 34 in DuckDuckGoDBPTests/DataBrokerProtectionPixelTests.swift

View workflow job for this annotation

GitHub Actions / SwiftLint

Lines should not have trailing whitespace (trailing_whitespace)
func set(_ value: String, forKey: String, completionHandler: ((Error?) -> Void)?) {
completionHandler?(nil)
}

Check failure on line 38 in DuckDuckGoDBPTests/DataBrokerProtectionPixelTests.swift

View workflow job for this annotation

GitHub Actions / SwiftLint

Lines should not have trailing whitespace (trailing_whitespace)
func set(_ value: Double, forKey: String, completionHandler: ((Error?) -> Void)?) {
completionHandler?(nil)
}

Check failure on line 42 in DuckDuckGoDBPTests/DataBrokerProtectionPixelTests.swift

View workflow job for this annotation

GitHub Actions / SwiftLint

Lines should not have trailing whitespace (trailing_whitespace)
func value(forKey key: String) -> Double? {
nil
}

Check failure on line 46 in DuckDuckGoDBPTests/DataBrokerProtectionPixelTests.swift

View workflow job for this annotation

GitHub Actions / SwiftLint

Lines should not have trailing whitespace (trailing_whitespace)
func value(forKey key: String) -> Int? {
nil
}

Check failure on line 50 in DuckDuckGoDBPTests/DataBrokerProtectionPixelTests.swift

View workflow job for this annotation

GitHub Actions / SwiftLint

Lines should not have trailing whitespace (trailing_whitespace)
func value(forKey key: String) -> String? {
nil
}

func removeValue(forKey key: String, completionHandler: ((Error?) -> Void)?) {
completionHandler?(nil)
}
}

/// This method implements basic validation logic that can be used to test several events.
///
func basicPixelValidation(for event: Pixel.Event) {
let inAppVersion = "1.0.1"
let inEvent: Pixel.Event = .optOutStart
let inUserAgent = "ddg_mac/\(inAppVersion) (com.duckduckgo.macos.browser.dbp.debug"

// We want to make sure the callback is executed exactly once to validate
// all of the fire parameters
let callbackExecuted = expectation(description: "We expect the callback to be executed once")
callbackExecuted.expectedFulfillmentCount = 1
callbackExecuted.assertForOverFulfill = true

// This is annoyingly necessary to test the user agent right now
APIRequest.Headers.setUserAgent(inUserAgent)

let storeMock = PixelDataStoreMock()

let pixel = Pixel(appVersion: inAppVersion, store: storeMock) { (event, parameters, _, headers, onComplete) in

// Validate that the event is the one we expect
XCTAssertEqual(event, inEvent)

PixelRequestValidator().validateBasicTestPixelRequest(inAppVersion: inAppVersion, inUserAgent: inUserAgent, requestParameters: parameters, requestHeaders: headers.httpHeaders)

callbackExecuted.fulfill()
onComplete(nil)
}

pixel.fire(inEvent, withAdditionalParameters: inEvent.parameters)

waitForExpectations(timeout: 0.1)
}

func testBasicPixelValidation() {
let eventsToTest: [Pixel.Event] = [
.parentChildMatches,
.optOutStart,
.optOutEmailGenerate,
.optOutCaptchaParse,
.optOutCaptchaSend,
.optOutCaptchaSolve,
.optOutSubmit,
.optOutEmailReceive,
.optOutEmailConfirm,
.optOutValidate,
.optOutFinish,
.optOutSubmitSuccess,
.optOutSuccess,
.optOutFailure
]

for event in eventsToTest {
basicPixelValidation(for: event)
}
}
}
8 changes: 7 additions & 1 deletion LocalPackages/PixelKit/Package.swift
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,10 @@ let package = Package(
// Products define the executables and libraries a package produces, and make them visible to other packages.
.library(
name: "PixelKit",
targets: ["PixelKit"])
targets: ["PixelKit"]),
.library(
name: "PixelKitTestingUtilities",
targets: ["PixelKitTestingUtilities"])
Comment on lines +17 to +19
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

New module for offering the standardized pixel validation logic.

],
dependencies: [
],
Expand All @@ -23,6 +26,9 @@ let package = Package(
dependencies: []),
.testTarget(
name: "PixelKitTests",
dependencies: ["PixelKit", "PixelKitTestingUtilities"]),
.target(
name: "PixelKitTestingUtilities",
dependencies: ["PixelKit"])
]
)
14 changes: 7 additions & 7 deletions LocalPackages/PixelKit/Sources/PixelKit/PixelKit.swift
Original file line number Diff line number Diff line change
Expand Up @@ -36,12 +36,12 @@ public final class PixelKit {
case dailyAndContinuous
}

enum Header {
static let acceptEncoding = "Accept-Encoding"
static let acceptLanguage = "Accept-Language"
static let userAgent = "User-Agent"
static let ifNoneMatch = "If-None-Match"
static let moreInfo = "X-DuckDuckGo-MoreInfo"
public enum Header {
public static let acceptEncoding = "Accept-Encoding"
public static let acceptLanguage = "Accept-Language"
public static let userAgent = "User-Agent"
public static let ifNoneMatch = "If-None-Match"
public static let moreInfo = "X-DuckDuckGo-MoreInfo"
}

/// A closure typealias to request sending pixels through the network.
Expand All @@ -56,7 +56,7 @@ public final class PixelKit {

public typealias Event = PixelKitEvent

static let duckDuckGoMorePrivacyInfo = URL(string: "https://help.duckduckgo.com/duckduckgo-help-pages/privacy/atb/")!
public static let duckDuckGoMorePrivacyInfo = URL(string: "https://help.duckduckgo.com/duckduckgo-help-pages/privacy/atb/")!
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Just make sure this value can be accessed for testing purposes.


private let defaults: UserDefaults

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
//
// ValidatePixel.swift
//
// Copyright © 2023 DuckDuckGo. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//

import Foundation
import PixelKit
import XCTest

public final class PixelRequestValidator {
public init() {}

public func validateBasicTestPixelRequest(
inAppVersion: String,
inUserAgent: String,
requestParameters parameters: [String: String],
requestHeaders headers: [String: String]) {

XCTAssertEqual(parameters.count, 2)
XCTAssertEqual(parameters[PixelKit.Parameters.test], "1")
XCTAssertEqual(parameters[PixelKit.Parameters.appVersion], inAppVersion)

XCTAssertEqual(headers[PixelKit.Header.userAgent], inUserAgent)
XCTAssertEqual(headers[PixelKit.Header.acceptEncoding], "gzip;q=1.0, compress;q=0.5")
XCTAssertNotNil(headers[PixelKit.Header.acceptLanguage])
XCTAssertNotNil(headers[PixelKit.Header.moreInfo], PixelKit.duckDuckGoMorePrivacyInfo.absoluteString)
}
}