diff --git a/.travis.yml b/.travis.yml index d13a67fdd..e2749c9be 100644 --- a/.travis.yml +++ b/.travis.yml @@ -3,5 +3,6 @@ osx_image: xcode8 before_script: "./scripts/add-keys.sh" after_script: "./scripts/remove-key.sh" script: +- "./scripts/swiftLint.sh" - "./scripts/buildPrebidMobile.sh" -- "./scripts/testPrebidMobile.sh" \ No newline at end of file +- "./scripts/testPrebidMobile.sh" diff --git a/example/Swift/PrebidDemo/Podfile.lock b/example/Swift/PrebidDemo/Podfile.lock index a46bf66e3..cb12f50b7 100644 --- a/example/Swift/PrebidDemo/Podfile.lock +++ b/example/Swift/PrebidDemo/Podfile.lock @@ -25,6 +25,6 @@ SPEC CHECKSUMS: Google-Mobile-Ads-SDK: 101ce89b94fdf60ec64ba7b6e9b9d812dc765936 mopub-ios-sdk: 937b82dd76d8a396ba6a22ae005a1e24c61bf28b -PODFILE CHECKSUM: f360a1c025d20f1c83df3465389ff18c30132917 +PODFILE CHECKSUM: 25c67724e27e16324b9ebf8ddc671c30272b0cf7 COCOAPODS: 1.5.2 diff --git a/example/Swift/PrebidDemo/PrebidDemo/AppDelegate.swift b/example/Swift/PrebidDemo/PrebidDemo/AppDelegate.swift index 3b0073aa0..98f0a6a0a 100644 --- a/example/Swift/PrebidDemo/PrebidDemo/AppDelegate.swift +++ b/example/Swift/PrebidDemo/PrebidDemo/AppDelegate.swift @@ -1,11 +1,11 @@ /* Copyright 2018-2019 Prebid.org, Inc. - + 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. @@ -18,34 +18,32 @@ import PrebidMobile import CoreLocation @UIApplicationMain -class AppDelegate: UIResponder, UIApplicationDelegate { +class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? - var coreLocation:CLLocationManager? + var coreLocation: CLLocationManager? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. - + //Declare in AppDelegate to the user agent could be passed in first call Prebid.shared.prebidServerAccountId = "bfa84af2-bd16-4d35-96ad-31c6bb888df0" Prebid.shared.shareGeoLocation = true //Prebid.shared.timeoutMillis = 1000; //Prebid.shared.prebidServerHost = PrebidHost.Rubicon //Prebid.shared.prebidServerAccountId = "12345" - + coreLocation = CLLocationManager() coreLocation?.requestWhenInUseAuthorization() - + return true } func applicationWillResignActive(_ application: UIApplication) { - // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { - // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } @@ -61,6 +59,4 @@ class AppDelegate: UIResponder, UIApplicationDelegate { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } - } - diff --git a/example/Swift/PrebidDemo/PrebidDemo/BannerController.swift b/example/Swift/PrebidDemo/PrebidDemo/BannerController.swift index 54f5838c6..33040e9d8 100644 --- a/example/Swift/PrebidDemo/PrebidDemo/BannerController.swift +++ b/example/Swift/PrebidDemo/PrebidDemo/BannerController.swift @@ -1,11 +1,11 @@ /* Copyright 2018-2019 Prebid.org, Inc. - + 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. @@ -22,47 +22,47 @@ import GoogleMobileAds import MoPub class BannerController: UIViewController, GADBannerViewDelegate, MPAdViewDelegate { - + @IBOutlet var appBannerView: UIView! - + @IBOutlet var adServerLabel: UILabel! - - var adServerName:String = "" - + + var adServerName: String = "" + let request = DFPRequest() - + var dfpBanner: DFPBannerView! - + var bannerUnit: BannerAdUnit! - + var mopubBanner: MPAdView? - + override func viewDidLoad() { super.viewDidLoad() - + adServerLabel.text = adServerName - + bannerUnit = BannerAdUnit(configId: "6ace8c7d-88c0-4623-8117-75bc3f0a2e45", size: CGSize(width: 300, height: 250)) bannerUnit.setAutoRefreshMillis(time: 35000) //bannerUnit.addAdditionalSize(sizes: [CGSize(width: 300, height: 600)]) - - if(adServerName == "DFP"){ + + if (adServerName == "DFP") { print("entered \(adServerName) loop" ) loadDFPBanner(bannerUnit: bannerUnit) - - } else if (adServerName == "MoPub"){ + + } else if (adServerName == "MoPub") { print("entered \(adServerName) loop" ) loadMoPubBanner(bannerUnit: bannerUnit) - + } } - + override func viewDidDisappear(_ animated: Bool) { // important to remove the time instance bannerUnit?.stopAutoRefresh() } - - func loadDFPBanner(bannerUnit : AdUnit){ + + func loadDFPBanner(bannerUnit: AdUnit) { print("Google Mobile Ads SDK version: \(DFPRequest.sdkVersion())") dfpBanner = DFPBannerView(adSize: kGADAdSizeMediumRectangle) dfpBanner.adUnitID = "/19968336/PrebidMobileValidator_Banner_All_Sizes" @@ -70,67 +70,62 @@ class BannerController: UIViewController, GADBannerViewDelegate, MPAdViewDelegat dfpBanner.delegate = self dfpBanner.backgroundColor = .red appBannerView.addSubview(dfpBanner) - request.testDevices = [ kGADSimulatorID,"cc7ca766f86b43ab6cdc92bed424069b"] - - bannerUnit.fetchDemand(adObject:self.request) { [weak self] (ResultCode) in + request.testDevices = [ kGADSimulatorID, "cc7ca766f86b43ab6cdc92bed424069b"] + + bannerUnit.fetchDemand(adObject: self.request) { [weak self] (ResultCode) in print("Prebid demand fetch for DFP \(ResultCode.name())") self?.dfpBanner!.load(self?.request) } } - - func loadMoPubBanner(bannerUnit: AdUnit){ - + + func loadMoPubBanner(bannerUnit: AdUnit) { + let sdkConfig = MPMoPubConfiguration(adUnitIdForAppInitialization: "a935eac11acd416f92640411234fbba6") sdkConfig.globalMediationSettings = [] - + MoPub.sharedInstance().initializeSdk(with: sdkConfig) { - + } - + mopubBanner = MPAdView(adUnitId: "a935eac11acd416f92640411234fbba6", size: CGSize(width: 300, height: 250)) mopubBanner!.delegate = self - + appBannerView.addSubview(mopubBanner!) - + // Do any additional setup after loading the view, typically from a nib. - bannerUnit.fetchDemand(adObject: mopubBanner!){ (ResultCode) in + bannerUnit.fetchDemand(adObject: mopubBanner!) { (ResultCode) in print("Prebid demand fetch for mopub \(ResultCode)") - + self.mopubBanner!.loadAd() } - + } - + override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } - + func adViewDidReceiveAd(_ bannerView: GADBannerView) { print("adViewDidReceiveAd") } - + func adView(_ bannerView: GADBannerView, didFailToReceiveAdWithError error: GADRequestError) { print("adView:didFailToReceiveAdWithError: \(error.localizedDescription)") } - + func adViewDidReceiveAd(_ bannerView: DFPBannerView) { print("adViewDidReceiveAd") } - + /// Tells the delegate an ad request failed. func adView(_ bannerView: DFPBannerView, didFailToReceiveAdWithError error: GADRequestError) { print("adView:didFailToReceiveAdWithError: \(error.localizedDescription)") } - + func viewControllerForPresentingModalView() -> UIViewController! { return self } - - - - } - diff --git a/example/Swift/PrebidDemo/PrebidDemo/IndexController.swift b/example/Swift/PrebidDemo/PrebidDemo/IndexController.swift index 3ff41919a..edd06dc6e 100644 --- a/example/Swift/PrebidDemo/PrebidDemo/IndexController.swift +++ b/example/Swift/PrebidDemo/PrebidDemo/IndexController.swift @@ -1,11 +1,11 @@ /* Copyright 2018-2019 Prebid.org, Inc. - + 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. @@ -21,24 +21,20 @@ class IndexController: UIViewController { @IBOutlet var adServerSegment: UISegmentedControl! override func viewDidLoad() { super.viewDidLoad() - + self.title = "Prebid Demo" } - - override func prepare(for segue: UIStoryboardSegue, sender: Any?) - { - if segue.destination is BannerController - { + + override func prepare(for segue: UIStoryboardSegue, sender: Any?) { + if segue.destination is BannerController { let vc = segue.destination as? BannerController - vc?.adServerName = adServerSegment.titleForSegment(at: adServerSegment.selectedSegmentIndex)! + vc?.adServerName = adServerSegment.titleForSegment(at: adServerSegment.selectedSegmentIndex)! } - - if segue.destination is InterstitialViewController - { + + if segue.destination is InterstitialViewController { let vc = segue.destination as? InterstitialViewController vc?.adServerName = adServerSegment.titleForSegment(at: adServerSegment.selectedSegmentIndex)! } } - - + } diff --git a/example/Swift/PrebidDemo/PrebidDemo/InterstitialViewController.swift b/example/Swift/PrebidDemo/PrebidDemo/InterstitialViewController.swift index 5340107c6..d5f511cce 100644 --- a/example/Swift/PrebidDemo/PrebidDemo/InterstitialViewController.swift +++ b/example/Swift/PrebidDemo/PrebidDemo/InterstitialViewController.swift @@ -1,11 +1,11 @@ /* Copyright 2018-2019 Prebid.org, Inc. - + 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. @@ -22,105 +22,102 @@ import GoogleMobileAds import MoPub class InterstitialViewController: UIViewController, GADInterstitialDelegate, MPInterstitialAdControllerDelegate { - + @IBOutlet var adServerLabel: UILabel! - - var adServerName:String = "" - + + var adServerName: String = "" + let request = GADRequest() - + var dfpInterstitial: DFPInterstitial! - + var mopubInterstitial: MPInterstitialAdController! - - + override func viewDidLoad() { super.viewDidLoad() - + adServerLabel.text = adServerName - + Prebid.shared.prebidServerAccountId = "bfa84af2-bd16-4d35-96ad-31c6bb888df0" let interstitialUnit = InterstitialAdUnit(configId: "625c6125-f19e-4d5b-95c5-55501526b2a4") - - if(adServerName == "DFP"){ + + if (adServerName == "DFP") { print("entered \(adServerName) loop" ) loadDFPInterstitial(adUnit: interstitialUnit) - - } else if (adServerName == "MoPub"){ + + } else if (adServerName == "MoPub") { print("entered \(adServerName) loop" ) loadMoPubInterstitial(adUnit: interstitialUnit) - + } } - - func loadDFPInterstitial(adUnit : AdUnit){ + + func loadDFPInterstitial(adUnit: AdUnit) { print("Google Mobile Ads SDK version: \(DFPRequest.sdkVersion())") - + dfpInterstitial = DFPInterstitial(adUnitID: "/19968336/PrebidMobileValidator_Interstitial") dfpInterstitial.delegate = self request.testDevices = [ kGADSimulatorID] - adUnit.fetchDemand(adObject:self.request) { (ResultCode) in + adUnit.fetchDemand(adObject: self.request) { (ResultCode) in print("Prebid demand fetch for DFP \(ResultCode)") self.dfpInterstitial!.load(self.request) } } - - func loadMoPubInterstitial(adUnit: AdUnit){ - + + func loadMoPubInterstitial(adUnit: AdUnit) { + let sdkConfig = MPMoPubConfiguration(adUnitIdForAppInitialization: "2829868d308643edbec0795977f17437") sdkConfig.globalMediationSettings = [] - + MoPub.sharedInstance().initializeSdk(with: sdkConfig) { - + } - + self.mopubInterstitial = MPInterstitialAdController(forAdUnitId: "2829868d308643edbec0795977f17437") self.mopubInterstitial.delegate = self - + // Do any additional setup after loading the view, typically from a nib. - adUnit.fetchDemand(adObject: mopubInterstitial!){ (ResultCode) in + adUnit.fetchDemand(adObject: mopubInterstitial!) { (ResultCode) in print("Prebid demand fetch for mopub \(ResultCode)") self.mopubInterstitial.loadAd() } - + } - + override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } - + func interstitialWillPresentScreen(_ ad: GADInterstitial) { print("Ad presented") } - + func interstitialDidDismissScreen(_ ad: GADInterstitial) { // Send another GADRequest here print("Ad dismissed") } - + func interstitialDidReceiveAd(_ ad: GADInterstitial) { - - if(self.dfpInterstitial?.isReady ?? true) - { + + if (self.dfpInterstitial?.isReady ?? true) { print("Ad ready") self.dfpInterstitial?.present(fromRootViewController: self) - }else { - print("Ad not ready"); + } else { + print("Ad not ready") } } - + func interstitialDidLoadAd(_ interstitial: MPInterstitialAdController!) { print("Ad ready") - if(self.mopubInterstitial.ready ){ + if (self.mopubInterstitial.ready ) { self.mopubInterstitial.show(from: self) } } - + func interstitialDidFail(toLoadAd interstitial: MPInterstitialAdController!) { - print("Ad not ready"); + print("Ad not ready") } - -} +} diff --git a/example/Swift/PrebidDemo/PrebidDemoTests/Constants.swift b/example/Swift/PrebidDemo/PrebidDemoTests/Constants.swift index f2b5d4866..f3c379e94 100644 --- a/example/Swift/PrebidDemo/PrebidDemoTests/Constants.swift +++ b/example/Swift/PrebidDemo/PrebidDemoTests/Constants.swift @@ -1,11 +1,11 @@ /* Copyright 2018-2019 Prebid.org, Inc. - + 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. @@ -14,7 +14,7 @@ */ struct Constants { - + static let PBS_ACCOUNT_ID = "bfa84af2-bd16-4d35-96ad-31c6bb888df0" static let PBS_CONFIG_ID_300x250_APPNEXUS_DEMAND = "6ace8c7d-88c0-4623-8117-75bc3f0a2e45" static let PBS_CONFIG_ID_INTERSTITIAL_APPNEXUS_DEMAND = "625c6125-f19e-4d5b-95c5-55501526b2a4" diff --git a/example/Swift/PrebidDemo/PrebidDemoTests/PBViewTool.swift b/example/Swift/PrebidDemo/PrebidDemoTests/PBViewTool.swift index 938c96a80..52b57deb9 100644 --- a/example/Swift/PrebidDemo/PrebidDemoTests/PBViewTool.swift +++ b/example/Swift/PrebidDemo/PrebidDemoTests/PBViewTool.swift @@ -1,11 +1,11 @@ /* Copyright 2018-2019 Prebid.org, Inc. - + 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. @@ -14,6 +14,7 @@ */ import UIKit +import WebKit import GoogleMobileAds import MoPub @@ -21,93 +22,82 @@ class PBViewTool: NSObject { class func checkMPAdViewContainsPBMAd(_ view: MPAdView?, withCompletionHandler completionHandler: @escaping (_ result: Bool) -> Void) { var checked = false - for view in view!.subviews { - if (view is MPClosableView) { - if(view.isKind(of: MPClosableView.self)){ - let wv = view as! MPClosableView - - for innerView in (wv.subviews) { - if (innerView != nil) { - if(innerView.isKind(of: MPWebView.self)){ - let wv = innerView as! MPWebView - - wv.evaluateJavaScript("document.body.innerHTML", completionHandler: { result, error in - let content = result as? String - if content?.contains("prebid/pbm.js") ?? false || content?.contains("creative.js") ?? false { - completionHandler(true) - } else { - completionHandler(false) - } - }) - checked = true - break + for view in view!.subviews where (view is MPClosableView) { + if (view.isKind(of: MPClosableView.self)) { + let wv = view as! MPClosableView + + for innerView in (wv.subviews) where (innerView != nil) { + if (innerView.isKind(of: MPWebView.self)) { + let wv = innerView as! MPWebView + + wv.evaluateJavaScript("document.body.innerHTML", completionHandler: { result, _ in + let content = result as? String + if content?.contains("prebid/pbm.js") ?? false || content?.contains("creative.js") ?? false { + completionHandler(true) + } else { + completionHandler(false) } - - } + }) + checked = true + break } } - } } + if !checked { completionHandler(false) } } - + class func checkMPInterstitialContainsPBMAd(_ viewController: UIViewController, withCompletionHandler completionHandler: @escaping (_ result: Bool) -> Void) { var checked = false let mainView = viewController.view - for view in mainView!.subviews { - if (view is MPClosableView) { - if(view.isKind(of: MPClosableView.self)){ - let wv = view as! MPClosableView - - for innerView in (wv.subviews) { - if (innerView != nil) { - if(innerView.isKind(of: MPWebView.self)){ - let wv = innerView as! MPWebView - - wv.evaluateJavaScript("document.body.innerHTML", completionHandler: { result, error in - let content = result as? String - if content?.contains("prebid/pbm.js") ?? false || content?.contains("creative.js") ?? false { - completionHandler(true) - } else { - completionHandler(false) - } - }) - checked = true - break + for view in mainView!.subviews where (view is MPClosableView) { + if (view.isKind(of: MPClosableView.self)) { + let wv = view as! MPClosableView + + for innerView in (wv.subviews) where (innerView != nil) { + if (innerView.isKind(of: MPWebView.self)) { + let wv = innerView as! MPWebView + + wv.evaluateJavaScript("document.body.innerHTML", completionHandler: { result, _ in + let content = result as? String + if content?.contains("prebid/pbm.js") ?? false || content?.contains("creative.js") ?? false { + completionHandler(true) + } else { + completionHandler(false) } - - } + }) + checked = true + break } } - } } + if !checked { completionHandler(false) } } - + class func checkDFPInterstitialAdViewContainsPBMAd(_ viewController: UIViewController) -> Bool { - let view:UIView = viewController.view + let view: UIView = viewController.view let subviews = view.subviews - + for view in subviews { - let name:String = String(describing: type(of: view)) - if(name == "GADNWebAdView" || name == "GADOAdView"){ + let name: String = String(describing: type(of: view)) + if (name == "GADNWebAdView" || name == "GADOAdView") { let views = view.subviews - for innerView in views{ - let nameInner:String = String(describing: type(of: innerView)) - if(innerView.isKind(of: UIWebView.self)){ - return PBViewTool.checkJSExistInWebView(webView: innerView as! UIWebView) - } - else if(nameInner == "GADOUIKitWebView"){ + for innerView in views { + let nameInner: String = String(describing: type(of: innerView)) + if (innerView.isKind(of: WKWebView.self)) { + return PBViewTool.checkJSExistInWebView(webView: innerView as! WKWebView) + } else if (nameInner == "GADOUIKitWebView") { let deepInnerView = innerView.subviews - for innerView2 in deepInnerView{ - if(innerView2.isKind(of: UIWebView.self)){ - return PBViewTool.checkJSExistInWebView(webView: innerView2 as! UIWebView) + for innerView2 in deepInnerView { + if (innerView2.isKind(of: WKWebView.self)) { + return PBViewTool.checkJSExistInWebView(webView: innerView2 as! WKWebView) } } } @@ -116,7 +106,7 @@ class PBViewTool: NSObject { } return false } - + class func checkDFPAdViewContainsPBMAd(_ view: GADBannerView?) -> Bool { for level1: UIView? in (view?.subviews)! { let level2s = level1?.subviews @@ -125,11 +115,9 @@ class PBViewTool: NSObject { for level4: UIView? in level3?.subviews ?? [] { for level5: UIView? in level4?.subviews ?? [] { for level6: UIView? in level5?.subviews ?? [] { - if (level6 is UIWebView) { - return PBViewTool.checkJSExistInWebView(webView: level6 as! UIWebView) - } - else if level5 == nil - { + if (level6 is WKWebView) { + return PBViewTool.checkJSExistInWebView(webView: level6 as! WKWebView) + } else if level5 == nil { return false } } @@ -140,14 +128,27 @@ class PBViewTool: NSObject { } return false } - - class func checkJSExistInWebView(webView:UIWebView)->Bool - { - let content:String = webView.stringByEvaluatingJavaScript(from: "document.body.innerHTML")! - if content.contains("prebid/pbm.js") || content.contains("creative.js") { + + class func checkJSExistInWebView(webView: WKWebView) -> Bool { + let sema = DispatchSemaphore(value: 0) + var content: String? + DispatchQueue.global().async { + // Background thread + webView.evaluateJavaScript("document.body.innerHTML", completionHandler: { (value: Any!, _: Error!) -> Void in + if let contentHtml = value as? String { + content = contentHtml + } else { + } + sema.signal() + }) + } + sema.wait() + + if ((content?.contains("prebid/pbm.js"))!) || (content?.contains("creative.js"))! { return true } else { return false + } } } diff --git a/example/Swift/PrebidDemo/PrebidDemoTests/PrebidDemoTests.swift b/example/Swift/PrebidDemo/PrebidDemoTests/PrebidDemoTests.swift index 4e2d341a3..1fbfe1d2e 100644 --- a/example/Swift/PrebidDemo/PrebidDemoTests/PrebidDemoTests.swift +++ b/example/Swift/PrebidDemo/PrebidDemoTests/PrebidDemoTests.swift @@ -1,11 +1,11 @@ /* Copyright 2018-2019 Prebid.org, Inc. - + 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. @@ -20,38 +20,36 @@ import WebKit @testable import PrebidMobile @testable import PrebidDemo -class PrebidDemoTests: XCTestCase, GADBannerViewDelegate, GADInterstitialDelegate, MPAdViewDelegate, MPInterstitialAdControllerDelegate { - - +class PrebidDemoTests: XCTestCase, GADBannerViewDelegate, GADInterstitialDelegate, MPAdViewDelegate, MPInterstitialAdControllerDelegate { + var viewController: IndexController? var loadSuccesfulException: XCTestExpectation? var timeoutForRequest: TimeInterval = 0.0 var mopubInterstitial: MPInterstitialAdController? var dfpInterstitial: DFPInterstitial? - + override func setUp() { // Put setup code here. This method is called before the invocation of each test method in the class. // Prebid.shared.prebidServerHost = PrebidHost.Appnexus Prebid.shared.prebidServerAccountId = Constants.PBS_ACCOUNT_ID // Prebid.shared.shareGeoLocation = true timeoutForRequest = 35.0 - + let storyboard = UIStoryboard(name: "Main", bundle: Bundle.main) viewController = storyboard.instantiateViewController(withIdentifier: "index") as? IndexController let appDelegate = (UIApplication.shared.delegate as! AppDelegate) appDelegate.window?.rootViewController = viewController } - + override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. loadSuccesfulException = nil mopubInterstitial = nil dfpInterstitial = nil } - - func testDFPBannerSanityAppCheckTest() - { + + func testDFPBannerSanityAppCheckTest() { timeoutForRequest = 30.0 let bannerUnit = BannerAdUnit(configId: Constants.PBS_CONFIG_ID_300x250_APPNEXUS_DEMAND, size: CGSize(width: 300, height: 250)) let dfpBanner = DFPBannerView(adSize: kGADAdSizeMediumRectangle) @@ -60,21 +58,18 @@ class PrebidDemoTests: XCTestCase, GADBannerViewDelegate, GADInterstitialDelegat dfpBanner.delegate = self dfpBanner.backgroundColor = .red viewController?.view.addSubview(dfpBanner) - let request:DFPRequest = DFPRequest() - request.testDevices = [ kGADSimulatorID,"cc7ca766f86b43ab6cdc92bed424069b"] - bannerUnit.fetchDemand(adObject:request) { (ResultCode) in + let request: DFPRequest = DFPRequest() + request.testDevices = [ kGADSimulatorID, "cc7ca766f86b43ab6cdc92bed424069b"] + bannerUnit.fetchDemand(adObject: request) { (ResultCode) in //DispatchQueue.main.async { - if 0 == ResultCode.rawValue - { + if 0 == ResultCode.rawValue { DispatchQueue.main.async { XCTAssertEqual(0, ResultCode.rawValue) XCTAssertNotNil(request.customTargeting) XCTAssertNotNil(request.customTargeting!["hb_pb"]) dfpBanner.load(request) } - } - else - { + } else { XCTFail("Unexpected response") self.loadSuccesfulException?.fulfill() } @@ -82,11 +77,10 @@ class PrebidDemoTests: XCTestCase, GADBannerViewDelegate, GADInterstitialDelegat } loadSuccesfulException = expectation(description: "\(#function)") waitForExpectations(timeout: timeoutForRequest, handler: nil) - + } - - func testDFPBannerWithoutAutoRefresh() - { + + func testDFPBannerWithoutAutoRefresh() { var fetchDemandCount = 0 let bannerUnit = BannerAdUnit(configId: Constants.PBS_CONFIG_ID_300x250_APPNEXUS_DEMAND, size: CGSize(width: 300, height: 250)) let dfpBanner = DFPBannerView(adSize: kGADAdSizeMediumRectangle) @@ -94,19 +88,18 @@ class PrebidDemoTests: XCTestCase, GADBannerViewDelegate, GADInterstitialDelegat dfpBanner.rootViewController = viewController dfpBanner.backgroundColor = .red viewController?.view.addSubview(dfpBanner) - let request:DFPRequest = DFPRequest() - request.testDevices = [ kGADSimulatorID,"cc7ca766f86b43ab6cdc92bed424069b"] - bannerUnit.fetchDemand(adObject:request) { (ResultCode) in + let request: DFPRequest = DFPRequest() + request.testDevices = [ kGADSimulatorID, "cc7ca766f86b43ab6cdc92bed424069b"] + bannerUnit.fetchDemand(adObject: request) { (_) in DispatchQueue.main.async { - fetchDemandCount = fetchDemandCount + 1 + fetchDemandCount += 1 } } wait(31) XCTAssertEqual(1, fetchDemandCount) } - - func testDFPBannerWithInvalidAutoRefresh() - { + + func testDFPBannerWithInvalidAutoRefresh() { var fetchDemandCount = 0 let bannerUnit = BannerAdUnit(configId: Constants.PBS_CONFIG_ID_300x250_APPNEXUS_DEMAND, size: CGSize(width: 300, height: 250)) bannerUnit.setAutoRefreshMillis(time: 20000) @@ -115,19 +108,18 @@ class PrebidDemoTests: XCTestCase, GADBannerViewDelegate, GADInterstitialDelegat dfpBanner.rootViewController = viewController dfpBanner.backgroundColor = .red viewController?.view.addSubview(dfpBanner) - let request:DFPRequest = DFPRequest() - request.testDevices = [ kGADSimulatorID,"cc7ca766f86b43ab6cdc92bed424069b"] - bannerUnit.fetchDemand(adObject:request) { (ResultCode) in + let request: DFPRequest = DFPRequest() + request.testDevices = [ kGADSimulatorID, "cc7ca766f86b43ab6cdc92bed424069b"] + bannerUnit.fetchDemand(adObject: request) { (_) in DispatchQueue.main.async { - fetchDemandCount = fetchDemandCount + 1 + fetchDemandCount += 1 } } wait(31) XCTAssertEqual(1, fetchDemandCount) } - - func testDFPBannerWithValidAutoRefresh() - { + + func testDFPBannerWithValidAutoRefresh() { var fetchDemandCount = 0 let bannerUnit = BannerAdUnit(configId: Constants.PBS_CONFIG_ID_300x250_APPNEXUS_DEMAND, size: CGSize(width: 300, height: 250)) bannerUnit.setAutoRefreshMillis(time: 30000) @@ -136,37 +128,33 @@ class PrebidDemoTests: XCTestCase, GADBannerViewDelegate, GADInterstitialDelegat dfpBanner.rootViewController = viewController dfpBanner.backgroundColor = .red viewController?.view.addSubview(dfpBanner) - let request:DFPRequest = DFPRequest() - request.testDevices = [ kGADSimulatorID,"cc7ca766f86b43ab6cdc92bed424069b"] - bannerUnit.fetchDemand(adObject:request) { (ResultCode) in + let request: DFPRequest = DFPRequest() + request.testDevices = [ kGADSimulatorID, "cc7ca766f86b43ab6cdc92bed424069b"] + bannerUnit.fetchDemand(adObject: request) { (_) in DispatchQueue.main.async { - fetchDemandCount = fetchDemandCount + 1 + fetchDemandCount += 1 } } wait(31) XCTAssertEqual(2, fetchDemandCount) } - - func testDFPInterstitialSanityAppCheckTest() - { + + func testDFPInterstitialSanityAppCheckTest() { timeoutForRequest = 30.0 let interstitialUnit = InterstitialAdUnit(configId: Constants.PBS_CONFIG_ID_INTERSTITIAL_APPNEXUS_DEMAND) dfpInterstitial = DFPInterstitial(adUnitID: Constants.DFP_INTERSTITIAL_ADUNIT_ID) - let request:DFPRequest = DFPRequest() + let request: DFPRequest = DFPRequest() dfpInterstitial?.delegate = self request.testDevices = [ kGADSimulatorID] - interstitialUnit.fetchDemand(adObject:request) { (ResultCode) in + interstitialUnit.fetchDemand(adObject: request) { (ResultCode) in DispatchQueue.main.async { - if 0 == ResultCode.rawValue - { + if 0 == ResultCode.rawValue { XCTAssertEqual(0, ResultCode.rawValue) XCTAssertNotNil(request.customTargeting) XCTAssertNotNil(request.customTargeting!["hb_pb"]) self.dfpInterstitial?.load(request) - - } - else - { + + } else { XCTFail("Unexpected response") self.loadSuccesfulException?.fulfill() } @@ -175,78 +163,71 @@ class PrebidDemoTests: XCTestCase, GADBannerViewDelegate, GADInterstitialDelegat loadSuccesfulException = expectation(description: "\(#function)") waitForExpectations(timeout: timeoutForRequest, handler: nil) } - - func testDFPInterstitialWithoutAutoRefresh() - { + + func testDFPInterstitialWithoutAutoRefresh() { var fetchDemandCount = 0 let interstitialUnit = InterstitialAdUnit(configId: Constants.PBS_CONFIG_ID_INTERSTITIAL_APPNEXUS_DEMAND) dfpInterstitial = DFPInterstitial(adUnitID: Constants.DFP_INTERSTITIAL_ADUNIT_ID) - let request:DFPRequest = DFPRequest() + let request: DFPRequest = DFPRequest() request.testDevices = [ kGADSimulatorID] - interstitialUnit.fetchDemand(adObject:request) { (ResultCode) in + interstitialUnit.fetchDemand(adObject: request) { (_) in DispatchQueue.main.async { - fetchDemandCount = fetchDemandCount + 1 + fetchDemandCount += 1 } } wait(31) XCTAssertEqual(1, fetchDemandCount) } - - func testDFPInterstitialWithInvalidAutoRefresh() - { + + func testDFPInterstitialWithInvalidAutoRefresh() { var fetchDemandCount = 0 let interstitialUnit = InterstitialAdUnit(configId: Constants.PBS_CONFIG_ID_INTERSTITIAL_APPNEXUS_DEMAND) interstitialUnit.setAutoRefreshMillis(time: 20000) dfpInterstitial = DFPInterstitial(adUnitID: Constants.DFP_INTERSTITIAL_ADUNIT_ID) - let request:DFPRequest = DFPRequest() + let request: DFPRequest = DFPRequest() request.testDevices = [ kGADSimulatorID] - interstitialUnit.fetchDemand(adObject:request) { (ResultCode) in + interstitialUnit.fetchDemand(adObject: request) { (_) in DispatchQueue.main.async { - fetchDemandCount = fetchDemandCount + 1 + fetchDemandCount += 1 } } wait(31) XCTAssertEqual(1, fetchDemandCount) } - - func testDFPInterstitialWithValidAutoRefresh() - { + + func testDFPInterstitialWithValidAutoRefresh() { var fetchDemandCount = 0 let interstitialUnit = InterstitialAdUnit(configId: Constants.PBS_CONFIG_ID_INTERSTITIAL_APPNEXUS_DEMAND) interstitialUnit.setAutoRefreshMillis(time: 30000) dfpInterstitial = DFPInterstitial(adUnitID: Constants.DFP_INTERSTITIAL_ADUNIT_ID) - let request:DFPRequest = DFPRequest() + let request: DFPRequest = DFPRequest() request.testDevices = [ kGADSimulatorID] - interstitialUnit.fetchDemand(adObject:request) { (ResultCode) in + interstitialUnit.fetchDemand(adObject: request) { (_) in DispatchQueue.main.async { - fetchDemandCount = fetchDemandCount + 1 + fetchDemandCount += 1 } } wait(31) XCTAssertEqual(2, fetchDemandCount) } - - func testMoPubBannerSanityAppCheckTest() - { + + func testMoPubBannerSanityAppCheckTest() { timeoutForRequest = 20.0 let bannerUnit = BannerAdUnit(configId: Constants.PBS_CONFIG_ID_300x250_APPNEXUS_DEMAND, size: CGSize(width: 300, height: 250)) - let sdkConfig = MPMoPubConfiguration(adUnitIdForAppInitialization:Constants.MOPUB_BANNER_ADUNIT_ID_300x250) + let sdkConfig = MPMoPubConfiguration(adUnitIdForAppInitialization: Constants.MOPUB_BANNER_ADUNIT_ID_300x250) sdkConfig.globalMediationSettings = [] - MoPub.sharedInstance().initializeSdk(with: sdkConfig){} + MoPub.sharedInstance().initializeSdk(with: sdkConfig) {} let mopubBanner = MPAdView(adUnitId: Constants.MOPUB_BANNER_ADUNIT_ID_300x250, size: CGSize(width: 300, height: 250)) mopubBanner?.delegate = self viewController?.view.addSubview(mopubBanner!) - bannerUnit.fetchDemand(adObject: mopubBanner!){ (ResultCode) in + bannerUnit.fetchDemand(adObject: mopubBanner!) { (ResultCode) in DispatchQueue.main.async { - if 0 == ResultCode.rawValue - { + if 0 == ResultCode.rawValue { XCTAssertEqual(0, ResultCode.rawValue) XCTAssertNotNil(mopubBanner!.keywords) XCTAssertNotNil(mopubBanner!.keywords.contains("hb_pb")) mopubBanner!.loadAd() - } - else - { + } else { XCTFail("Unexpected response") self.loadSuccesfulException?.fulfill() } @@ -255,81 +236,74 @@ class PrebidDemoTests: XCTestCase, GADBannerViewDelegate, GADInterstitialDelegat loadSuccesfulException = expectation(description: "\(#function)") waitForExpectations(timeout: timeoutForRequest, handler: nil) } - - func testMopubBannerWithoutAutoRefresh() - { + + func testMopubBannerWithoutAutoRefresh() { var fetchDemandCount = 0 let bannerUnit = BannerAdUnit(configId: Constants.PBS_CONFIG_ID_300x250_APPNEXUS_DEMAND, size: CGSize(width: 300, height: 250)) - let sdkConfig = MPMoPubConfiguration(adUnitIdForAppInitialization:Constants.MOPUB_BANNER_ADUNIT_ID_300x250) + let sdkConfig = MPMoPubConfiguration(adUnitIdForAppInitialization: Constants.MOPUB_BANNER_ADUNIT_ID_300x250) sdkConfig.globalMediationSettings = [] - MoPub.sharedInstance().initializeSdk(with: sdkConfig){} + MoPub.sharedInstance().initializeSdk(with: sdkConfig) {} let mopubBanner = MPAdView(adUnitId: Constants.MOPUB_BANNER_ADUNIT_ID_300x250, size: CGSize(width: 300, height: 250)) - bannerUnit.fetchDemand(adObject: mopubBanner!){ (ResultCode) in + bannerUnit.fetchDemand(adObject: mopubBanner!) { (_) in DispatchQueue.main.async { - fetchDemandCount = fetchDemandCount + 1 + fetchDemandCount += 1 } } wait(31) XCTAssertEqual(1, fetchDemandCount) } - - func testMopubBannerWithInvalidAutoRefresh() - { + + func testMopubBannerWithInvalidAutoRefresh() { var fetchDemandCount = 0 let bannerUnit = BannerAdUnit(configId: Constants.PBS_CONFIG_ID_300x250_APPNEXUS_DEMAND, size: CGSize(width: 300, height: 250)) bannerUnit.setAutoRefreshMillis(time: 20000) - let sdkConfig = MPMoPubConfiguration(adUnitIdForAppInitialization:Constants.MOPUB_BANNER_ADUNIT_ID_300x250) + let sdkConfig = MPMoPubConfiguration(adUnitIdForAppInitialization: Constants.MOPUB_BANNER_ADUNIT_ID_300x250) sdkConfig.globalMediationSettings = [] - MoPub.sharedInstance().initializeSdk(with: sdkConfig){} + MoPub.sharedInstance().initializeSdk(with: sdkConfig) {} let mopubBanner = MPAdView(adUnitId: Constants.MOPUB_BANNER_ADUNIT_ID_300x250, size: CGSize(width: 300, height: 250)) - bannerUnit.fetchDemand(adObject: mopubBanner!){ (ResultCode) in + bannerUnit.fetchDemand(adObject: mopubBanner!) { (_) in DispatchQueue.main.async { - fetchDemandCount = fetchDemandCount + 1 + fetchDemandCount += 1 } } wait(31) XCTAssertEqual(1, fetchDemandCount) } - - func testMopubBannerWithValidAutoRefresh() - { + + func testMopubBannerWithValidAutoRefresh() { var fetchDemandCount = 0 let bannerUnit = BannerAdUnit(configId: Constants.PBS_CONFIG_ID_300x250_APPNEXUS_DEMAND, size: CGSize(width: 300, height: 250)) bannerUnit.setAutoRefreshMillis(time: 30000) - let sdkConfig = MPMoPubConfiguration(adUnitIdForAppInitialization:Constants.MOPUB_BANNER_ADUNIT_ID_300x250) + let sdkConfig = MPMoPubConfiguration(adUnitIdForAppInitialization: Constants.MOPUB_BANNER_ADUNIT_ID_300x250) sdkConfig.globalMediationSettings = [] - MoPub.sharedInstance().initializeSdk(with: sdkConfig){} + MoPub.sharedInstance().initializeSdk(with: sdkConfig) {} let mopubBanner = MPAdView(adUnitId: Constants.MOPUB_BANNER_ADUNIT_ID_300x250, size: CGSize(width: 300, height: 250)) - bannerUnit.fetchDemand(adObject: mopubBanner!){ (ResultCode) in + bannerUnit.fetchDemand(adObject: mopubBanner!) { (_) in DispatchQueue.main.async { - fetchDemandCount = fetchDemandCount + 1 + fetchDemandCount += 1 } } wait(31) XCTAssertEqual(2, fetchDemandCount) } - - func testMoPubInterstitialSanityAppCheckTest() - { + + func testMoPubInterstitialSanityAppCheckTest() { timeoutForRequest = 20.0 let interstitialUnit = InterstitialAdUnit(configId: Constants.PBS_CONFIG_ID_INTERSTITIAL_APPNEXUS_DEMAND) - let sdkConfig = MPMoPubConfiguration(adUnitIdForAppInitialization:Constants.MOPUB_INTERSTITIAL_ADUNIT_ID) + let sdkConfig = MPMoPubConfiguration(adUnitIdForAppInitialization: Constants.MOPUB_INTERSTITIAL_ADUNIT_ID) sdkConfig.globalMediationSettings = [] - MoPub.sharedInstance().initializeSdk(with: sdkConfig){} + MoPub.sharedInstance().initializeSdk(with: sdkConfig) {} mopubInterstitial = MPInterstitialAdController(forAdUnitId: Constants.MOPUB_INTERSTITIAL_ADUNIT_ID) mopubInterstitial?.delegate = self - interstitialUnit.fetchDemand(adObject: mopubInterstitial!){ (ResultCode) in + interstitialUnit.fetchDemand(adObject: mopubInterstitial!) { (ResultCode) in DispatchQueue.main.async { - if 0 == ResultCode.rawValue - { + if 0 == ResultCode.rawValue { XCTAssertEqual(0, ResultCode.rawValue) XCTAssertNotNil(self.mopubInterstitial!.keywords) XCTAssertNotNil(self.mopubInterstitial!.keywords.contains("hb_pb")) self.mopubInterstitial?.loadAd() - - } - else - { + + } else { XCTFail("Unexpected response") self.loadSuccesfulException?.fulfill() } @@ -338,62 +312,58 @@ class PrebidDemoTests: XCTestCase, GADBannerViewDelegate, GADInterstitialDelegat loadSuccesfulException = expectation(description: "\(#function)") waitForExpectations(timeout: timeoutForRequest, handler: nil) } - - func testMopubInterstitialWithoutAutoRefresh() - { + + func testMopubInterstitialWithoutAutoRefresh() { var fetchDemandCount = 0 let interstitialUnit = InterstitialAdUnit(configId: Constants.PBS_CONFIG_ID_INTERSTITIAL_APPNEXUS_DEMAND) - let sdkConfig = MPMoPubConfiguration(adUnitIdForAppInitialization:Constants.MOPUB_INTERSTITIAL_ADUNIT_ID) + let sdkConfig = MPMoPubConfiguration(adUnitIdForAppInitialization: Constants.MOPUB_INTERSTITIAL_ADUNIT_ID) sdkConfig.globalMediationSettings = [] - MoPub.sharedInstance().initializeSdk(with: sdkConfig){} + MoPub.sharedInstance().initializeSdk(with: sdkConfig) {} mopubInterstitial = MPInterstitialAdController(forAdUnitId: Constants.MOPUB_INTERSTITIAL_ADUNIT_ID) - interstitialUnit.fetchDemand(adObject: mopubInterstitial!){ (ResultCode) in + interstitialUnit.fetchDemand(adObject: mopubInterstitial!) { (_) in DispatchQueue.main.async { - fetchDemandCount = fetchDemandCount + 1 + fetchDemandCount += 1 } } wait(31) XCTAssertEqual(1, fetchDemandCount) } - - func testMopubInterstitialWithInvalidAutoRefresh() - { + + func testMopubInterstitialWithInvalidAutoRefresh() { var fetchDemandCount = 0 let interstitialUnit = InterstitialAdUnit(configId: Constants.PBS_CONFIG_ID_INTERSTITIAL_APPNEXUS_DEMAND) interstitialUnit.setAutoRefreshMillis(time: 20000) - let sdkConfig = MPMoPubConfiguration(adUnitIdForAppInitialization:Constants.MOPUB_INTERSTITIAL_ADUNIT_ID) + let sdkConfig = MPMoPubConfiguration(adUnitIdForAppInitialization: Constants.MOPUB_INTERSTITIAL_ADUNIT_ID) sdkConfig.globalMediationSettings = [] - MoPub.sharedInstance().initializeSdk(with: sdkConfig){} + MoPub.sharedInstance().initializeSdk(with: sdkConfig) {} mopubInterstitial = MPInterstitialAdController(forAdUnitId: Constants.MOPUB_INTERSTITIAL_ADUNIT_ID) - interstitialUnit.fetchDemand(adObject: mopubInterstitial!){ (ResultCode) in + interstitialUnit.fetchDemand(adObject: mopubInterstitial!) { (_) in DispatchQueue.main.async { - fetchDemandCount = fetchDemandCount + 1 + fetchDemandCount += 1 } } wait(31) XCTAssertEqual(1, fetchDemandCount) } - - func testMopubInterstitialWithValidAutoRefresh() - { + + func testMopubInterstitialWithValidAutoRefresh() { var fetchDemandCount = 0 let interstitialUnit = InterstitialAdUnit(configId: Constants.PBS_CONFIG_ID_INTERSTITIAL_APPNEXUS_DEMAND) interstitialUnit.setAutoRefreshMillis(time: 30000) - let sdkConfig = MPMoPubConfiguration(adUnitIdForAppInitialization:Constants.MOPUB_INTERSTITIAL_ADUNIT_ID) + let sdkConfig = MPMoPubConfiguration(adUnitIdForAppInitialization: Constants.MOPUB_INTERSTITIAL_ADUNIT_ID) sdkConfig.globalMediationSettings = [] - MoPub.sharedInstance().initializeSdk(with: sdkConfig){} + MoPub.sharedInstance().initializeSdk(with: sdkConfig) {} mopubInterstitial = MPInterstitialAdController(forAdUnitId: Constants.MOPUB_INTERSTITIAL_ADUNIT_ID) - interstitialUnit.fetchDemand(adObject: mopubInterstitial!){ (ResultCode) in + interstitialUnit.fetchDemand(adObject: mopubInterstitial!) { (_) in DispatchQueue.main.async { - fetchDemandCount = fetchDemandCount + 1 + fetchDemandCount += 1 } } wait(31) XCTAssertEqual(2, fetchDemandCount) } - - func testAutoRefreshWith2MinThenDisable() - { + + func testAutoRefreshWith2MinThenDisable() { var fetchDemandCount = 0 let bannerUnit = BannerAdUnit(configId: Constants.PBS_CONFIG_ID_300x250_APPNEXUS_DEMAND, size: CGSize(width: 300, height: 250)) bannerUnit.setAutoRefreshMillis(time: 30000) @@ -402,11 +372,11 @@ class PrebidDemoTests: XCTestCase, GADBannerViewDelegate, GADInterstitialDelegat dfpBanner.rootViewController = viewController dfpBanner.backgroundColor = .red viewController?.view.addSubview(dfpBanner) - let request:DFPRequest = DFPRequest() - request.testDevices = [ kGADSimulatorID,"cc7ca766f86b43ab6cdc92bed424069b"] - bannerUnit.fetchDemand(adObject:request) { (ResultCode) in + let request: DFPRequest = DFPRequest() + request.testDevices = [ kGADSimulatorID, "cc7ca766f86b43ab6cdc92bed424069b"] + bannerUnit.fetchDemand(adObject: request) { (_) in DispatchQueue.main.async { - fetchDemandCount = fetchDemandCount + 1 + fetchDemandCount += 1 } } wait(124) @@ -416,9 +386,8 @@ class PrebidDemoTests: XCTestCase, GADBannerViewDelegate, GADInterstitialDelegat wait(35) XCTAssertEqual(0, fetchDemandCount) } - - func testAutoRefreshWith5MinThenDisable() - { + + func testAutoRefreshWith5MinThenDisable() { var fetchDemandCount = 0 let bannerUnit = BannerAdUnit(configId: Constants.PBS_CONFIG_ID_300x250_APPNEXUS_DEMAND, size: CGSize(width: 300, height: 250)) bannerUnit.setAutoRefreshMillis(time: 120000) @@ -427,11 +396,11 @@ class PrebidDemoTests: XCTestCase, GADBannerViewDelegate, GADInterstitialDelegat dfpBanner.rootViewController = viewController dfpBanner.backgroundColor = .red viewController?.view.addSubview(dfpBanner) - let request:DFPRequest = DFPRequest() - request.testDevices = [ kGADSimulatorID,"cc7ca766f86b43ab6cdc92bed424069b"] - bannerUnit.fetchDemand(adObject:request) { (ResultCode) in + let request: DFPRequest = DFPRequest() + request.testDevices = [ kGADSimulatorID, "cc7ca766f86b43ab6cdc92bed424069b"] + bannerUnit.fetchDemand(adObject: request) { (_) in DispatchQueue.main.async { - fetchDemandCount = fetchDemandCount + 1 + fetchDemandCount += 1 } } wait(300) @@ -441,17 +410,16 @@ class PrebidDemoTests: XCTestCase, GADBannerViewDelegate, GADInterstitialDelegat wait(35) XCTAssertEqual(0, fetchDemandCount) } - - func testInvalidPrebidServerAccountId() - { + + func testInvalidPrebidServerAccountId() { Prebid.shared.prebidServerAccountId = Constants.PBS_INVALID_ACCOUNT_ID timeoutForRequest = 10.0 let bannerUnit = BannerAdUnit(configId: Constants.PBS_CONFIG_ID_300x250_APPNEXUS_DEMAND, size: CGSize(width: 300, height: 250)) let dfpBanner = DFPBannerView(adSize: kGADAdSizeMediumRectangle) dfpBanner.adUnitID = Constants.DFP_BANNER_ADUNIT_ID_300x250 - let request:DFPRequest = DFPRequest() + let request: DFPRequest = DFPRequest() request.testDevices = [ kGADSimulatorID] - bannerUnit.fetchDemand(adObject:request) { (ResultCode) in + bannerUnit.fetchDemand(adObject: request) { (ResultCode) in DispatchQueue.main.async { XCTAssertEqual(2, ResultCode.rawValue) self.loadSuccesfulException?.fulfill() @@ -459,19 +427,18 @@ class PrebidDemoTests: XCTestCase, GADBannerViewDelegate, GADInterstitialDelegat } loadSuccesfulException = expectation(description: "\(#function)") waitForExpectations(timeout: timeoutForRequest, handler: nil) - + } - - func testEmptyPrebidServerAccountId() - { + + func testEmptyPrebidServerAccountId() { Prebid.shared.prebidServerAccountId = Constants.PBS_EMPTY_ACCOUNT_ID timeoutForRequest = 10.0 let bannerUnit = BannerAdUnit(configId: Constants.PBS_CONFIG_ID_300x250_APPNEXUS_DEMAND, size: CGSize(width: 300, height: 250)) let dfpBanner = DFPBannerView(adSize: kGADAdSizeMediumRectangle) dfpBanner.adUnitID = Constants.DFP_BANNER_ADUNIT_ID_300x250 - let request:DFPRequest = DFPRequest() + let request: DFPRequest = DFPRequest() request.testDevices = [ kGADSimulatorID] - bannerUnit.fetchDemand(adObject:request) { (ResultCode) in + bannerUnit.fetchDemand(adObject: request) { (ResultCode) in DispatchQueue.main.async { XCTAssertEqual(2, ResultCode.rawValue) self.loadSuccesfulException?.fulfill() @@ -479,18 +446,17 @@ class PrebidDemoTests: XCTestCase, GADBannerViewDelegate, GADInterstitialDelegat } loadSuccesfulException = expectation(description: "\(#function)") waitForExpectations(timeout: timeoutForRequest, handler: nil) - + } - - func testInvalidConfigId() - { + + func testInvalidConfigId() { timeoutForRequest = 10.0 let bannerUnit = BannerAdUnit(configId: Constants.PBS_INVALID_CONFIG_ID, size: CGSize(width: 300, height: 250)) let dfpBanner = DFPBannerView(adSize: kGADAdSizeMediumRectangle) dfpBanner.adUnitID = Constants.DFP_BANNER_ADUNIT_ID_300x250 - let request:DFPRequest = DFPRequest() + let request: DFPRequest = DFPRequest() request.testDevices = [ kGADSimulatorID] - bannerUnit.fetchDemand(adObject:request) { (ResultCode) in + bannerUnit.fetchDemand(adObject: request) { (ResultCode) in DispatchQueue.main.async { XCTAssertEqual(3, ResultCode.rawValue) self.loadSuccesfulException?.fulfill() @@ -498,18 +464,17 @@ class PrebidDemoTests: XCTestCase, GADBannerViewDelegate, GADInterstitialDelegat } loadSuccesfulException = expectation(description: "\(#function)") waitForExpectations(timeout: timeoutForRequest, handler: nil) - + } - - func testEmptyConfigId() - { + + func testEmptyConfigId() { timeoutForRequest = 10.0 let bannerUnit = BannerAdUnit(configId: Constants.PBS_EMPTY_CONFIG_ID, size: CGSize(width: 300, height: 250)) let dfpBanner = DFPBannerView(adSize: kGADAdSizeMediumRectangle) dfpBanner.adUnitID = Constants.DFP_BANNER_ADUNIT_ID_300x250 - let request:DFPRequest = DFPRequest() + let request: DFPRequest = DFPRequest() request.testDevices = [ kGADSimulatorID] - bannerUnit.fetchDemand(adObject:request) { (ResultCode) in + bannerUnit.fetchDemand(adObject: request) { (ResultCode) in DispatchQueue.main.async { XCTAssertEqual(3, ResultCode.rawValue) self.loadSuccesfulException?.fulfill() @@ -518,20 +483,19 @@ class PrebidDemoTests: XCTestCase, GADBannerViewDelegate, GADInterstitialDelegat } loadSuccesfulException = expectation(description: "\(#function)") waitForExpectations(timeout: timeoutForRequest, handler: nil) - + } - - func testRubiconDemandForDFP() - { + + func testRubiconDemandForDFP() { timeoutForRequest = 10.0 Prebid.shared.prebidServerHost = PrebidHost.Rubicon Prebid.shared.prebidServerAccountId = Constants.PBS_RUBICON_ACCOUNT_ID let bannerUnit = BannerAdUnit(configId: "1001-2", size: CGSize(width: 300, height: 250)) let dfpBanner = DFPBannerView(adSize: kGADAdSizeMediumRectangle) dfpBanner.adUnitID = "/112115922/PB_test_2" - let request:DFPRequest = DFPRequest() + let request: DFPRequest = DFPRequest() request.testDevices = [ kGADSimulatorID] - bannerUnit.fetchDemand(adObject:request) { (ResultCode) in + bannerUnit.fetchDemand(adObject: request) { (ResultCode) in DispatchQueue.main.async { XCTAssertEqual(0, ResultCode.rawValue) self.loadSuccesfulException?.fulfill() @@ -540,21 +504,20 @@ class PrebidDemoTests: XCTestCase, GADBannerViewDelegate, GADInterstitialDelegat loadSuccesfulException = expectation(description: "\(#function)") waitForExpectations(timeout: timeoutForRequest, handler: nil) } - - func testYOBWith2018() - { + + func testYOBWith2018() { let targeting = Targeting.shared XCTAssertNoThrow(try targeting.setYearOfBirth(yob: 2018)) let value = Targeting.shared.yearOfBirth XCTAssertTrue((value == 2018)) - + let adUnit = BannerAdUnit(configId: "47706260-ee91-4cd7-b656-2185aca89f59", size: CGSize(width: 300, height: 250)) - - let sdkConfig = MPMoPubConfiguration(adUnitIdForAppInitialization:"a935eac11acd416f92640411234fbba6") + + let sdkConfig = MPMoPubConfiguration(adUnitIdForAppInitialization: "a935eac11acd416f92640411234fbba6") sdkConfig.globalMediationSettings = [] - MoPub.sharedInstance().initializeSdk(with: sdkConfig){} + MoPub.sharedInstance().initializeSdk(with: sdkConfig) {} let mopubBanner = MPAdView(adUnitId: "a935eac11acd416f92640411234fbba6", size: CGSize(width: 300, height: 250)) - adUnit.fetchDemand(adObject: mopubBanner!){ (ResultCode) in + adUnit.fetchDemand(adObject: mopubBanner!) { (ResultCode) in DispatchQueue.main.async { XCTAssertEqual(8, ResultCode.rawValue) self.loadSuccesfulException?.fulfill() @@ -563,21 +526,20 @@ class PrebidDemoTests: XCTestCase, GADBannerViewDelegate, GADInterstitialDelegat loadSuccesfulException = expectation(description: "\(#function)") waitForExpectations(timeout: timeoutForRequest, handler: nil) } - - func testYOBWith1989() - { + + func testYOBWith1989() { let targeting = Targeting.shared XCTAssertNoThrow(try targeting.setYearOfBirth(yob: 1989)) let value = Targeting.shared.yearOfBirth XCTAssertTrue((value == 1989)) - + let adUnit = BannerAdUnit(configId: "47706260-ee91-4cd7-b656-2185aca89f59", size: CGSize(width: 300, height: 250)) - - let sdkConfig = MPMoPubConfiguration(adUnitIdForAppInitialization:"a935eac11acd416f92640411234fbba6") + + let sdkConfig = MPMoPubConfiguration(adUnitIdForAppInitialization: "a935eac11acd416f92640411234fbba6") sdkConfig.globalMediationSettings = [] - MoPub.sharedInstance().initializeSdk(with: sdkConfig){} + MoPub.sharedInstance().initializeSdk(with: sdkConfig) {} let mopubBanner = MPAdView(adUnitId: "a935eac11acd416f92640411234fbba6", size: CGSize(width: 300, height: 250)) - adUnit.fetchDemand(adObject: mopubBanner!){ (ResultCode) in + adUnit.fetchDemand(adObject: mopubBanner!) { (ResultCode) in //DispatchQueue.main.async { XCTAssertEqual(0, ResultCode.rawValue) self.loadSuccesfulException?.fulfill() @@ -586,9 +548,8 @@ class PrebidDemoTests: XCTestCase, GADBannerViewDelegate, GADInterstitialDelegat loadSuccesfulException = expectation(description: "\(#function)") waitForExpectations(timeout: timeoutForRequest, handler: nil) } - - func testAppNexusKeyValueTargeting() - { + + func testAppNexusKeyValueTargeting() { Prebid.shared.prebidServerHost = PrebidHost.Appnexus Prebid.shared.prebidServerAccountId = "bfa84af2-bd16-4d35-96ad-31c6bb888df0" @@ -597,11 +558,11 @@ class PrebidDemoTests: XCTestCase, GADBannerViewDelegate, GADInterstitialDelegat adUnit.removeUserKeyword(forKey: "pbm_key") adUnit.addUserKeyword(key: "pbm_key", value: "pbm_value1") - let sdkConfig = MPMoPubConfiguration(adUnitIdForAppInitialization:"a935eac11acd416f92640411234fbba6") + let sdkConfig = MPMoPubConfiguration(adUnitIdForAppInitialization: "a935eac11acd416f92640411234fbba6") sdkConfig.globalMediationSettings = [] - MoPub.sharedInstance().initializeSdk(with: sdkConfig){} + MoPub.sharedInstance().initializeSdk(with: sdkConfig) {} let mopubBanner = MPAdView(adUnitId: "a935eac11acd416f92640411234fbba6", size: CGSize(width: 300, height: 250)) - adUnit.fetchDemand(adObject: mopubBanner!){ (ResultCode) in + adUnit.fetchDemand(adObject: mopubBanner!) { (ResultCode) in DispatchQueue.main.async { XCTAssertEqual(0, ResultCode.rawValue) self.loadSuccesfulException?.fulfill() @@ -609,24 +570,23 @@ class PrebidDemoTests: XCTestCase, GADBannerViewDelegate, GADInterstitialDelegat } loadSuccesfulException = expectation(description: "\(#function)") waitForExpectations(timeout: timeoutForRequest, handler: nil) - + } - - func testAppNexusKeyValueTargeting2() - { + + func testAppNexusKeyValueTargeting2() { Prebid.shared.prebidServerHost = PrebidHost.Appnexus Prebid.shared.prebidServerAccountId = "bfa84af2-bd16-4d35-96ad-31c6bb888df0" - + timeoutForRequest = 20.0 let adUnit = BannerAdUnit(configId: "67bac530-9832-4f78-8c94-fbf88ac7bd14", size: CGSize(width: 300, height: 250)) adUnit.removeUserKeyword(forKey: "pbm_key") adUnit.addUserKeyword(key: "pbm_key", value: "pbm_value2") - - let sdkConfig = MPMoPubConfiguration(adUnitIdForAppInitialization:"a935eac11acd416f92640411234fbba6") + + let sdkConfig = MPMoPubConfiguration(adUnitIdForAppInitialization: "a935eac11acd416f92640411234fbba6") sdkConfig.globalMediationSettings = [] - MoPub.sharedInstance().initializeSdk(with: sdkConfig){} + MoPub.sharedInstance().initializeSdk(with: sdkConfig) {} let mopubBanner = MPAdView(adUnitId: "a935eac11acd416f92640411234fbba6", size: CGSize(width: 300, height: 250)) - adUnit.fetchDemand(adObject: mopubBanner!){ (ResultCode) in + adUnit.fetchDemand(adObject: mopubBanner!) { (ResultCode) in DispatchQueue.main.async { XCTAssertEqual(8, ResultCode.rawValue) self.loadSuccesfulException?.fulfill() @@ -634,11 +594,10 @@ class PrebidDemoTests: XCTestCase, GADBannerViewDelegate, GADInterstitialDelegat } loadSuccesfulException = expectation(description: "\(#function)") waitForExpectations(timeout: timeoutForRequest, handler: nil) - + } - - func testDFPCustomKeywords() - { + + func testDFPCustomKeywords() { var fetchCount = 0 timeoutForRequest = 60.0 let bannerUnit = BannerAdUnit(configId: Constants.PBS_CONFIG_ID_300x250_APPNEXUS_DEMAND, size: CGSize(width: 300, height: 250)) @@ -648,20 +607,17 @@ class PrebidDemoTests: XCTestCase, GADBannerViewDelegate, GADInterstitialDelegat dfpBanner.rootViewController = viewController dfpBanner.backgroundColor = .red viewController?.view.addSubview(dfpBanner) - let request:DFPRequest = DFPRequest() - request.customTargeting = ["key1":"value1", "key2":"value2"] as [String : AnyObject] - request.testDevices = [ kGADSimulatorID,"cc7ca766f86b43ab6cdc92bed424069b"] - bannerUnit.fetchDemand(adObject:request) { (ResultCode) in + let request: DFPRequest = DFPRequest() + request.customTargeting = ["key1": "value1", "key2": "value2"] as [String: AnyObject] + request.testDevices = [ kGADSimulatorID, "cc7ca766f86b43ab6cdc92bed424069b"] + bannerUnit.fetchDemand(adObject: request) { (_) in DispatchQueue.main.async { - fetchCount = fetchCount + 1 + fetchCount += 1 XCTAssertNotNil(request.customTargeting) - if fetchCount == 1 - { + if fetchCount == 1 { XCTAssertEqual(request.customTargeting!["key1"] as! String, "value1") XCTAssertEqual(request.customTargeting!["key2"] as! String, "value2") - } - else - { + } else { XCTAssertNotEqual(request.customTargeting!["key1"] as! String, "value1") XCTAssertNotEqual(request.customTargeting!["key2"] as! String, "value2") XCTAssertEqual(request.customTargeting!["key2"] as! String, "value1") @@ -669,37 +625,33 @@ class PrebidDemoTests: XCTestCase, GADBannerViewDelegate, GADInterstitialDelegat XCTAssertEqual(request.customTargeting!["key1"] as! String, "") self.loadSuccesfulException?.fulfill() } - request.customTargeting = ["key1":"", "key2":"value1", "key3":"value3"] as [String : AnyObject] + request.customTargeting = ["key1": "", "key2": "value1", "key3": "value3"] as [String: AnyObject] } } loadSuccesfulException = expectation(description: "\(#function)") waitForExpectations(timeout: timeoutForRequest, handler: nil) } - - func testMoPubCustomKeywords() - { + + func testMoPubCustomKeywords() { var fetchCount = 0 timeoutForRequest = 60.0 let bannerUnit = BannerAdUnit(configId: Constants.PBS_CONFIG_ID_300x250_APPNEXUS_DEMAND, size: CGSize(width: 300, height: 250)) bannerUnit.setAutoRefreshMillis(time: 30000) - let sdkConfig = MPMoPubConfiguration(adUnitIdForAppInitialization:Constants.MOPUB_BANNER_ADUNIT_ID_300x250) + let sdkConfig = MPMoPubConfiguration(adUnitIdForAppInitialization: Constants.MOPUB_BANNER_ADUNIT_ID_300x250) sdkConfig.globalMediationSettings = [] - MoPub.sharedInstance().initializeSdk(with: sdkConfig){} + MoPub.sharedInstance().initializeSdk(with: sdkConfig) {} let mopubBanner = MPAdView(adUnitId: Constants.MOPUB_BANNER_ADUNIT_ID_300x250, size: CGSize(width: 300, height: 250)) mopubBanner?.keywords = "key1:value1,key2:value2" - bannerUnit.fetchDemand(adObject: mopubBanner!){ (ResultCode) in + bannerUnit.fetchDemand(adObject: mopubBanner!) { (_) in DispatchQueue.main.async { - fetchCount = fetchCount + 1 + fetchCount += 1 XCTAssertNotNil(mopubBanner?.keywords) let keywords = mopubBanner?.keywords let keywordsArray = keywords!.components(separatedBy: ",") - if fetchCount == 1 - { + if fetchCount == 1 { XCTAssertTrue(keywordsArray.contains("key1:value1")) XCTAssertTrue(keywordsArray.contains("key2:value2")) - } - else - { + } else { XCTAssertFalse(keywordsArray.contains("key1:value1")) XCTAssertFalse(keywordsArray.contains("key2:value2")) XCTAssertTrue(keywordsArray.contains("key1:value2")) @@ -712,21 +664,20 @@ class PrebidDemoTests: XCTestCase, GADBannerViewDelegate, GADInterstitialDelegat loadSuccesfulException = expectation(description: "\(#function)") waitForExpectations(timeout: timeoutForRequest, handler: nil) } - - func testBannerWith5ValidAnd1InvalidSizes() - { + + func testBannerWith5ValidAnd1InvalidSizes() { timeoutForRequest = 30.0 let bannerUnit = BannerAdUnit(configId: Constants.PBS_CONFIG_ID_300x250_APPNEXUS_DEMAND, size: CGSize(width: 300, height: 250)) - let arraySizes = [CGSize(width: 320, height: 50), CGSize(width: 300, height: 250), CGSize(width: 300, height: 600) , CGSize(width: 320, height: 100), CGSize(width: 320, height: 480), CGSize(width: 0, height: 0)] - bannerUnit.addAdditionalSize(sizes:arraySizes) + let arraySizes = [CGSize(width: 320, height: 50), CGSize(width: 300, height: 250), CGSize(width: 300, height: 600), CGSize(width: 320, height: 100), CGSize(width: 320, height: 480), CGSize(width: 0, height: 0)] + bannerUnit.addAdditionalSize(sizes: arraySizes) let dfpBanner = DFPBannerView(adSize: kGADAdSizeMediumRectangle) dfpBanner.adUnitID = Constants.DFP_BANNER_ADUNIT_ID_300x250 dfpBanner.rootViewController = viewController dfpBanner.backgroundColor = .red viewController?.view.addSubview(dfpBanner) - let request:DFPRequest = DFPRequest() - request.testDevices = [ kGADSimulatorID,"cc7ca766f86b43ab6cdc92bed424069b"] - bannerUnit.fetchDemand(adObject:request) { (ResultCode) in + let request: DFPRequest = DFPRequest() + request.testDevices = [ kGADSimulatorID, "cc7ca766f86b43ab6cdc92bed424069b"] + bannerUnit.fetchDemand(adObject: request) { (ResultCode) in DispatchQueue.main.async { XCTAssertEqual(4, ResultCode.rawValue) self.loadSuccesfulException?.fulfill() @@ -735,21 +686,20 @@ class PrebidDemoTests: XCTestCase, GADBannerViewDelegate, GADInterstitialDelegat loadSuccesfulException = expectation(description: "\(#function)") waitForExpectations(timeout: timeoutForRequest, handler: nil) } - - func testBannerWithInvalidSize() - { + + func testBannerWithInvalidSize() { timeoutForRequest = 30.0 let bannerUnit = BannerAdUnit(configId: Constants.PBS_CONFIG_ID_300x250_APPNEXUS_DEMAND, size: CGSize(width: 320, height: 50)) let arraySizes = [CGSize(width: 0, height: 0)] - bannerUnit.addAdditionalSize(sizes:arraySizes) + bannerUnit.addAdditionalSize(sizes: arraySizes) let dfpBanner = DFPBannerView(adSize: kGADAdSizeMediumRectangle) dfpBanner.adUnitID = Constants.DFP_BANNER_ADUNIT_ID_300x250 dfpBanner.rootViewController = viewController dfpBanner.backgroundColor = .red viewController?.view.addSubview(dfpBanner) - let request:DFPRequest = DFPRequest() - request.testDevices = [ kGADSimulatorID,"cc7ca766f86b43ab6cdc92bed424069b"] - bannerUnit.fetchDemand(adObject:request) { (ResultCode) in + let request: DFPRequest = DFPRequest() + request.testDevices = [ kGADSimulatorID, "cc7ca766f86b43ab6cdc92bed424069b"] + bannerUnit.fetchDemand(adObject: request) { (ResultCode) in DispatchQueue.main.async { XCTAssertEqual(4, ResultCode.rawValue) self.loadSuccesfulException?.fulfill() @@ -758,196 +708,192 @@ class PrebidDemoTests: XCTestCase, GADBannerViewDelegate, GADInterstitialDelegat loadSuccesfulException = expectation(description: "\(#function)") waitForExpectations(timeout: timeoutForRequest, handler: nil) } - - func testMultipleAdUnitsAllDemandFetched() - { + + func testMultipleAdUnitsAllDemandFetched() { var fetchDemandCount = 0 let bannerUnit1 = BannerAdUnit(configId: "7cd2c7c8-cebe-4206-b5a4-97b9e840729e", size: CGSize(width: 320, height: 50)) let sdkConfig1 = MPMoPubConfiguration(adUnitIdForAppInitialization: "9a8c2ccd3dae405bb925397d35eed8f9") sdkConfig1.globalMediationSettings = [] - MoPub.sharedInstance().initializeSdk(with: sdkConfig1){} + MoPub.sharedInstance().initializeSdk(with: sdkConfig1) {} let mopubBanner1 = MPAdView(adUnitId: "9a8c2ccd3dae405bb925397d35eed8f9", size: CGSize(width: 320, height: 50)) mopubBanner1?.delegate = self viewController?.view.addSubview(mopubBanner1!) - bannerUnit1.fetchDemand(adObject: mopubBanner1!){ (ResultCode) in + bannerUnit1.fetchDemand(adObject: mopubBanner1!) { (ResultCode) in DispatchQueue.main.async { XCTAssertEqual(0, ResultCode.rawValue) - fetchDemandCount = fetchDemandCount + 1 + fetchDemandCount += 1 } } - + let bannerUnit2 = BannerAdUnit(configId: "525a5fee-ffbb-4f16-935d-3717c56e7aeb", size: CGSize(width: 320, height: 50)) let sdkConfig2 = MPMoPubConfiguration(adUnitIdForAppInitialization: "50564379db734ebbb347849221a1081e") sdkConfig2.globalMediationSettings = [] - MoPub.sharedInstance().initializeSdk(with: sdkConfig2){} + MoPub.sharedInstance().initializeSdk(with: sdkConfig2) {} let mopubBanner2 = MPAdView(adUnitId: "50564379db734ebbb347849221a1081e", size: CGSize(width: 320, height: 50)) mopubBanner2?.delegate = self viewController?.view.addSubview(mopubBanner2!) - bannerUnit2.fetchDemand(adObject: mopubBanner2!){ (ResultCode) in + bannerUnit2.fetchDemand(adObject: mopubBanner2!) { (ResultCode) in DispatchQueue.main.async { XCTAssertEqual(0, ResultCode.rawValue) - fetchDemandCount = fetchDemandCount + 1 + fetchDemandCount += 1 } } - + let bannerUnit3 = BannerAdUnit(configId: "511c39f2-b527-41af-811a-adac6911bdfc", size: CGSize(width: 300, height: 250)) let sdkConfig3 = MPMoPubConfiguration(adUnitIdForAppInitialization: "5ff9556b05964e65b684ec54013df59d") sdkConfig3.globalMediationSettings = [] - MoPub.sharedInstance().initializeSdk(with: sdkConfig3){} + MoPub.sharedInstance().initializeSdk(with: sdkConfig3) {} let mopubBanner3 = MPAdView(adUnitId: "5ff9556b05964e65b684ec54013df59d", size: CGSize(width: 300, height: 250)) mopubBanner3?.delegate = self viewController?.view.addSubview(mopubBanner3!) - bannerUnit3.fetchDemand(adObject: mopubBanner3!){ (ResultCode) in + bannerUnit3.fetchDemand(adObject: mopubBanner3!) { (ResultCode) in DispatchQueue.main.async { XCTAssertEqual(0, ResultCode.rawValue) - fetchDemandCount = fetchDemandCount + 1 + fetchDemandCount += 1 } } - + let bannerUnit4 = BannerAdUnit(configId: "42ad4418-9b36-4e39-ae54-2f7a13ad8616", size: CGSize(width: 300, height: 250)) let sdkConfig4 = MPMoPubConfiguration(adUnitIdForAppInitialization: "c5c9267bcf6247cb91a116d1ef6c7487") sdkConfig4.globalMediationSettings = [] - MoPub.sharedInstance().initializeSdk(with: sdkConfig4){} + MoPub.sharedInstance().initializeSdk(with: sdkConfig4) {} let mopubBanner4 = MPAdView(adUnitId: "c5c9267bcf6247cb91a116d1ef6c7487", size: CGSize(width: 300, height: 250)) mopubBanner4?.delegate = self viewController?.view.addSubview(mopubBanner4!) - bannerUnit4.fetchDemand(adObject: mopubBanner4!){ (ResultCode) in + bannerUnit4.fetchDemand(adObject: mopubBanner4!) { (ResultCode) in DispatchQueue.main.async { XCTAssertEqual(0, ResultCode.rawValue) - fetchDemandCount = fetchDemandCount + 1 + fetchDemandCount += 1 } } - + let bannerUnit5 = BannerAdUnit(configId: "6ace8c7d-88c0-4623-8117-75bc3f0a2e45", size: CGSize(width: 300, height: 250)) let sdkConfig5 = MPMoPubConfiguration(adUnitIdForAppInitialization: "a935eac11acd416f92640411234fbba6") sdkConfig5.globalMediationSettings = [] - MoPub.sharedInstance().initializeSdk(with: sdkConfig5){} + MoPub.sharedInstance().initializeSdk(with: sdkConfig5) {} let mopubBanner5 = MPAdView(adUnitId: "a935eac11acd416f92640411234fbba6", size: CGSize(width: 300, height: 250)) mopubBanner5?.delegate = self viewController?.view.addSubview(mopubBanner5!) - bannerUnit5.fetchDemand(adObject: mopubBanner5!){ (ResultCode) in + bannerUnit5.fetchDemand(adObject: mopubBanner5!) { (ResultCode) in DispatchQueue.main.async { XCTAssertEqual(0, ResultCode.rawValue) - fetchDemandCount = fetchDemandCount + 1 + fetchDemandCount += 1 } } - + let interstitialUnit6 = InterstitialAdUnit(configId: "625c6125-f19e-4d5b-95c5-55501526b2a4") - let sdkConfig6 = MPMoPubConfiguration(adUnitIdForAppInitialization:"2829868d308643edbec0795977f17437") + let sdkConfig6 = MPMoPubConfiguration(adUnitIdForAppInitialization: "2829868d308643edbec0795977f17437") sdkConfig6.globalMediationSettings = [] - MoPub.sharedInstance().initializeSdk(with: sdkConfig6){} + MoPub.sharedInstance().initializeSdk(with: sdkConfig6) {} let mopubInterstitial6 = MPInterstitialAdController(forAdUnitId: "2829868d308643edbec0795977f17437") - interstitialUnit6.fetchDemand(adObject: mopubInterstitial6!){ (ResultCode) in + interstitialUnit6.fetchDemand(adObject: mopubInterstitial6!) { (ResultCode) in DispatchQueue.main.async { XCTAssertEqual(0, ResultCode.rawValue) - fetchDemandCount = fetchDemandCount + 1 + fetchDemandCount += 1 } } - + let interstitialUnit7 = InterstitialAdUnit(configId: "bde00f49-0a1b-483a-9716-e2dd427b794c") - let sdkConfig7 = MPMoPubConfiguration(adUnitIdForAppInitialization:"c3fca03154a540bfa7f0971fb984e3e8") + let sdkConfig7 = MPMoPubConfiguration(adUnitIdForAppInitialization: "c3fca03154a540bfa7f0971fb984e3e8") sdkConfig7.globalMediationSettings = [] - MoPub.sharedInstance().initializeSdk(with: sdkConfig7){} + MoPub.sharedInstance().initializeSdk(with: sdkConfig7) {} let mopubInterstitial7 = MPInterstitialAdController(forAdUnitId: "c3fca03154a540bfa7f0971fb984e3e8") - interstitialUnit7.fetchDemand(adObject: mopubInterstitial7!){ (ResultCode) in + interstitialUnit7.fetchDemand(adObject: mopubInterstitial7!) { (ResultCode) in DispatchQueue.main.async { XCTAssertEqual(0, ResultCode.rawValue) - fetchDemandCount = fetchDemandCount + 1 + fetchDemandCount += 1 } } - + let interstitialUnit8 = InterstitialAdUnit(configId: "6ceca3d4-f5b8-4717-b4d9-178843f873f8") let sdkConfig8 = MPMoPubConfiguration(adUnitIdForAppInitialization: "12ecf78eb8314f8bb36192a6286adc56") sdkConfig8.globalMediationSettings = [] - MoPub.sharedInstance().initializeSdk(with: sdkConfig8){} + MoPub.sharedInstance().initializeSdk(with: sdkConfig8) {} let mopubInterstitial8 = MPInterstitialAdController(forAdUnitId: "12ecf78eb8314f8bb36192a6286adc56") - interstitialUnit8.fetchDemand(adObject: mopubInterstitial8!){ (ResultCode) in + interstitialUnit8.fetchDemand(adObject: mopubInterstitial8!) { (ResultCode) in DispatchQueue.main.async { XCTAssertEqual(0, ResultCode.rawValue) - fetchDemandCount = fetchDemandCount + 1 + fetchDemandCount += 1 } } - + let interstitialUnit9 = InterstitialAdUnit(configId: Constants.PBS_CONFIG_ID_INTERSTITIAL_APPNEXUS_DEMAND) - let sdkConfig9 = MPMoPubConfiguration(adUnitIdForAppInitialization:Constants.MOPUB_INTERSTITIAL_ADUNIT_ID) + let sdkConfig9 = MPMoPubConfiguration(adUnitIdForAppInitialization: Constants.MOPUB_INTERSTITIAL_ADUNIT_ID) sdkConfig9.globalMediationSettings = [] - MoPub.sharedInstance().initializeSdk(with: sdkConfig9){} + MoPub.sharedInstance().initializeSdk(with: sdkConfig9) {} let mopubInterstitial9 = MPInterstitialAdController(forAdUnitId: Constants.MOPUB_INTERSTITIAL_ADUNIT_ID) - interstitialUnit9.fetchDemand(adObject: mopubInterstitial9!){ (ResultCode) in + interstitialUnit9.fetchDemand(adObject: mopubInterstitial9!) { (ResultCode) in DispatchQueue.main.async { XCTAssertEqual(0, ResultCode.rawValue) - fetchDemandCount = fetchDemandCount + 1 + fetchDemandCount += 1 } } - + let interstitialUnit = InterstitialAdUnit(configId: Constants.PBS_CONFIG_ID_INTERSTITIAL_APPNEXUS_DEMAND) let dfpInterstitial = DFPInterstitial(adUnitID: Constants.DFP_INTERSTITIAL_ADUNIT_ID) - let request:DFPRequest = DFPRequest() + let request: DFPRequest = DFPRequest() dfpInterstitial.delegate = self request.testDevices = [ kGADSimulatorID] - interstitialUnit.fetchDemand(adObject:request) { (ResultCode) in + interstitialUnit.fetchDemand(adObject: request) { (ResultCode) in DispatchQueue.main.async { XCTAssertEqual(0, ResultCode.rawValue) - fetchDemandCount = fetchDemandCount + 1 + fetchDemandCount += 1 } } - + wait(5) XCTAssertEqual(10, fetchDemandCount) } - - func testSameConfigIdOnDifferentAdObjects() - { + + func testSameConfigIdOnDifferentAdObjects() { var fetchDemandCount = 0 let bannerUnit1 = BannerAdUnit(configId: Constants.PBS_CONFIG_ID_300x250_APPNEXUS_DEMAND, size: CGSize(width: 300, height: 250)) let sdkConfig1 = MPMoPubConfiguration(adUnitIdForAppInitialization: Constants.MOPUB_BANNER_ADUNIT_ID_300x250) sdkConfig1.globalMediationSettings = [] - MoPub.sharedInstance().initializeSdk(with: sdkConfig1){} + MoPub.sharedInstance().initializeSdk(with: sdkConfig1) {} let mopubBanner1 = MPAdView(adUnitId: Constants.MOPUB_BANNER_ADUNIT_ID_300x250, size: CGSize(width: 300, height: 250)) mopubBanner1?.delegate = self viewController?.view.addSubview(mopubBanner1!) - bannerUnit1.fetchDemand(adObject: mopubBanner1!){ (ResultCode) in + bannerUnit1.fetchDemand(adObject: mopubBanner1!) { (ResultCode) in DispatchQueue.main.async { XCTAssertEqual(0, ResultCode.rawValue) XCTAssertNotNil(mopubBanner1!.keywords) let keywords = mopubBanner1!.keywords - if let keywordsArray = keywords?.components(separatedBy: ",") - { + if let keywordsArray = keywords?.components(separatedBy: ",") { XCTAssertEqual(10, keywordsArray.count) XCTAssertTrue (keywordsArray.contains("hb_pb:0.50")) XCTAssertTrue (keywords!.contains("hb_cache_id:")) - fetchDemandCount = fetchDemandCount + 1 + fetchDemandCount += 1 } } } - + let bannerUnit2 = BannerAdUnit(configId: Constants.PBS_CONFIG_ID_300x250_APPNEXUS_DEMAND, size: CGSize(width: 300, height: 250)) let sdkConfig2 = MPMoPubConfiguration(adUnitIdForAppInitialization: Constants.MOPUB_BANNER_ADUNIT_ID_300x250) sdkConfig2.globalMediationSettings = [] - MoPub.sharedInstance().initializeSdk(with: sdkConfig2){} + MoPub.sharedInstance().initializeSdk(with: sdkConfig2) {} let mopubBanner2 = MPAdView(adUnitId: Constants.MOPUB_BANNER_ADUNIT_ID_300x250, size: CGSize(width: 300, height: 250)) mopubBanner2?.delegate = self viewController?.view.addSubview(mopubBanner2!) - bannerUnit2.fetchDemand(adObject: mopubBanner2!){ (ResultCode) in + bannerUnit2.fetchDemand(adObject: mopubBanner2!) { (ResultCode) in DispatchQueue.main.async { XCTAssertEqual(0, ResultCode.rawValue) XCTAssertNotNil(mopubBanner2?.keywords) let keywords = mopubBanner2?.keywords - if let keywordsArray = keywords?.components(separatedBy: ",") - { + if let keywordsArray = keywords?.components(separatedBy: ",") { XCTAssertEqual(10, keywordsArray.count) XCTAssertTrue (keywordsArray.contains("hb_pb:0.50")) XCTAssertTrue (keywords!.contains("hb_cache_id:")) - fetchDemandCount = fetchDemandCount + 1 + fetchDemandCount += 1 } } } - + wait(5) XCTAssertEqual(2, fetchDemandCount) } - - //MARK:- DFP delegate + + // MARK: - DFP delegate func adViewDidReceiveAd(_ bannerView: GADBannerView) { print("adViewDidReceiveAd") DispatchQueue.main.asyncAfter(deadline: .now() + 10.0, execute: { @@ -956,25 +902,24 @@ class PrebidDemoTests: XCTestCase, GADBannerViewDelegate, GADInterstitialDelegat self.loadSuccesfulException?.fulfill() }) } - + func adView(_ bannerView: GADBannerView, didFailToReceiveAdWithError error: GADRequestError) { print("adView:didFailToReceiveAdWithError: \(error.localizedDescription)") loadSuccesfulException = nil } - + func interstitialWillPresentScreen(_ ad: GADInterstitial) { print("Ad presented") } - + func interstitialDidDismissScreen(_ ad: GADInterstitial) { // Send another GADRequest here print("Ad dismissed") } - + func interstitialDidReceiveAd(_ ad: GADInterstitial) { - - if(self.dfpInterstitial?.isReady ?? true) - { + + if (self.dfpInterstitial?.isReady ?? true) { print("Ad ready") self.dfpInterstitial?.present(fromRootViewController: viewController!) DispatchQueue.main.asyncAfter(deadline: .now() + 5.0, execute: { @@ -982,16 +927,16 @@ class PrebidDemoTests: XCTestCase, GADBannerViewDelegate, GADInterstitialDelegat XCTAssertTrue(result) self.loadSuccesfulException?.fulfill() }) - }else { - print("Ad not ready"); + } else { + print("Ad not ready") } } - - //MARK:- Mopub delegate + + // MARK: - Mopub delegate func viewControllerForPresentingModalView() -> UIViewController! { return viewController } - + func adViewDidLoadAd(_ view: MPAdView!) { print("adViewDidReceiveAd") PBViewTool.checkMPAdViewContainsPBMAd(view) { (result) in @@ -999,41 +944,39 @@ class PrebidDemoTests: XCTestCase, GADBannerViewDelegate, GADInterstitialDelegat self.loadSuccesfulException?.fulfill() } } - + func adViewDidFail(toLoadAd view: MPAdView!) { print("adViewDidFail") loadSuccesfulException = nil } - + func interstitialDidLoadAd(_ interstitial: MPInterstitialAdController!) { print("Ad ready") - if(self.mopubInterstitial?.ready ?? true){ + if (self.mopubInterstitial?.ready ?? true) { self.mopubInterstitial?.show(from: viewController) } } - + func interstitialDidFail(toLoadAd interstitial: MPInterstitialAdController!) { - print("Ad not ready"); + print("Ad not ready") loadSuccesfulException = nil } - + func interstitialDidAppear(_ interstitial: MPInterstitialAdController!) { print("ad appeared") PBViewTool.checkMPInterstitialContainsPBMAd(self.viewController!.presentedViewController!, withCompletionHandler: { (result) in XCTAssertTrue(result) self.loadSuccesfulException?.fulfill() }) - + } - + func interstitialWillAppear(_ interstitial: MPInterstitialAdController!) { print("ad appeared") } - } - extension XCTestCase { func wait(for element: XCUIElement, timeout: TimeInterval) { let p = NSPredicate(format: "exists == true") // Checks for exists true diff --git a/scripts/swiftLint.sh b/scripts/swiftLint.sh new file mode 100755 index 000000000..647c49db5 --- /dev/null +++ b/scripts/swiftLint.sh @@ -0,0 +1,23 @@ +#!/bin/bash + +# Installs the SwiftLint package. +# Tries to get the precompiled .pkg file from Github, but if that +# fails just recompiles from source. + +set -e + +SWIFTLINT_PKG_PATH="/tmp/SwiftLint.pkg" +SWIFTLINT_PKG_URL="https://github.com/realm/SwiftLint/releases/download/0.31.0/SwiftLint.pkg" + +wget --output-document=$SWIFTLINT_PKG_PATH $SWIFTLINT_PKG_URL + +if [ -f $SWIFTLINT_PKG_PATH ]; then + echo "SwiftLint package exists! Installing it..." + sudo installer -pkg $SWIFTLINT_PKG_PATH -target / +else + echo "SwiftLint package doesn't exist. Compiling from source..." && + git clone https://github.com/realm/SwiftLint.git /tmp/SwiftLint && + cd /tmp/SwiftLint && + git submodule update --init --recursive && + sudo make install +fi \ No newline at end of file diff --git a/scripts/testPrebidMobile.sh b/scripts/testPrebidMobile.sh index 83720cfb6..5847c9954 100755 --- a/scripts/testPrebidMobile.sh +++ b/scripts/testPrebidMobile.sh @@ -8,6 +8,11 @@ echo "Running unit tests" gem install xcpretty xcodebuild test -project PrebidMobile.xcodeproj -scheme "PrebidMobileTests" -destination 'platform=iOS Simulator,name=iPhone 8 Plus,OS=11.0.1' | xcpretty +cd ../src/PrebidMobile/ +echo $PWD +echo "Running swiftlint tests" +swiftlint --config .swiftlint.yml + #echo "Running integration tests" cd ../../example/Swift/PrebidDemo/ echo $PWD diff --git a/src/PrebidMobile/.swiftlint.yml b/src/PrebidMobile/.swiftlint.yml new file mode 100644 index 000000000..499194e16 --- /dev/null +++ b/src/PrebidMobile/.swiftlint.yml @@ -0,0 +1,10 @@ +disabled_rules: # rule identifiers to exclude from running + - force_cast + - force_try + - identifier_name + - control_statement + - nesting + +line_length: 250 +function_body_length: 100 +type_body_length: 100 diff --git a/src/PrebidMobile/PrebidMobile/AdUnits/AdUnit.swift b/src/PrebidMobile/PrebidMobile/AdUnits/AdUnit.swift index b36927732..c635811fd 100644 --- a/src/PrebidMobile/PrebidMobile/AdUnits/AdUnit.swift +++ b/src/PrebidMobile/PrebidMobile/AdUnits/AdUnit.swift @@ -1,11 +1,8 @@ /* Copyright 2018-2019 Prebid.org, Inc. - 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. @@ -16,55 +13,55 @@ import Foundation import ObjectiveC.runtime -@objcMembers public class AdUnit : NSObject, DispatcherDelegate { - +@objcMembers public class AdUnit: NSObject, DispatcherDelegate { + var prebidConfigId: String! = "" - + var adSizes = Array () - - var identifier:String - + + var identifier: String + var dispatcher: Dispatcher? - + private var customKeywords = [String: Array]() - + //This flag is set to check if the refresh needs to be made though the user has not invoked the fetch demand after initialization private var isInitialFetchDemandCallMade: Bool = false - - private var adServerObject:AnyObject? - + + private var adServerObject: AnyObject? + private var closure: (ResultCode) -> Void - + //notification flag set to check if the prebid response is received within the specified time - var didReceiveResponse:Bool! = false - + var didReceiveResponse: Bool! = false + //notification flag set to determine if delegate call needs to be made after timeout delegate is sent - var timeOutSignalSent:Bool! = false - - init(configId:String, size:CGSize) { + var timeOutSignalSent: Bool! = false + + init(configId: String, size: CGSize) { self.closure = {_ in return} prebidConfigId = configId adSizes.append(size) identifier = UUID.init().uuidString super.init() } - - dynamic public func fetchDemand(adObject:AnyObject, completion: @escaping(_ result:ResultCode) -> Void) { - + + dynamic public func fetchDemand(adObject: AnyObject, completion: @escaping(_ result: ResultCode) -> Void) { + Utils.shared.removeHBKeywords(adObject: adObject) - + for size in adSizes { - if(size.width < 0 || size.height < 0){ - completion(ResultCode.prebidInvalidSize) + if (size.width < 0 || size.height < 0) { + completion(ResultCode.prebidInvalidSize) return } } - - if(prebidConfigId.isEmpty || (prebidConfigId.trimmingCharacters(in: CharacterSet.whitespaces)).count == 0){ + + if (prebidConfigId.isEmpty || (prebidConfigId.trimmingCharacters(in: CharacterSet.whitespaces)).count == 0) { completion(ResultCode.prebidInvalidConfigId) return } - if(Prebid.shared.prebidServerAccountId.isEmpty || (Prebid.shared.prebidServerAccountId.trimmingCharacters(in: CharacterSet.whitespaces)).count == 0){ + if (Prebid.shared.prebidServerAccountId.isEmpty || (Prebid.shared.prebidServerAccountId.trimmingCharacters(in: CharacterSet.whitespaces)).count == 0) { completion(ResultCode.prebidInvalidAccountId) return } @@ -78,140 +75,138 @@ import ObjectiveC.runtime timeOutSignalSent = false self.closure = completion adServerObject = adObject - let manager:BidManager = BidManager(adUnit: self) - - manager.requestBidsForAdUnit() { (bidResponse, resultCode) in + let manager: BidManager = BidManager(adUnit: self) + + manager.requestBidsForAdUnit { (bidResponse, resultCode) in self.didReceiveResponse = true - if(bidResponse != nil){ - if(!self.timeOutSignalSent){ - Utils.shared.validateAndAttachKeywords (adObject: adObject, bidResponse: bidResponse!) - completion(resultCode) + if (bidResponse != nil) { + if (!self.timeOutSignalSent) { + Utils.shared.validateAndAttachKeywords (adObject: adObject, bidResponse: bidResponse!) + completion(resultCode) } - + } else { - if(!self.timeOutSignalSent){ + if (!self.timeOutSignalSent) { completion(resultCode) } } } - - DispatchQueue.main.asyncAfter(deadline: .now() + .milliseconds(.PB_Request_Timeout) , execute: { - if(!self.didReceiveResponse){ + + DispatchQueue.main.asyncAfter(deadline: .now() + .milliseconds(.PB_Request_Timeout), execute: { + if (!self.didReceiveResponse) { self.timeOutSignalSent = true completion(ResultCode.prebidDemandTimedOut) - + } }) } - - - - var userKeywords:[String: Array] { + + var userKeywords: [String: [String]] { Log.info("user keywords are \(customKeywords)") return customKeywords } - + /** * This method obtains the user keyword & value user for targeting * if the key already exists the value will be appended to the list. No duplicates will be added */ - public func addUserKeyword(key:String, value:String) { - var existingValues:[String] = [] - if(customKeywords[key] != nil){ + public func addUserKeyword(key: String, value: String) { + var existingValues: [String] = [] + if (customKeywords[key] != nil) { existingValues = customKeywords[key]! } - if(!existingValues.contains(value)){ + if (!existingValues.contains(value)) { existingValues.append(value) customKeywords[key] = existingValues } } - + /** * This method obtains the user keyword & values set for user targeting. * the values if the key already exist will be replaced with the new set of values */ - public func addUserKeywords(key:String, value:Array) { - + public func addUserKeywords(key: String, value: [String]) { + customKeywords[key] = value - + } - + /** * This method allows to remove all the user keywords set for user targeting */ public func clearUserKeywords() { - - if(customKeywords.count > 0 ){ + + if (customKeywords.count > 0 ) { customKeywords.removeAll() } - + } - + /** * This method allows to remove specific user keyword & value set from user targeting */ - public func removeUserKeyword(forKey:String){ - if(customKeywords[forKey] != nil){ + public func removeUserKeyword(forKey: String) { + if (customKeywords[forKey] != nil) { customKeywords.removeValue(forKey: forKey) } } - + /** * This method allows to set the auto refresh period for the demand * * - Parameter time: refresh time interval */ - public func setAutoRefreshMillis(time:Double) { - + public func setAutoRefreshMillis(time: Double) { + stopDispatcher() - + guard time >= .PB_MIN_RefreshTime else { Log.error("auto refresh not set as the refresh time is less than to \(.PB_MIN_RefreshTime as Double) seconds") return } - + initDispatcher(refreshTime: time) - + if isInitialFetchDemandCallMade { - startDispatcher(); + startDispatcher() } } - + /** * This method stops the auto refresh of demand */ - public func stopAutoRefresh(){ + public func stopAutoRefresh() { stopDispatcher() } - - func refreshDemand(){ - if(adServerObject != nil){ - self.fetchDemand(adObject: adServerObject!, completion: self.closure) - } - + + func refreshDemand() { + if (adServerObject != nil) { + self.fetchDemand(adObject: adServerObject!, completion: self.closure) + } + } - + func initDispatcher(refreshTime: Double) { - self.dispatcher = Dispatcher.init(withDelegate:self, autoRefreshMillies: refreshTime) + self.dispatcher = Dispatcher.init(withDelegate: self, autoRefreshMillies: refreshTime) } - + func startDispatcher() { guard let dispatcher = self.dispatcher else { Log.verbose("Dispatcher is nil") return } - + dispatcher.start() } - + func stopDispatcher() { guard let dispatcher = self.dispatcher else { Log.verbose("Dispatcher is nil") return } - + dispatcher.stop() self.dispatcher = nil } - + } diff --git a/src/PrebidMobile/PrebidMobile/AdUnits/BannerAdUnit.swift b/src/PrebidMobile/PrebidMobile/AdUnits/BannerAdUnit.swift index b2bc7d70f..a2884d0d9 100644 --- a/src/PrebidMobile/PrebidMobile/AdUnits/BannerAdUnit.swift +++ b/src/PrebidMobile/PrebidMobile/AdUnits/BannerAdUnit.swift @@ -1,11 +1,11 @@ /* Copyright 2018-2019 Prebid.org, Inc. - + 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. @@ -15,14 +15,14 @@ import Foundation -public class BannerAdUnit : AdUnit { - - public override init(configId:String, size:CGSize) { +public class BannerAdUnit: AdUnit { + + public override init(configId: String, size: CGSize) { super.init(configId: configId, size: size) } - - public func addAdditionalSize(sizes:Array) { + + public func addAdditionalSize(sizes: [CGSize]) { super.adSizes += sizes } - + } diff --git a/src/PrebidMobile/PrebidMobile/AdUnits/InterstitialAdUnit.swift b/src/PrebidMobile/PrebidMobile/AdUnits/InterstitialAdUnit.swift index 9ddf268cf..66b6ae1fe 100644 --- a/src/PrebidMobile/PrebidMobile/AdUnits/InterstitialAdUnit.swift +++ b/src/PrebidMobile/PrebidMobile/AdUnits/InterstitialAdUnit.swift @@ -1,11 +1,11 @@ /* Copyright 2018-2019 Prebid.org, Inc. - + 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. @@ -15,12 +15,10 @@ import Foundation -@objcMembers public class InterstitialAdUnit : AdUnit { - - public init(configId:String) { +@objcMembers public class InterstitialAdUnit: AdUnit { + + public init(configId: String) { super.init(configId: configId, size: CGSize(width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height)) } - - - + } diff --git a/src/PrebidMobile/PrebidMobile/AdUnits/Utils.swift b/src/PrebidMobile/PrebidMobile/AdUnits/Utils.swift index f2fa56dfe..7d71b35f3 100644 --- a/src/PrebidMobile/PrebidMobile/AdUnits/Utils.swift +++ b/src/PrebidMobile/PrebidMobile/AdUnits/Utils.swift @@ -1,11 +1,11 @@ /* Copyright 2018-2019 Prebid.org, Inc. - + 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. @@ -15,134 +15,129 @@ import Foundation -public class Utils : NSObject { - +public class Utils: NSObject { + /** * The class is created as a singleton object & used */ public static let shared = Utils() - + /** * The initializer that needs to be created only once */ private override init() { super.init() - - + } -@objc public func removeHBKeywords (adObject:AnyObject) { - - let adServerObject:String = String(describing: type(of: adObject)) - if(adServerObject == .DFP_O_Object_Name || adServerObject == .DFP_N_Object_Name || adServerObject == .GAD_N_Object_Name){ +@objc public func removeHBKeywords (adObject: AnyObject) { + + let adServerObject: String = String(describing: type(of: adObject)) + if (adServerObject == .DFP_O_Object_Name || adServerObject == .DFP_N_Object_Name || adServerObject == .GAD_N_Object_Name) { let hasDFPMember = adObject.responds(to: NSSelectorFromString("setCustomTargeting:")) - if(hasDFPMember){ + if (hasDFPMember) { //check if the publisher has added any custom targeting. If so then merge the bid keywords to the same. - if(adObject.value(forKey:"customTargeting") != nil){ - var existingDict:[String:Any] = adObject.value(forKey:"customTargeting") as! [String:Any] - for (key,_)in existingDict { - if(key.starts(with:"hb_")){ + if (adObject.value(forKey: "customTargeting") != nil) { + var existingDict: [String: Any] = adObject.value(forKey: "customTargeting") as! [String: Any] + for (key, _)in existingDict { + if (key.starts(with: "hb_")) { existingDict[key] = nil } } - adObject.setValue( existingDict,forKey:"customTargeting") + adObject.setValue( existingDict, forKey: "customTargeting") } } } - - if(adServerObject == .MoPub_Object_Name || adServerObject == .MoPub_Interstitial_Name){ + + if (adServerObject == .MoPub_Object_Name || adServerObject == .MoPub_Interstitial_Name) { let hasMoPubMember = adObject.responds(to: NSSelectorFromString("setKeywords:")) - - if(hasMoPubMember) { + + if (hasMoPubMember) { //for mopub the keywords has to be set as a string seperated by , // split the dictionary & construct a string comma separated - if(adObject.value(forKey:"keywords") != nil){ - let targetingKeywordsString:String = adObject.value(forKey:"keywords") as! String - - let commaString :String = "," - if(targetingKeywordsString != ""){ + if (adObject.value(forKey: "keywords") != nil) { + let targetingKeywordsString: String = adObject.value(forKey: "keywords") as! String + + let commaString: String = "," + if (targetingKeywordsString != "") { var keywordsArray = targetingKeywordsString.components(separatedBy: ",") var i = 0 - var newString:String = "" + var newString: String = "" while i < keywordsArray.count { - if(!keywordsArray[i].starts(with:"hb_")){ - - if( newString == .EMPTY_String){ + if (!keywordsArray[i].starts(with: "hb_")) { + + if ( newString == .EMPTY_String) { newString = keywordsArray[i] } else { - newString = newString + commaString + keywordsArray[i] + newString += commaString + keywordsArray[i] } } - - i = i+1 + + i += 1 } DispatchQueue.main.async { Log.info("MoPub targeting keys are \(newString)") - adObject.setValue( newString,forKey:"keywords") + adObject.setValue( newString, forKey: "keywords") } - + } } - - + } - + } } -@objc func validateAndAttachKeywords (adObject:AnyObject, bidResponse:BidResponse) { - - let adServerObject:String = String(describing: type(of: adObject)) - if(adServerObject == .DFP_O_Object_Name || adServerObject == .DFP_N_Object_Name || adServerObject == .GAD_N_Object_Name){ +@objc func validateAndAttachKeywords (adObject: AnyObject, bidResponse: BidResponse) { + + let adServerObject: String = String(describing: type(of: adObject)) + if (adServerObject == .DFP_O_Object_Name || adServerObject == .DFP_N_Object_Name || adServerObject == .GAD_N_Object_Name) { let hasDFPMember = adObject.responds(to: NSSelectorFromString("setCustomTargeting:")) - if(hasDFPMember){ + if (hasDFPMember) { //check if the publisher has added any custom targeting. If so then merge the bid keywords to the same. - if(adObject.value(forKey:"customTargeting") != nil){ - var existingDict:[String:Any] = adObject.value(forKey:"customTargeting") as! [String:Any] - existingDict.merge(dict:bidResponse.customKeywords) - adObject.setValue( existingDict,forKey:"customTargeting") + if (adObject.value(forKey: "customTargeting") != nil) { + var existingDict: [String: Any] = adObject.value(forKey: "customTargeting") as! [String: Any] + existingDict.merge(dict: bidResponse.customKeywords) + adObject.setValue( existingDict, forKey: "customTargeting") } else { - adObject.setValue( bidResponse.customKeywords,forKey:"customTargeting") + adObject.setValue( bidResponse.customKeywords, forKey: "customTargeting") } - - + return } } - - if(adServerObject == .MoPub_Object_Name || adServerObject == .MoPub_Interstitial_Name){ + + if (adServerObject == .MoPub_Object_Name || adServerObject == .MoPub_Interstitial_Name) { let hasMoPubMember = adObject.responds(to: NSSelectorFromString("setKeywords:")) - - if(hasMoPubMember) { + + if (hasMoPubMember) { //for mopub the keywords has to be set as a string seperated by , // split the dictionary & construct a string comma separated - var targetingKeywordsString:String = "" + var targetingKeywordsString: String = "" //get the publisher set keywords & append the bid keywords to the same - - if let keywordsString = (adObject.value(forKey:"keywords") as? String) { + + if let keywordsString = (adObject.value(forKey: "keywords") as? String) { targetingKeywordsString = keywordsString } - - let commaString :String = "," - - for (key,value) in bidResponse.customKeywords { - if( targetingKeywordsString == .EMPTY_String){ + + let commaString: String = "," + + for (key, value) in bidResponse.customKeywords { + if ( targetingKeywordsString == .EMPTY_String) { targetingKeywordsString = key + ":" + value } else { - targetingKeywordsString = targetingKeywordsString + commaString + key + ":" + value + targetingKeywordsString += commaString + key + ":" + value } - + } Log.info("MoPub targeting keys are \(targetingKeywordsString)") - adObject.setValue( targetingKeywordsString,forKey:"keywords") + adObject.setValue( targetingKeywordsString, forKey: "keywords") - - } - + } - + } } diff --git a/src/PrebidMobile/PrebidMobile/BidManager.swift b/src/PrebidMobile/PrebidMobile/BidManager.swift index ffada57c7..6ca82eb4b 100644 --- a/src/PrebidMobile/PrebidMobile/BidManager.swift +++ b/src/PrebidMobile/PrebidMobile/BidManager.swift @@ -1,11 +1,11 @@ /* Copyright 2018-2019 Prebid.org, Inc. - + 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. @@ -15,92 +15,92 @@ import Foundation -@objcMembers class BidManager:NSObject { - - var prebidAdUnit:AdUnit - - init(adUnit:AdUnit) { - +@objcMembers class BidManager: NSObject { + + var prebidAdUnit: AdUnit + + init(adUnit: AdUnit) { + prebidAdUnit = adUnit super.init() } - + dynamic func requestBidsForAdUnit(callback: @escaping (_ response: BidResponse?, _ result: ResultCode) -> Void) { - + do { - try RequestBuilder.shared.buildPrebidRequest(adUnit: prebidAdUnit){(urlRequest) in + try RequestBuilder.shared.buildPrebidRequest(adUnit: prebidAdUnit) {(urlRequest) in let demandFetchStartTime = self.getCurrentMillis() - URLSession.shared.dataTask(with: urlRequest!) { data, response, error in + URLSession.shared.dataTask(with: urlRequest!) { data, _, error in let demandFetchEndTime = self.getCurrentMillis() guard error == nil else { print("error calling GET on /todos/1") return } - + // make sure we got data - if(data == nil ) { + if (data == nil ) { print("Error: did not receive data") - callback(nil,ResultCode.prebidNetworkError) + callback(nil, ResultCode.prebidNetworkError) } - if(!Prebid.shared.timeoutUpdated) { + if (!Prebid.shared.timeoutUpdated) { let tmax = self.getTmaxRequest(data!) - if(tmax > 0) { + if (tmax > 0) { Prebid.shared.timeoutMillis = min(demandFetchEndTime - demandFetchStartTime + tmax + 200, 2000) Prebid.shared.timeoutUpdated = true } } let processData = self.processBids(data!) - let bidMap:[String:AnyObject] = processData.0 - let result:ResultCode = processData.1 - if(result == ResultCode.prebidDemandFetchSuccess) { + let bidMap: [String: AnyObject] = processData.0 + let result: ResultCode = processData.1 + if (result == ResultCode.prebidDemandFetchSuccess) { let bidResponse = BidResponse(adId: "PrebidMobile", adServerTargeting: bidMap) Log.info("Bid Successful with rounded bid targeting keys are \(bidResponse.customKeywords) for adUnit id is \(bidResponse.adUnitId)") - - DispatchQueue.main.async() { + + DispatchQueue.main.async { callback(bidResponse, ResultCode.prebidDemandFetchSuccess) } } else { callback(nil, result) } - + }.resume() - + } - + } catch let error { print(error.localizedDescription) - callback(nil,ResultCode.prebidServerURLInvalid) + callback(nil, ResultCode.prebidServerURLInvalid) } } - - func processBids(_ data:Data) -> ([String:AnyObject],ResultCode) { - + + func processBids(_ data: Data) -> ([String: AnyObject], ResultCode) { + do { - let errorString:String = String.init(data: data, encoding: .utf8)! + let errorString: String = String.init(data: data, encoding: .utf8)! print(String(format: "Response from server: %@", errorString)) - if(!errorString.contains("Invalid request")){ - let response:[String:AnyObject] = try JSONSerialization.jsonObject(with: data, options: []) as! [String: AnyObject] - - var bidDict:[String:AnyObject] = [:] + if (!errorString.contains("Invalid request")) { + let response: [String: AnyObject] = try JSONSerialization.jsonObject(with: data, options: []) as! [String: AnyObject] + + var bidDict: [String: AnyObject] = [:] var containTopBid = false - - guard response.count > 0 , response["seatbid"] != nil else { return ([:],ResultCode.prebidDemandNoBids)} + + guard response.count > 0, response["seatbid"] != nil else { return ([:], ResultCode.prebidDemandNoBids)} let seatbids = response["seatbid"] as! [AnyObject] for seatbid in seatbids { - var seatbidDict = seatbid as? [String:AnyObject] - guard seatbid is [String : AnyObject] , seatbidDict?["bid"] is [AnyObject] else { break } + var seatbidDict = seatbid as? [String: AnyObject] + guard seatbid is [String: AnyObject], seatbidDict?["bid"] is [AnyObject] else { break } let bids = seatbidDict?["bid"] as! [AnyObject] for bid in bids { var containBid = false - var adServerTargeting:[String:AnyObject]? + var adServerTargeting: [String: AnyObject]? guard bid["ext"] != nil else { break } - let extDict:[String:Any] = bid["ext"] as! [String:Any] + let extDict: [String: Any] = bid["ext"] as! [String: Any] guard extDict["prebid"] != nil else { break } - let prebidDict:[String:Any] = extDict["prebid"] as! [String:Any] - adServerTargeting = prebidDict["targeting"] as? [String:AnyObject] + let prebidDict: [String: Any] = extDict["prebid"] as! [String: Any] + adServerTargeting = prebidDict["targeting"] as? [String: AnyObject] guard adServerTargeting != nil else { break } - for key in adServerTargeting!.keys{ + for key in adServerTargeting!.keys { if (key == "hb_cache_id") { containTopBid = true } @@ -115,39 +115,39 @@ import Foundation } } if (containTopBid && bidDict.count > 0) { - return (bidDict,ResultCode.prebidDemandFetchSuccess) + return (bidDict, ResultCode.prebidDemandFetchSuccess) } else { - return ([:],ResultCode.prebidDemandNoBids) + return ([:], ResultCode.prebidDemandNoBids) } } else { - if(errorString.contains("Stored Imp with ID") || errorString.contains("No stored imp found")){ - return ([:],ResultCode.prebidInvalidConfigId) - } else if(errorString.contains("Stored Request with ID") || errorString.contains("No stored request found")) { - return ([:],ResultCode.prebidInvalidAccountId) - } else if((errorString.contains("Invalid request: Request imp[0].banner.format")) || errorString.contains("Request imp[0].banner.format") || (errorString.contains("Unable to set interstitial size list"))){ - return ([:],ResultCode.prebidInvalidSize) + if (errorString.contains("Stored Imp with ID") || errorString.contains("No stored imp found")) { + return ([:], ResultCode.prebidInvalidConfigId) + } else if (errorString.contains("Stored Request with ID") || errorString.contains("No stored request found")) { + return ([:], ResultCode.prebidInvalidAccountId) + } else if ((errorString.contains("Invalid request: Request imp[0].banner.format")) || errorString.contains("Request imp[0].banner.format") || (errorString.contains("Unable to set interstitial size list"))) { + return ([:], ResultCode.prebidInvalidSize) } else { - return ([:],ResultCode.prebidServerError) + return ([:], ResultCode.prebidServerError) } } - + } catch let error { print(error.localizedDescription) - - return ([:],ResultCode.prebidDemandNoBids) + + return ([:], ResultCode.prebidDemandNoBids) } - + } - + func getCurrentMillis() -> Int { return Int(Date().timeIntervalSince1970 * 1000) } - - func getTmaxRequest(_ data:Data) -> Int { - do{ - let response:[String:AnyObject] = try JSONSerialization.jsonObject(with: data, options: []) as! [String: AnyObject] + + func getTmaxRequest(_ data: Data) -> Int { + do { + let response: [String: AnyObject] = try JSONSerialization.jsonObject(with: data, options: []) as! [String: AnyObject] let ext = response["ext"] as! [String: AnyObject] - if(ext["tmaxrequest"] != nil) { + if (ext["tmaxrequest"] != nil) { return ext["tmaxrequest"] as! Int } } catch let error { diff --git a/src/PrebidMobile/PrebidMobile/BidResponse.swift b/src/PrebidMobile/PrebidMobile/BidResponse.swift index 4a8f02d4f..57ce496df 100644 --- a/src/PrebidMobile/PrebidMobile/BidResponse.swift +++ b/src/PrebidMobile/PrebidMobile/BidResponse.swift @@ -1,11 +1,11 @@ /* Copyright 2018-2019 Prebid.org, Inc. - + 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. @@ -17,13 +17,13 @@ import Foundation private let kDefaultBidExpiryTime: TimeInterval = 270 -class BidResponse:NSObject { - +class BidResponse: NSObject { + /** * the adUnitId is the adUnit identifier that the bid response corresponds to */ private(set) var adUnitId: String = "" - + var myUnitId: String? = "" { didSet { adUnitId = myUnitId! @@ -32,22 +32,22 @@ class BidResponse:NSObject { /** * customKeywords is a dictionary of all the response objects returned by the demand source that can be used in future */ - private(set) var customKeywords: [String : String] = [:] - - private var myCustomKeywords: [String : String] = [:] { + private(set) var customKeywords: [String: String] = [:] + + private var myCustomKeywords: [String: String] = [:] { didSet { customKeywords = myCustomKeywords } } - - init(adId: String, adServerTargeting: [String : AnyObject]) { + + init(adId: String, adServerTargeting: [String: AnyObject]) { super.init() adUnitId = adId - setMyCustomKeywords(newValue: adServerTargeting as! [String:String]) + setMyCustomKeywords(newValue: adServerTargeting as! [String: String]) } - - func setMyCustomKeywords(newValue:[String:String]) { + + func setMyCustomKeywords(newValue: [String: String]) { self.myCustomKeywords = newValue } diff --git a/src/PrebidMobile/PrebidMobile/Constants.swift b/src/PrebidMobile/PrebidMobile/Constants.swift index c4a67c242..6a96b94de 100644 --- a/src/PrebidMobile/PrebidMobile/Constants.swift +++ b/src/PrebidMobile/PrebidMobile/Constants.swift @@ -1,11 +1,11 @@ /* Copyright 2018-2019 Prebid.org, Inc. - + 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. @@ -15,45 +15,43 @@ import Foundation - extension String { public static let PB_GDPR_ConsentString = "kPBGDPRConsentString" - + public static let PB_GDPR_SubjectToConsent = "kPBGdprSubjectToConsent" - + public static let IAB_GDPR_SubjectToConsent = "IABConsent_SubjectToGDPR" - + public static let IAB_GDPR_ConsentString = "IABConsent_ConsentString" - + public static let EMPTY_String = "" - + public static let kIFASentinelValue = "00000000-0000-0000-0000-000000000000" - + public static let DFP_N_Object_Name = "DFPNRequest" - + public static let DFP_O_Object_Name = "DFPORequest" - + public static let GAD_N_Object_Name = "GADNRequest" - + public static let MoPub_Object_Name = "MPAdView" - + public static let MoPub_Interstitial_Name = "MPInterstitialAdController" - - + } extension Double { public static let PB_MIN_RefreshTime = 30000.0 - + } extension Int { - + public static let PB_Request_Timeout = Prebid.shared.timeoutMillis } extension UIDevice { - + var modelName: String { var systemInfo = utsname() uname(&systemInfo) @@ -62,7 +60,7 @@ extension UIDevice { guard let value = element.value as? Int8, value != 0 else { return identifier } return identifier + String(UnicodeScalar(UInt8(value))) } - + switch identifier { case "iPod5,1": return "iPod Touch 5" case "iPod7,1": return "iPod Touch 6" @@ -93,11 +91,11 @@ extension UIDevice { default: return identifier } } - + } extension Dictionary { - mutating func merge(dict: [Key: Value]){ + mutating func merge(dict: [Key: Value]) { for (k, v) in dict { updateValue(v, forKey: k) } @@ -105,12 +103,11 @@ extension Dictionary { } extension Array { - public func toDictionary(with selectKey: (Element) -> Key) -> [Key:Element] { - var dict = [Key:Element]() + public func toDictionary(with selectKey: (Element) -> Key) -> [Key: Element] { + var dict = [Key: Element]() for element in self { dict[selectKey(element)] = element } return dict } } - diff --git a/src/PrebidMobile/PrebidMobile/Dispatcher.swift b/src/PrebidMobile/PrebidMobile/Dispatcher.swift index 1d0a772a3..f82c566dd 100644 --- a/src/PrebidMobile/PrebidMobile/Dispatcher.swift +++ b/src/PrebidMobile/PrebidMobile/Dispatcher.swift @@ -1,11 +1,11 @@ /* Copyright 2018-2019 Prebid.org, Inc. - + 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. @@ -19,50 +19,47 @@ protocol DispatcherDelegate: class { func refreshDemand() } -class Dispatcher:NSObject { - - var timer : Timer? - +class Dispatcher: NSObject { + + var timer: Timer? + var delegate: DispatcherDelegate! - - var repeatInSeconds:Double = 0 - - init(withDelegate:DispatcherDelegate, autoRefreshMillies:Double) { - + + var repeatInSeconds: Double = 0 + + init(withDelegate: DispatcherDelegate, autoRefreshMillies: Double) { + //timer takes values in seconds... repeatInSeconds = autoRefreshMillies/1000 delegate = withDelegate - + super.init() - } - + open func invalidate() { stop() delegate = nil } - + func start() { - + stop() - + self.timer = Timer.scheduledTimer(timeInterval: repeatInSeconds, target: self, selector: #selector(fireTimer), userInfo: nil, repeats: true) - + RunLoop.main.add(self.timer!, forMode: .commonModes) - + } - + func stop() { - if(self.timer != nil){ - self.timer?.invalidate(); - self.timer = nil; + if (self.timer != nil) { + self.timer?.invalidate() + self.timer = nil } } - - @objc func fireTimer(){ + + @objc func fireTimer() { delegate?.refreshDemand() } - - } diff --git a/src/PrebidMobile/PrebidMobile/Global.swift b/src/PrebidMobile/PrebidMobile/Global.swift index a8ae07f8f..d4bcaf50f 100644 --- a/src/PrebidMobile/PrebidMobile/Global.swift +++ b/src/PrebidMobile/PrebidMobile/Global.swift @@ -1,11 +1,11 @@ /* Copyright 2018-2019 Prebid.org, Inc. - + 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. @@ -15,7 +15,7 @@ import Foundation -public enum ErrorCode : Error { +public enum ErrorCode: Error { case prebidServerURLInvalid (String) case yearOfBirthInvalid case invalidSize (CGSize) diff --git a/src/PrebidMobile/PrebidMobile/Host.swift b/src/PrebidMobile/PrebidMobile/Host.swift index 735f5815b..be0712093 100644 --- a/src/PrebidMobile/PrebidMobile/Host.swift +++ b/src/PrebidMobile/PrebidMobile/Host.swift @@ -1,11 +1,11 @@ /* Copyright 2018-2019 Prebid.org, Inc. - + 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. @@ -15,61 +15,61 @@ import Foundation -@objc public enum PrebidHost:Int { +@objc public enum PrebidHost: Int { case Appnexus case Rubicon case Custom - + func name () -> String { switch self { - case .Appnexus: return "https://prebid.adnxs.com/pbs/v1/openrtb2/auction" - case .Rubicon: return "https://prebid-server.rubiconproject.com/openrtb2/auction" - case .Custom: return "" + case .Appnexus: return "https://prebid.adnxs.com/pbs/v1/openrtb2/auction" + case .Rubicon: return "https://prebid-server.rubiconproject.com/openrtb2/auction" + case .Custom: return "" } } } -class Host : NSObject { - - var prebidServerURL:String? = .EMPTY_String - +class Host: NSObject { + + var prebidServerURL: String? = .EMPTY_String + /** * The class is created as a singleton object & used */ public static let shared = Host() - + override init() { - + } - + /** * The CustomHost property holds the URL for the custom prebid adaptor */ - public var setHostURL:String{ + public var setHostURL: String { get { return self.prebidServerURL! } set { - + self.prebidServerURL = newValue - + } } - + /** * This function retrieves the prebid server URL for the selected host */ - func getHostURL(host:PrebidHost) throws -> String{ - if(host == PrebidHost.Custom){ - if(verifyUrl(urlString: self.prebidServerURL) == false){ + func getHostURL(host: PrebidHost) throws -> String { + if (host == PrebidHost.Custom) { + if (verifyUrl(urlString: self.prebidServerURL) == false) { throw ErrorCode.prebidServerURLInvalid(self.prebidServerURL!) } return self.prebidServerURL! } - - return host.name(); + + return host.name() } - + /** * This function verifies if the prebid server URL is in the url format */ @@ -80,10 +80,10 @@ class Host : NSObject { if let url = URL(string: urlString) { // check if your application can open the NSURL instance return UIApplication.shared.canOpenURL(url) - + } } return false } - + } diff --git a/src/PrebidMobile/PrebidMobile/Location.swift b/src/PrebidMobile/PrebidMobile/Location.swift index c975c0415..2e7e70fbb 100644 --- a/src/PrebidMobile/PrebidMobile/Location.swift +++ b/src/PrebidMobile/PrebidMobile/Location.swift @@ -1,11 +1,11 @@ /* Copyright 2018-2019 Prebid.org, Inc. - + 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. @@ -16,17 +16,17 @@ import Foundation import CoreLocation -class Location:NSObject,CLLocationManagerDelegate { - +class Location: NSObject, CLLocationManagerDelegate { + /** * The class is created as a singleton object & used */ public static let shared = Location() - - private var locationManager:CLLocationManager? = nil - - public var location:CLLocation? = nil - + + private var locationManager: CLLocationManager? + + public var location: CLLocation? + /** * The initializer that needs to be created only once */ @@ -38,27 +38,26 @@ class Location:NSObject,CLLocationManagerDelegate { locationManager!.desiredAccuracy = kCLLocationAccuracyKilometer locationManager!.startMonitoringSignificantLocationChanges() } - + func startCapture () { let status = CLLocationManager.authorizationStatus() - if(status == CLAuthorizationStatus.authorizedWhenInUse || status == CLAuthorizationStatus.authorizedAlways ) { + if (status == CLAuthorizationStatus.authorizedWhenInUse || status == CLAuthorizationStatus.authorizedAlways ) { locationManager!.startUpdatingLocation() } - + } - + func stopCapture () { locationManager?.stopUpdatingLocation() - + } - + func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { location = locations.last! } - + func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) { Log.debug("Location cannot be fetched now") } - -} +} diff --git a/src/PrebidMobile/PrebidMobile/Logging.swift b/src/PrebidMobile/PrebidMobile/Logging.swift index 2106cd87e..9b5434ae7 100644 --- a/src/PrebidMobile/PrebidMobile/Logging.swift +++ b/src/PrebidMobile/PrebidMobile/Logging.swift @@ -1,11 +1,11 @@ /* Copyright 2018-2019 Prebid.org, Inc. - + 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. @@ -26,7 +26,6 @@ enum LogEvent: String { case severe = "[🔥]" // severe } - /// Wrapping Swift.print() within DEBUG flag /// /// - Note: *print()* might cause [security vulnerabilities](https://codifiedsecurity.com/mobile-app-security-testing-checklist-ios/) @@ -41,7 +40,7 @@ func print(_ object: Any) { } class Log { - + static var dateFormat = "yyyy-MM-dd hh:mm:ssSSS" static var dateFormatter: DateFormatter { let formatter = DateFormatter() @@ -50,7 +49,7 @@ class Log { formatter.timeZone = TimeZone.current return formatter } - + private static var isLoggingEnabled: Bool { #if DEBUG return true @@ -58,10 +57,9 @@ class Log { return false #endif } - + // MARK: - Loging methods - - + /// Logs error messages on console with prefix [‼️] /// /// - Parameters: @@ -75,7 +73,7 @@ class Log { print("\(Date().toString()) \(LogEvent.error.rawValue)[\(sourceFileName(filePath: filename))]:\(line) \(column) \(funcName) -> \(object)") } } - + /// Logs info messages on console with prefix [ℹ️] /// /// - Parameters: @@ -89,7 +87,7 @@ class Log { print("\(Date().toString()) \(LogEvent.info.rawValue)[\(sourceFileName(filePath: filename))]:\(line) \(column) \(funcName) -> \(object)") } } - + /// Logs debug messages on console with prefix [💬] /// /// - Parameters: @@ -103,7 +101,7 @@ class Log { print("\(Date().toString()) \(LogEvent.debug.rawValue)[\(sourceFileName(filePath: filename))]:\(line) \(column) \(funcName) -> \(object)") } } - + /// Logs messages verbosely on console with prefix [🔬] /// /// - Parameters: @@ -117,7 +115,7 @@ class Log { print("\(Date().toString()) \(LogEvent.verbose.rawValue)[\(sourceFileName(filePath: filename))]:\(line) \(column) \(funcName) -> \(object)") } } - + /// Logs warnings verbosely on console with prefix [⚠️] /// /// - Parameters: @@ -131,7 +129,7 @@ class Log { print("\(Date().toString()) \(LogEvent.warn.rawValue)[\(sourceFileName(filePath: filename))]:\(line) \(column) \(funcName) -> \(object)") } } - + /// Logs severe events on console with prefix [🔥] /// /// - Parameters: @@ -145,8 +143,7 @@ class Log { print("\(Date().toString()) \(LogEvent.severe.rawValue)[\(sourceFileName(filePath: filename))]:\(line) \(column) \(funcName) -> \(object)") } } - - + /// Extract the file name from the file path /// /// - Parameter filePath: Full file path in bundle diff --git a/src/PrebidMobile/PrebidMobile/Prebid.swift b/src/PrebidMobile/PrebidMobile/Prebid.swift index eeac86200..e9c16ce77 100644 --- a/src/PrebidMobile/PrebidMobile/Prebid.swift +++ b/src/PrebidMobile/PrebidMobile/Prebid.swift @@ -1,11 +1,11 @@ /* Copyright 2018-2019 Prebid.org, Inc. - + 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. @@ -15,25 +15,24 @@ import Foundation - -@objcMembers public class Prebid:NSObject { - public var timeoutMillis : Int = 2000 +@objcMembers public class Prebid: NSObject { + public var timeoutMillis: Int = 2000 var timeoutUpdated: Bool = false - - public var prebidServerAccountId : String! = "" + + public var prebidServerAccountId: String! = "" /** * This property is set by the developer when he is willing to share the location for better ad targeting **/ - private var geoLocation:Bool = false - public var shareGeoLocation : Bool { + private var geoLocation: Bool = false + public var shareGeoLocation: Bool { get { return geoLocation } - + set { geoLocation = newValue - if(geoLocation == true){ + if (geoLocation == true) { Location.shared.startCapture() } else { Location.shared.stopCapture() @@ -41,40 +40,38 @@ import Foundation } } - public var prebidServerHost : PrebidHost = PrebidHost.Appnexus{ + public var prebidServerHost: PrebidHost = PrebidHost.Appnexus { didSet { timeoutMillis = 2000 timeoutUpdated = false } } - + /** * The class is created as a singleton object & used */ public static let shared = Prebid() - + /** * The initializer that needs to be created only once */ private override init() { super.init() - if(RequestBuilder.myUserAgent == ""){ - RequestBuilder.UserAgent(){(userAgentString) in + if (RequestBuilder.myUserAgent == "") { + RequestBuilder.UserAgent {(userAgentString) in Log.info(userAgentString) RequestBuilder.myUserAgent = userAgentString } } } - - public func setCustomPrebidServer(url:String) throws { - - if(Host.shared.verifyUrl(urlString: url) == false){ + + public func setCustomPrebidServer(url: String) throws { + + if (Host.shared.verifyUrl(urlString: url) == false) { throw ErrorCode.prebidServerURLInvalid(url) - }else { + } else { prebidServerHost = PrebidHost.Custom Host.shared.setHostURL = url } } } - - diff --git a/src/PrebidMobile/PrebidMobile/Reachability.swift b/src/PrebidMobile/PrebidMobile/Reachability.swift index 571052de9..05402aebe 100644 --- a/src/PrebidMobile/PrebidMobile/Reachability.swift +++ b/src/PrebidMobile/PrebidMobile/Reachability.swift @@ -1,11 +1,11 @@ /* Copyright 2018-2019 Prebid.org, Inc. - + 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. @@ -32,10 +32,10 @@ public extension Notification.Name { } public class Reachability { - - public typealias NetworkReachable = (Reachability) -> () - public typealias NetworkUnreachable = (Reachability) -> () - + + public typealias NetworkReachable = (Reachability) -> Void + public typealias NetworkUnreachable = (Reachability) -> Void + @available(*, unavailable, renamed: "Connection") public enum NetworkStatus: CustomStringConvertible { case notReachable, reachableViaWiFi, reachableViaWWAN @@ -47,7 +47,7 @@ public class Reachability { } } } - + public enum Connection: CustomStringConvertible { case none, wifi, cellular public var description: String { @@ -58,41 +58,41 @@ public class Reachability { } } } - + public var whenReachable: NetworkReachable? public var whenUnreachable: NetworkUnreachable? - + @available(*, deprecated: 4.0, renamed: "allowsCellularConnection") public let reachableOnWWAN: Bool = true - + /// Set to `false` to force Reachability.connection to .none when on cellular connection (default value `true`) public var allowsCellularConnection: Bool - + // The notification center on which "reachability changed" events are being posted public var notificationCenter: NotificationCenter = NotificationCenter.default - + @available(*, deprecated: 4.0, renamed: "connection.description") public var currentReachabilityString: String { return "\(connection)" } - + @available(*, unavailable, renamed: "connection") public var currentReachabilityStatus: Connection { return connection } - + public var connection: Connection { if flags == nil { try? setReachabilityFlags() } - + switch flags?.connection { case .none?, nil: return .none case .cellular?: return allowsCellularConnection ? .cellular : .none case .wifi?: return .wifi } } - + fileprivate var isRunningOnDevice: Bool = { #if targetEnvironment(simulator) return false @@ -100,7 +100,7 @@ public class Reachability { return true #endif }() - + fileprivate var notifierRunning = false fileprivate let reachabilityRef: SCNetworkReachability fileprivate let reachabilitySerialQueue: DispatchQueue @@ -110,88 +110,88 @@ public class Reachability { reachabilityChanged() } } - + required public init(reachabilityRef: SCNetworkReachability, queueQoS: DispatchQoS = .default, targetQueue: DispatchQueue? = nil) { self.allowsCellularConnection = true self.reachabilityRef = reachabilityRef self.reachabilitySerialQueue = DispatchQueue(label: "uk.co.ashleymills.reachability", qos: queueQoS, target: targetQueue) } - + public convenience init?(hostname: String, queueQoS: DispatchQoS = .default, targetQueue: DispatchQueue? = nil) { guard let ref = SCNetworkReachabilityCreateWithName(nil, hostname) else { return nil } self.init(reachabilityRef: ref, queueQoS: queueQoS, targetQueue: targetQueue) } - + public convenience init?(queueQoS: DispatchQoS = .default, targetQueue: DispatchQueue? = nil) { var zeroAddress = sockaddr() zeroAddress.sa_len = UInt8(MemoryLayout.size) zeroAddress.sa_family = sa_family_t(AF_INET) - + guard let ref = SCNetworkReachabilityCreateWithAddress(nil, &zeroAddress) else { return nil } - + self.init(reachabilityRef: ref, queueQoS: queueQoS, targetQueue: targetQueue) } - + deinit { stopNotifier() } } public extension Reachability { - + // MARK: - *** Notifier methods *** func startNotifier() throws { guard !notifierRunning else { return } - + let callback: SCNetworkReachabilityCallBack = { (reachability, flags, info) in guard let info = info else { return } - + let reachability = Unmanaged.fromOpaque(info).takeUnretainedValue() reachability.flags = flags } - + var context = SCNetworkReachabilityContext(version: 0, info: nil, retain: nil, release: nil, copyDescription: nil) context.info = UnsafeMutableRawPointer(Unmanaged.passUnretained(self).toOpaque()) if !SCNetworkReachabilitySetCallback(reachabilityRef, callback, &context) { stopNotifier() throw ReachabilityError.UnableToSetCallback } - + if !SCNetworkReachabilitySetDispatchQueue(reachabilityRef, reachabilitySerialQueue) { stopNotifier() throw ReachabilityError.UnableToSetDispatchQueue } - + // Perform an initial check try setReachabilityFlags() - + notifierRunning = true } - + func stopNotifier() { defer { notifierRunning = false } - + SCNetworkReachabilitySetCallback(reachabilityRef, nil, nil) SCNetworkReachabilitySetDispatchQueue(reachabilityRef, nil) } - + // MARK: - *** Connection test methods *** @available(*, deprecated: 4.0, message: "Please use `connection != .none`") var isReachable: Bool { return connection != .none } - + @available(*, deprecated: 4.0, message: "Please use `connection == .cellular`") var isReachableViaWWAN: Bool { // Check we're not on the simulator, we're REACHABLE and check we're on WWAN return connection == .cellular } - + @available(*, deprecated: 4.0, message: "Please use `connection == .wifi`") var isReachableViaWiFi: Bool { return connection == .wifi } - + var description: String { guard let flags = flags else { return "unavailable flags" } let W = isRunningOnDevice ? (flags.isOnWWANFlagSet ? "W" : "-") : "X" @@ -203,13 +203,13 @@ public extension Reachability { let D = flags.isConnectionOnDemandFlagSet ? "D" : "-" let l = flags.isLocalAddressFlagSet ? "l" : "-" let d = flags.isDirectFlagSet ? "d" : "-" - + return "\(W)\(R) \(c)\(t)\(i)\(C)\(D)\(l)\(d)" } } fileprivate extension Reachability { - + func setReachabilityFlags() throws { try reachabilitySerialQueue.sync { [unowned self] in var flags = SCNetworkReachabilityFlags() @@ -217,14 +217,14 @@ fileprivate extension Reachability { self.stopNotifier() throw ReachabilityError.UnableToGetInitialFlags } - + self.flags = flags } } - + func reachabilityChanged() { let block = connection != .none ? whenReachable : whenUnreachable - + DispatchQueue.main.async { [weak self] in guard let strongSelf = self else { return } block?(strongSelf) @@ -234,36 +234,36 @@ fileprivate extension Reachability { } extension SCNetworkReachabilityFlags { - + typealias Connection = Reachability.Connection - + var connection: Connection { guard isReachableFlagSet else { return .none } - + // If we're reachable, but not on an iOS device (i.e. simulator), we must be on WiFi #if targetEnvironment(simulator) return .wifi #else var connection = Connection.none - + if !isConnectionRequiredFlagSet { connection = .wifi } - + if isConnectionOnTrafficOrDemandFlagSet { if !isInterventionRequiredFlagSet { connection = .wifi } } - + if isOnWWANFlagSet { connection = .cellular } - + return connection #endif } - + var isOnWWANFlagSet: Bool { #if os(iOS) return contains(.isWWAN) diff --git a/src/PrebidMobile/PrebidMobile/RequestBuilder.swift b/src/PrebidMobile/PrebidMobile/RequestBuilder.swift index 9fda63972..4c7a1a316 100644 --- a/src/PrebidMobile/PrebidMobile/RequestBuilder.swift +++ b/src/PrebidMobile/PrebidMobile/RequestBuilder.swift @@ -1,11 +1,11 @@ /* Copyright 2018-2019 Prebid.org, Inc. - + 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. @@ -19,38 +19,38 @@ import CoreLocation import WebKit import AdSupport -@objcMembers public class RequestBuilder:NSObject{ +@objcMembers public class RequestBuilder: NSObject { /** * The class is created as a singleton object & used */ static let shared = RequestBuilder() - - static var myUserAgent:String = "" - + + static var myUserAgent: String = "" + /** * The initializer that needs to be created only once */ private override init() { - + super.init() } - - func buildPrebidRequest(adUnit: AdUnit?,callback:@escaping(_ urlRequest: URLRequest?) throws -> ()) throws { + + func buildPrebidRequest(adUnit: AdUnit?, callback:@escaping(_ urlRequest: URLRequest?) throws -> Void) throws { do { - try callback(self.buildRequest(adUnit:adUnit)) - + try callback(self.buildRequest(adUnit: adUnit)) + } catch let error { throw error } } - + func buildRequest(adUnit: AdUnit?) throws -> URLRequest? { - - let hostUrl:String = try Host.shared.getHostURL(host: Prebid.shared.prebidServerHost) - var request:URLRequest = URLRequest(url: URL(string: hostUrl)!, cachePolicy: .reloadIgnoringLocalCacheData, timeoutInterval: TimeInterval(Prebid.shared.timeoutMillis)) + + let hostUrl: String = try Host.shared.getHostURL(host: Prebid.shared.prebidServerHost) + var request: URLRequest = URLRequest(url: URL(string: hostUrl)!, cachePolicy: .reloadIgnoringLocalCacheData, timeoutInterval: TimeInterval(Prebid.shared.timeoutMillis)) request.httpMethod = "POST" - let requestBody:[String : Any] = openRTBRequestBody(adUnit: adUnit)! - + let requestBody: [String: Any] = openRTBRequestBody(adUnit: adUnit)! + request.httpBody = try JSONSerialization.data(withJSONObject: requestBody, options: .prettyPrinted) // pass dictionary to nsdata object and set it as request body //HTTP HeadersExpression implicitly coerced from '[AnyHashable : Any]?' to Any request.addValue("application/json", forHTTPHeaderField: "Content-Type") @@ -58,10 +58,10 @@ import AdSupport Log.info("Prebid Request post body \(requestBody)") return request } - - func openRTBRequestBody(adUnit: AdUnit?) -> [String : Any]? { - var requestDict: [String : Any] = [:] - + + func openRTBRequestBody(adUnit: AdUnit?) -> [String: Any]? { + var requestDict: [String: Any] = [:] + requestDict["id"] = UUID().uuidString if let aSource = openrtbSource() { requestDict["source"] = aSource @@ -71,28 +71,28 @@ import AdSupport if Targeting.shared.subjectToGDPR == true { requestDict["regs"] = openrtbRegs() } - requestDict["user"] = openrtbUser(adUnit:adUnit) + requestDict["user"] = openrtbUser(adUnit: adUnit) requestDict["imp"] = openrtbImps(adUnit: adUnit) requestDict["ext"] = openrtbRequestExtension() - + return requestDict } - - func openrtbSource() -> [String:Any]? { - + + func openrtbSource() -> [String: Any]? { + let uuid = UUID().uuidString - var sourceDict: [String : Any] = [:] + var sourceDict: [String: Any] = [:] sourceDict["tid"] = uuid - + return sourceDict } - - func openrtbRequestExtension() -> [AnyHashable : Any]? { - var requestPrebidExt: [AnyHashable : Any] = [:] + + func openrtbRequestExtension() -> [AnyHashable: Any]? { + var requestPrebidExt: [AnyHashable: Any] = [:] requestPrebidExt["targeting"] = [:] requestPrebidExt["storedrequest"] = ["id": Prebid.shared.prebidServerAccountId] - requestPrebidExt["cache"] = ["bids": [AnyHashable : Any]()] - var requestExt: [AnyHashable : Any] = [:] + requestPrebidExt["cache"] = ["bids": [AnyHashable: Any]()] + var requestExt: [AnyHashable: Any] = [:] requestExt["prebid"] = requestPrebidExt return requestExt } @@ -100,35 +100,35 @@ import AdSupport func openrtbImps(adUnit: AdUnit?) -> [Any]! { var imps: [Any] = [] - var imp: [AnyHashable : Any] = [:] + var imp: [AnyHashable: Any] = [:] if let anIdentifier = adUnit?.identifier { imp["id"] = anIdentifier } imp["secure"] = 1 - var sizeArray = [[String:CGFloat]]() + var sizeArray = [[String: CGFloat]]() for size: CGSize in (adUnit?.adSizes)! { let sizeDict = [ - "w" : size.width, - "h" : size.height + "w": size.width, + "h": size.height ] sizeArray.append(sizeDict) } let formats = ["format": sizeArray] imp["banner"] = formats - - if(adUnit is InterstitialAdUnit){ + + if (adUnit is InterstitialAdUnit) { imp["instl"] = 1 } //to be used when openRTB supports storedRequests - var prebidAdUnitExt: [AnyHashable : Any] = [:] + var prebidAdUnitExt: [AnyHashable: Any] = [:] if let anId = adUnit?.prebidConfigId { prebidAdUnitExt["storedrequest"] = ["id": anId] } - var adUnitExt: [AnyHashable : Any] = [:] + var adUnitExt: [AnyHashable: Any] = [:] adUnitExt["prebid"] = prebidAdUnitExt imp["ext"] = adUnitExt @@ -137,13 +137,13 @@ import AdSupport return imps } - + // OpenRTB 2.5 Object: App in section 3.2.14 - - func openrtbApp() -> [AnyHashable : Any]? { - var app: [AnyHashable : Any] = [:] - - let itunesID:String? = Targeting.shared.itunesID + + func openrtbApp() -> [AnyHashable: Any]? { + var app: [AnyHashable: Any] = [:] + + let itunesID: String? = Targeting.shared.itunesID let bundle = Bundle.main.bundleIdentifier if itunesID != nil { app["bundle"] = itunesID @@ -151,28 +151,27 @@ import AdSupport app["bundle"] = bundle ?? "" } - let version:String = Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String ?? "" + let version: String = Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String ?? "" if version != "" { app["ver"] = version } - + app["publisher"] = ["id": Prebid.shared.prebidServerAccountId ?? 0] as NSDictionary app["ext"] = ["prebid": ["version": String(PrebidMobileVersionNumber), "source": "prebid-mobile"]] - + return app } - + // OpenRTB 2.5 Object: Device in section 3.2.18 - - func openrtbDevice() -> [AnyHashable : Any]? { - var deviceDict: [AnyHashable : Any] = [:] - - if(RequestBuilder.myUserAgent != ""){ + + func openrtbDevice() -> [AnyHashable: Any]? { + var deviceDict: [AnyHashable: Any] = [:] + + if (RequestBuilder.myUserAgent != "") { deviceDict["ua"] = RequestBuilder.myUserAgent } - - deviceDict["geo"] = openrtbGeo() + deviceDict["geo"] = openrtbGeo() deviceDict["make"] = "Apple" deviceDict["os"] = "iOS" @@ -190,23 +189,23 @@ import AdSupport if (carrier?.carrierName?.count ?? 0) > 0 { deviceDict["carrier"] = carrier?.carrierName ?? "" } - - let reachability:Reachability = Reachability()! - var connectionType:Int = 0 - if (reachability.connection == .wifi){ + + let reachability: Reachability = Reachability()! + var connectionType: Int = 0 + if (reachability.connection == .wifi) { connectionType = 1 - }else if(reachability.connection == .cellular){ + } else if (reachability.connection == .cellular) { connectionType = 2 } - + deviceDict["connectiontype"] = connectionType if (carrier?.mobileCountryCode?.count ?? 0) > 0 && (carrier?.mobileNetworkCode?.count ?? 0) > 0 { deviceDict["mccmnc"] = carrier?.mobileCountryCode ?? "" + ("-") + (carrier?.mobileNetworkCode ?? "") } - let lmtAd:Bool = !ASIdentifierManager.shared().isAdvertisingTrackingEnabled + let lmtAd: Bool = !ASIdentifierManager.shared().isAdvertisingTrackingEnabled // Limit ad tracking - deviceDict["lmt"] = NSNumber(value:lmtAd).intValue + deviceDict["lmt"] = NSNumber(value: lmtAd).intValue let deviceId = RequestBuilder.DeviceUUID() if deviceId != "" { @@ -218,18 +217,18 @@ import AdSupport let pixelRatio: CGFloat = UIScreen.main.scale - deviceDict["pxratio"] = pixelRatio; + deviceDict["pxratio"] = pixelRatio - return deviceDict; + return deviceDict } // OpenRTB 2.5 Object: Geo in section 3.2.19 - func openrtbGeo() -> [AnyHashable : Any]? { - + func openrtbGeo() -> [AnyHashable: Any]? { + if Location.shared.location != nil { - var geoDict: [AnyHashable : Any] = [:] + var geoDict: [AnyHashable: Any] = [:] let latitude = Location.shared.location?.coordinate.latitude let longitude = Location.shared.location?.coordinate.longitude @@ -248,21 +247,21 @@ import AdSupport return nil } - func openrtbRegs() -> [AnyHashable : Any]? { + func openrtbRegs() -> [AnyHashable: Any]? { + + var regsDict: [AnyHashable: Any] = [:] - var regsDict: [AnyHashable : Any] = [:] + let gdpr: Bool? = Targeting.shared.subjectToGDPR - let gdpr:Bool? = Targeting.shared.subjectToGDPR - - if(gdpr != nil){ + if (gdpr != nil) { regsDict["ext"] = ["gdpr": NSNumber(value: gdpr!).intValue] as NSDictionary } return regsDict } // OpenRTB 2.5 Object: User in section 3.2.20 - func openrtbUser(adUnit: AdUnit?) -> [AnyHashable : Any]? { - var userDict: [AnyHashable : Any] = [:] + func openrtbUser(adUnit: AdUnit?) -> [AnyHashable: Any]? { + var userDict: [AnyHashable: Any] = [:] let yob = Targeting.shared.yearOfBirth if yob > 0 { @@ -281,12 +280,12 @@ import AdSupport } userDict["gender"] = gender - let targetingParams = adUnit?.userKeywords + let targetingUserParams = adUnit?.userKeywords - let keywordString = fetchKeywordsString(targetingParams) + let userKeywordString = fetchKeywordsString(targetingUserParams) - if !(keywordString == "") { - userDict["keywords"] = keywordString + if !(userKeywordString == "") { + userDict["keywords"] = userKeywordString } if Targeting.shared.subjectToGDPR == true { @@ -310,19 +309,19 @@ import AdSupport return precisionNumberFormatter } - func fetchKeywordsString(_ kewordsDictionary: [AnyHashable : Any]?) -> String? { + func fetchKeywordsString(_ kewordsDictionary: [AnyHashable: Any]?) -> String? { var keywordString = "" - for (key,dictValues) in (kewordsDictionary)! { + for (key, dictValues) in (kewordsDictionary)! { let values = dictValues as? [String?] - - for value in values! { + + for value in values! { let keyvalue = "\(key)=\(value!)" - if(keywordString != ""){ + if (keywordString != "") { keywordString = "\(keywordString),\(keyvalue)" } else { keywordString = keyvalue @@ -332,43 +331,43 @@ import AdSupport return keywordString } - + class func UserAgent(callback:@escaping(_ userAgentString: String) -> Void) { - - var wkUserAgent:String = "" + + var wkUserAgent: String = "" let myGroup = DispatchGroup() - + let window = UIApplication.shared.keyWindow - let webView = WKWebView(frame:UIScreen.main.bounds) + let webView = WKWebView(frame: UIScreen.main.bounds) webView.isHidden = true window?.addSubview(webView) myGroup.enter() webView.loadHTMLString("", baseURL: nil) - webView.evaluateJavaScript("navigator.userAgent", completionHandler: { (userAgent, error) in + webView.evaluateJavaScript("navigator.userAgent", completionHandler: { (userAgent, _) in wkUserAgent = userAgent as! String webView.stopLoading() webView.removeFromSuperview() myGroup.leave() - + }) myGroup.notify(queue: .main) { callback(wkUserAgent) } - + } - + class func DeviceUUID() -> String { - var uuidString:String = "" - - if(uuidString == ""){ - let advertisingIdentifier:String = ASIdentifierManager.shared().advertisingIdentifier.uuidString - - if(advertisingIdentifier != .kIFASentinelValue){ + var uuidString: String = "" + + if (uuidString == "") { + let advertisingIdentifier: String = ASIdentifierManager.shared().advertisingIdentifier.uuidString + + if (advertisingIdentifier != .kIFASentinelValue) { uuidString = advertisingIdentifier } } - + return uuidString } - + } diff --git a/src/PrebidMobile/PrebidMobile/ResultCode.swift b/src/PrebidMobile/PrebidMobile/ResultCode.swift index 64b43f762..edb0623e6 100644 --- a/src/PrebidMobile/PrebidMobile/ResultCode.swift +++ b/src/PrebidMobile/PrebidMobile/ResultCode.swift @@ -1,11 +1,11 @@ /* Copyright 2018-2019 Prebid.org, Inc. - + 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. @@ -15,7 +15,7 @@ import Foundation -@objc public enum ResultCode : Int { +@objc public enum ResultCode: Int { case prebidDemandFetchSuccess case prebidServerNotSpecified case prebidInvalidAccountId @@ -26,7 +26,7 @@ import Foundation case prebidServerError case prebidDemandNoBids case prebidDemandTimedOut - + public func name () -> String { switch self { case .prebidDemandFetchSuccess: return "Prebid Demand Fetch Successful" @@ -39,7 +39,7 @@ import Foundation case .prebidServerError: return "Prebid Server Error" case .prebidDemandNoBids: return "Prebid Server did not return bids" case .prebidDemandTimedOut: return "Prebid demand timedout" - + } } } diff --git a/src/PrebidMobile/PrebidMobile/Targeting.swift b/src/PrebidMobile/PrebidMobile/Targeting.swift index b1339bc5c..8a270e932 100644 --- a/src/PrebidMobile/PrebidMobile/Targeting.swift +++ b/src/PrebidMobile/PrebidMobile/Targeting.swift @@ -1,11 +1,11 @@ /* Copyright 2018-2019 Prebid.org, Inc. - + 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. @@ -16,119 +16,118 @@ import Foundation import CoreLocation -@objc public enum Gender:Int { +@objc public enum Gender: Int { case unknown case male case female } -@objcMembers public class Targeting :NSObject { - - private var yearofbirth:Int = 0; - +@objcMembers public class Targeting: NSObject { + + private var yearofbirth: Int = 0 + /** * This property gets the gender enum passed set by the developer */ - - public var gender:Gender - + + public var gender: Gender + public var yearOfBirth: Int { return yearofbirth } - + /** * This property gets the year of birth value set by the application developer */ - public func setYearOfBirth(yob:Int) throws { + public func setYearOfBirth(yob: Int) throws { let date = Date() let calendar = Calendar.current - + let year = calendar.component(.year, from: date) - - if(yob <= 1900 || yob >= year){ + + if (yob <= 1900 || yob >= year) { throw ErrorCode.yearOfBirthInvalid } else { yearofbirth = yob } } - + /** * This property clears year of birth value set by the application developer */ - public func clearYearOfBirth() { + public func clearYearOfBirth() { yearofbirth = 0 } - + /** * The itunes app id for targeting */ - public var itunesID:String? - + public var itunesID: String? + /** * The application location for targeting */ - public var location:CLLocation? - + public var location: CLLocation? + /** * The application location precision for targeting */ - public var locationPrecision:Int? - + public var locationPrecision: Int? + /** * The boolean value set by the user to collect user data */ - public var subjectToGDPR:Bool { + public var subjectToGDPR: Bool { set { UserDefaults.standard.set(newValue, forKey: .PB_GDPR_SubjectToConsent) } - + get { - var gdprConsent:Bool = false - - if((UserDefaults.standard.object(forKey: .PB_GDPR_SubjectToConsent)) != nil){ + var gdprConsent: Bool = false + + if ((UserDefaults.standard.object(forKey: .PB_GDPR_SubjectToConsent)) != nil) { gdprConsent = UserDefaults.standard.bool(forKey: .PB_GDPR_SubjectToConsent) - } else if((UserDefaults.standard.object(forKey: .IAB_GDPR_SubjectToConsent)) != nil){ - let stringValue :String = UserDefaults.standard.object(forKey: .IAB_GDPR_SubjectToConsent) as! String - + } else if ((UserDefaults.standard.object(forKey: .IAB_GDPR_SubjectToConsent)) != nil) { + let stringValue: String = UserDefaults.standard.object(forKey: .IAB_GDPR_SubjectToConsent) as! String + gdprConsent = Bool(stringValue)! } - return gdprConsent; + return gdprConsent } } - + /** * The consent string for sending the GDPR consent */ - public var gdprConsentString:String? { + public var gdprConsentString: String? { set { UserDefaults.standard.set(newValue, forKey: .PB_GDPR_ConsentString) } - + get { - let pbString:String? = UserDefaults.standard.object(forKey: .PB_GDPR_ConsentString) as? String - let iabString:String? = UserDefaults.standard.object(forKey: .IAB_GDPR_ConsentString) as? String - - var savedConsent :String? - if(pbString != nil){ + let pbString: String? = UserDefaults.standard.object(forKey: .PB_GDPR_ConsentString) as? String + let iabString: String? = UserDefaults.standard.object(forKey: .IAB_GDPR_ConsentString) as? String + + var savedConsent: String? + if (pbString != nil) { savedConsent = pbString - } else if(iabString != nil){ + } else if (iabString != nil) { savedConsent = iabString } return savedConsent } } - + /** * The class is created as a singleton object & used */ public static let shared = Targeting() - + /** * The initializer that needs to be created only once */ private override init() { gender = Gender.unknown } - - + } diff --git a/src/PrebidMobile/PrebidMobileTests/AdUnitTests/AdUnitTests.swift b/src/PrebidMobile/PrebidMobileTests/AdUnitTests/AdUnitTests.swift index 482f41930..05f4b2802 100644 --- a/src/PrebidMobile/PrebidMobileTests/AdUnitTests/AdUnitTests.swift +++ b/src/PrebidMobile/PrebidMobileTests/AdUnitTests/AdUnitTests.swift @@ -1,11 +1,11 @@ /* Copyright 2018-2019 Prebid.org, Inc. - + 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. @@ -29,50 +29,50 @@ class AdUnitTests: XCTestCase { } func testFetchDemandSuccess() { - let adUnit:AdUnit = AdUnit.shared + let adUnit: AdUnit = AdUnit.shared adUnit.testScenario = ResultCode.prebidDemandFetchSuccess - let testObject:AnyObject = () as AnyObject - + let testObject: AnyObject = () as AnyObject + adUnit.fetchDemand(adObject: testObject) { (ResultCode) in XCTAssertEqual(ResultCode.name(), "Prebid Demand Fetch Successful") } } - + func testFetchDemandNoBid() { - let adUnit:AdUnit = AdUnit.shared + let adUnit: AdUnit = AdUnit.shared adUnit.testScenario = ResultCode.prebidDemandNoBids - let testObject:AnyObject = () as AnyObject - + let testObject: AnyObject = () as AnyObject + adUnit.fetchDemand(adObject: testObject) { (ResultCode) in XCTAssertEqual(ResultCode.name(), "Prebid Server did not return bids") } } - + func testFetchDemandNetworkError() { - let adUnit:AdUnit = AdUnit.shared + let adUnit: AdUnit = AdUnit.shared adUnit.testScenario = ResultCode.prebidNetworkError - let testObject:AnyObject = () as AnyObject - + let testObject: AnyObject = () as AnyObject + adUnit.fetchDemand(adObject: testObject) { (ResultCode) in XCTAssertEqual(ResultCode.name(), "Network Error") } } - + func testFetchDemandTimedOut() { - let adUnit:AdUnit = AdUnit.shared + let adUnit: AdUnit = AdUnit.shared adUnit.testScenario = ResultCode.prebidDemandTimedOut - let testObject:AnyObject = () as AnyObject - + let testObject: AnyObject = () as AnyObject + adUnit.fetchDemand(adObject: testObject) { (ResultCode) in XCTAssertEqual(ResultCode.name(), "Prebid demand timedout") } } - + func testInvalidSize() { - let adUnit:AdUnit = AdUnit.shared + let adUnit: AdUnit = AdUnit.shared adUnit.testScenario = ResultCode.prebidInvalidSize - let testObject:AnyObject = () as AnyObject - + let testObject: AnyObject = () as AnyObject + adUnit.fetchDemand(adObject: testObject) { (ResultCode) in XCTAssertEqual(ResultCode.name(), "Prebid server does not recognize the size requested") } diff --git a/src/PrebidMobile/PrebidMobileTests/AdUnitTests/BannerAdUnitTests.swift b/src/PrebidMobile/PrebidMobileTests/AdUnitTests/BannerAdUnitTests.swift index f10a9a7e7..0765de304 100644 --- a/src/PrebidMobile/PrebidMobileTests/AdUnitTests/BannerAdUnitTests.swift +++ b/src/PrebidMobile/PrebidMobileTests/AdUnitTests/BannerAdUnitTests.swift @@ -1,11 +1,11 @@ /* Copyright 2018-2019 Prebid.org, Inc. - + 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. @@ -17,43 +17,38 @@ import XCTest @testable import PrebidMobile class BannerAdUnitTests: XCTestCase { - + override func setUp() { // Put setup code here. This method is called before the invocation of each test method in the class. } - + override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. } - - func testBannerAdUnitCreation() - { + + func testBannerAdUnitCreation() { let adUnit = BannerAdUnit(configId: Constants.configID1, size: CGSize(width: Constants.width2, height: Constants.height2)) XCTAssertTrue(1 == adUnit.adSizes.count) XCTAssertTrue(adUnit.prebidConfigId == Constants.configID1) XCTAssertNil(adUnit.dispatcher) } - - func testBannerAdUnitAddSize() - { + + func testBannerAdUnitAddSize() { let adUnit = BannerAdUnit(configId: Constants.configID1, size: CGSize(width: Constants.width1, height: Constants.height1)) adUnit.adSizes = [CGSize(width: Constants.width1, height: Constants.height1), CGSize(width: Constants.width2, height: Constants.height2)] XCTAssertNotNil(adUnit.adSizes) XCTAssertTrue(2 == adUnit.adSizes.count) } - - func testSetUserKeyword() - { + + func testSetUserKeyword() { let adUnit = BannerAdUnit(configId: Constants.configID1, size: CGSize(width: Constants.width1, height: Constants.height1)) adUnit.addUserKeyword(key: "key1", value: "value1") adUnit.addUserKeyword(key: "key2", value: "value2") XCTAssertTrue(2 == adUnit.userKeywords.count) - if let value = adUnit.userKeywords["key1"]?[0] - { + if let value = adUnit.userKeywords["key1"]?[0] { XCTAssertEqual("value1", value) } - if let value = adUnit.userKeywords["key2"]?[0] - { + if let value = adUnit.userKeywords["key2"]?[0] { XCTAssertEqual("value2", value) } adUnit.removeUserKeyword(forKey: "key1") @@ -63,33 +58,27 @@ class BannerAdUnitTests: XCTestCase { XCTAssertTrue(0 == adUnit.userKeywords.count) XCTAssertNil(adUnit.userKeywords["key2"]) } - - func testSetUserKeywords() - { + + func testSetUserKeywords() { let adUnit = BannerAdUnit(configId: Constants.configID1, size: CGSize(width: Constants.width1, height: Constants.height1)) adUnit.addUserKeyword(key: "key1", value: "value1") let arrValues = ["value1", "value2"] adUnit.addUserKeywords(key: "key2", value: arrValues) XCTAssertTrue(2 == adUnit.userKeywords.count) - if let value = adUnit.userKeywords["key1"]?[0] - { + if let value = adUnit.userKeywords["key1"]?[0] { XCTAssertEqual("value1", value) } - if let value = adUnit.userKeywords["key2"]?[0] - { + if let value = adUnit.userKeywords["key2"]?[0] { XCTAssertEqual("value1", value) } - if let value = adUnit.userKeywords["key2"]?[1] - { + if let value = adUnit.userKeywords["key2"]?[1] { XCTAssertEqual("value2", value) } adUnit.addUserKeywords(key: "key1", value: arrValues) - if let value = adUnit.userKeywords["key1"]?[0] - { + if let value = adUnit.userKeywords["key1"]?[0] { XCTAssertEqual("value1", value) } - if let value = adUnit.userKeywords["key1"]?[1] - { + if let value = adUnit.userKeywords["key1"]?[1] { XCTAssertEqual("value2", value) } XCTAssertTrue(2 == adUnit.userKeywords.count) @@ -100,4 +89,3 @@ class BannerAdUnitTests: XCTestCase { } } - diff --git a/src/PrebidMobile/PrebidMobileTests/AdUnitTests/Constants.swift b/src/PrebidMobile/PrebidMobileTests/AdUnitTests/Constants.swift index 7e494ffc7..50f25175d 100644 --- a/src/PrebidMobile/PrebidMobileTests/AdUnitTests/Constants.swift +++ b/src/PrebidMobile/PrebidMobileTests/AdUnitTests/Constants.swift @@ -1,11 +1,11 @@ /* Copyright 2018-2019 Prebid.org, Inc. - + 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. @@ -14,7 +14,7 @@ */ struct Constants { - + static let configID1 = "6ace8c7d-88c0-4623-8117-75bc3f0a2e45" static let configID2 = "0c286d00-b3ee-4550-b15d-f71f8e746865" static let configID3 = "35f1d17d-c99a-4d55-800e-062b80750d65" @@ -24,7 +24,7 @@ struct Constants { static let APNPlacementId_1 = 1111 static let APNPlacementId_2 = 2222 static let APNPlacementId_3 = 3333 - static let accountId = "bfa84af2-bd16-4d35-96ad-31c6bb888df0"; + static let accountId = "bfa84af2-bd16-4d35-96ad-31c6bb888df0" static let width1 = 320 static let height1 = 50 static let width2 = 300 diff --git a/src/PrebidMobile/PrebidMobileTests/AdUnitTests/ExAdUnit.swift b/src/PrebidMobile/PrebidMobileTests/AdUnitTests/ExAdUnit.swift index 2bc0cd0ee..fe4c81197 100644 --- a/src/PrebidMobile/PrebidMobileTests/AdUnitTests/ExAdUnit.swift +++ b/src/PrebidMobile/PrebidMobileTests/AdUnitTests/ExAdUnit.swift @@ -1,11 +1,11 @@ /* Copyright 2018-2019 Prebid.org, Inc. - + 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. @@ -17,10 +17,10 @@ import Foundation @testable import PrebidMobile public extension AdUnit { - - private static var _myComputedProperty:ResultCode = .prebidDemandFetchSuccess - - var testScenario:ResultCode { + + private static var _myComputedProperty: ResultCode = .prebidDemandFetchSuccess + + var testScenario: ResultCode { get { return AdUnit._myComputedProperty } @@ -28,43 +28,40 @@ public extension AdUnit { AdUnit._myComputedProperty = newValue } } - - func mock_fetchDemandSuccess(adObject:AnyObject, completion: @escaping(_ result:ResultCode) -> Void) { - - if(AdUnit._myComputedProperty == ResultCode.prebidDemandFetchSuccess){ + + func mock_fetchDemandSuccess(adObject: AnyObject, completion: @escaping(_ result: ResultCode) -> Void) { + + if (AdUnit._myComputedProperty == ResultCode.prebidDemandFetchSuccess) { completion(ResultCode.prebidDemandFetchSuccess) - } else if(AdUnit._myComputedProperty == ResultCode.prebidDemandNoBids){ + } else if (AdUnit._myComputedProperty == ResultCode.prebidDemandNoBids) { completion(ResultCode.prebidDemandNoBids) - } else if(AdUnit._myComputedProperty == ResultCode.prebidDemandTimedOut){ + } else if (AdUnit._myComputedProperty == ResultCode.prebidDemandTimedOut) { completion(ResultCode.prebidDemandTimedOut) - }else if(AdUnit._myComputedProperty == ResultCode.prebidNetworkError){ + } else if (AdUnit._myComputedProperty == ResultCode.prebidNetworkError) { completion(ResultCode.prebidNetworkError) } } - - static let shared : AdUnit = { + + static let shared: AdUnit = { $0.initialize() return $0 }(AdUnit(configId: "138c4d03-0efb-4498-9dc6-cb5a9acb2ea4", size: CGSize(width: 300, height: 250))) - - //In Objective-C you'd perform the swizzling in load() , but this method is not permitted in Swift - func initialize() - { + func initialize() { // Perform this one time only struct Inner { static let i: () = { let originalSelector = #selector(AdUnit.fetchDemand(adObject:completion:)) let swizzledSelector = #selector(AdUnit.mock_fetchDemandSuccess(adObject:completion:)) - + let originalMethod = class_getInstanceMethod(AdUnit.self, originalSelector) let swizzledMethod = class_getInstanceMethod(AdUnit.self, swizzledSelector) - + method_exchangeImplementations(originalMethod!, swizzledMethod!) }() } - let _ = Inner.i + _ = Inner.i } } diff --git a/src/PrebidMobile/PrebidMobileTests/AdUnitTests/InterstItialAdUnitTests.swift b/src/PrebidMobile/PrebidMobileTests/AdUnitTests/InterstItialAdUnitTests.swift index 50e5b1a76..1ba005fc9 100644 --- a/src/PrebidMobile/PrebidMobileTests/AdUnitTests/InterstItialAdUnitTests.swift +++ b/src/PrebidMobile/PrebidMobileTests/AdUnitTests/InterstItialAdUnitTests.swift @@ -1,11 +1,11 @@ /* Copyright 2018-2019 Prebid.org, Inc. - + 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. @@ -26,25 +26,21 @@ class InterstItialAdUnitTests: XCTestCase { // Put teardown code here. This method is called after the invocation of each test method in the class. } - func testInterstitialAdUnitCreation() - { + func testInterstitialAdUnitCreation() { let adUnit = InterstitialAdUnit(configId: Constants.configID1) XCTAssertTrue(adUnit.prebidConfigId == Constants.configID1) XCTAssertNil(adUnit.dispatcher) } - func testSetUserKeyword() - { + func testSetUserKeyword() { let adUnit = InterstitialAdUnit(configId: Constants.configID1) adUnit.addUserKeyword(key: "key1", value: "value1") adUnit.addUserKeyword(key: "key2", value: "value2") XCTAssertTrue(2 == adUnit.userKeywords.count) - if let value = adUnit.userKeywords["key1"]?[0] - { + if let value = adUnit.userKeywords["key1"]?[0] { XCTAssertEqual("value1", value) } - if let value = adUnit.userKeywords["key2"]?[0] - { + if let value = adUnit.userKeywords["key2"]?[0] { XCTAssertEqual("value2", value) } adUnit.removeUserKeyword(forKey: "key1") @@ -54,33 +50,27 @@ class InterstItialAdUnitTests: XCTestCase { XCTAssertTrue(0 == adUnit.userKeywords.count) XCTAssertNil(adUnit.userKeywords["key2"]) } - - func testSetUserKeywords() - { + + func testSetUserKeywords() { let adUnit = InterstitialAdUnit(configId: Constants.configID1) adUnit.addUserKeyword(key: "key1", value: "value1") let arrValues = ["value1", "value2"] adUnit.addUserKeywords(key: "key2", value: arrValues) XCTAssertTrue(2 == adUnit.userKeywords.count) - if let value = adUnit.userKeywords["key1"]?[0] - { + if let value = adUnit.userKeywords["key1"]?[0] { XCTAssertEqual("value1", value) } - if let value = adUnit.userKeywords["key2"]?[0] - { + if let value = adUnit.userKeywords["key2"]?[0] { XCTAssertEqual("value1", value) } - if let value = adUnit.userKeywords["key2"]?[1] - { + if let value = adUnit.userKeywords["key2"]?[1] { XCTAssertEqual("value2", value) } adUnit.addUserKeywords(key: "key1", value: arrValues) - if let value = adUnit.userKeywords["key1"]?[0] - { + if let value = adUnit.userKeywords["key1"]?[0] { XCTAssertEqual("value1", value) } - if let value = adUnit.userKeywords["key1"]?[1] - { + if let value = adUnit.userKeywords["key1"]?[1] { XCTAssertEqual("value2", value) } XCTAssertTrue(2 == adUnit.userKeywords.count) @@ -89,4 +79,5 @@ class InterstItialAdUnitTests: XCTestCase { XCTAssertNil(adUnit.userKeywords["key1"]) XCTAssertNil(adUnit.userKeywords["key2"]) } + } diff --git a/src/PrebidMobile/PrebidMobileTests/FetchingLogictests/BidManagerTests.swift b/src/PrebidMobile/PrebidMobileTests/FetchingLogictests/BidManagerTests.swift index 7883f2786..a7dcf3c74 100644 --- a/src/PrebidMobile/PrebidMobileTests/FetchingLogictests/BidManagerTests.swift +++ b/src/PrebidMobile/PrebidMobileTests/FetchingLogictests/BidManagerTests.swift @@ -1,11 +1,11 @@ /* Copyright 2018-2019 Prebid.org, Inc. - + 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. @@ -19,12 +19,16 @@ import XCTest //@testable import MoPub class BidManagerTests: XCTestCase { - + var request: URLRequest! - var jsonRequestBody = [String : Any]() + var jsonRequestBody = [String: Any]() var loadAdSuccesfulException: XCTestExpectation? var timeoutForImpbusRequest: TimeInterval = 0.0 - + + deinit { + NotificationCenter.default.removeObserver(self) + } + override func setUp() { // Put setup code here. This method is called before the invocation of each test method in the class. timeoutForImpbusRequest = 10.0 @@ -41,26 +45,25 @@ class BidManagerTests: XCTestCase { PBHTTPStubbingManager.shared().removeAllStubs() PBHTTPStubbingManager.shared().broadcastRequests = false loadAdSuccesfulException = nil - NotificationCenter.default.removeObserver(self) } // MARK: - Test methods. func testBidManagerAdUnitRequest() { stubRequestWithResponse("responsePBM") let bannerUnit = BannerAdUnit(configId: "6ace8c7d-88c0-4623-8117-75bc3f0a2e45", size: CGSize(width: 300, height: 250)) - let manager:BidManager = BidManager(adUnit: bannerUnit) - manager.requestBidsForAdUnit() { (bidResponse, resultCode) in + let manager: BidManager = BidManager(adUnit: bannerUnit) + manager.requestBidsForAdUnit { (_, _) in self.loadAdSuccesfulException?.fulfill() } loadAdSuccesfulException = expectation(description: "\(#function)") waitForExpectations(timeout: timeoutForImpbusRequest, handler: nil) } - + func testBidManagerRequestForInvaidBidResponseNoCacheId() { stubRequestWithResponse("responseInvalidResponseWithoutCacheId") let bannerUnit = BannerAdUnit(configId: "6ace8c7d-88c0-4623-8117-75bc3f0a2e45", size: CGSize(width: 300, height: 250)) - let manager:BidManager = BidManager(adUnit: bannerUnit) - manager.requestBidsForAdUnit() { (bidResponse, resultCode) in + let manager: BidManager = BidManager(adUnit: bannerUnit) + manager.requestBidsForAdUnit { (bidResponse, resultCode) in XCTAssertNil(bidResponse) XCTAssertEqual(resultCode, ResultCode.prebidDemandNoBids) self.loadAdSuccesfulException?.fulfill() @@ -68,12 +71,12 @@ class BidManagerTests: XCTestCase { loadAdSuccesfulException = expectation(description: "\(#function)") waitForExpectations(timeout: timeoutForImpbusRequest, handler: nil) } - - func testBidManagerRequestForBidResponseFromTwoBidders(){ + + func testBidManagerRequestForBidResponseFromTwoBidders() { stubRequestWithResponse("PrebidServerOneBidFromAppNexusOneBidFromRubicon") let bannerUnit = BannerAdUnit(configId: "6ace8c7d-88c0-4623-8117-75bc3f0a2e45", size: CGSize(width: 300, height: 250)) - let manager:BidManager = BidManager(adUnit: bannerUnit) - manager.requestBidsForAdUnit() { (bidResponse, resultCode) in + let manager: BidManager = BidManager(adUnit: bannerUnit) + manager.requestBidsForAdUnit { (bidResponse, resultCode) in XCTAssertEqual(resultCode, ResultCode.prebidDemandFetchSuccess) XCTAssertNotNil(bidResponse) let keywords = bidResponse?.customKeywords @@ -83,12 +86,12 @@ class BidManagerTests: XCTestCase { loadAdSuccesfulException = expectation(description: "\(#function)") waitForExpectations(timeout: timeoutForImpbusRequest, handler: nil) } - - func testBidManagerRequestForBidResponseOneSeatHasCacheIdAnotherSeatDoesNot(){ + + func testBidManagerRequestForBidResponseOneSeatHasCacheIdAnotherSeatDoesNot() { stubRequestWithResponse("PrebidServerValidResponseAppNexusNoCacheIdAndRunbiconHasCacheId") let bannerUnit = BannerAdUnit(configId: "6ace8c7d-88c0-4623-8117-75bc3f0a2e45", size: CGSize(width: 300, height: 250)) - let manager:BidManager = BidManager(adUnit: bannerUnit) - manager.requestBidsForAdUnit() { (bidResponse, resultCode) in + let manager: BidManager = BidManager(adUnit: bannerUnit) + manager.requestBidsForAdUnit { (bidResponse, resultCode) in XCTAssertEqual(resultCode, ResultCode.prebidDemandFetchSuccess) XCTAssertNotNil(bidResponse) let keywords = bidResponse?.customKeywords @@ -97,14 +100,14 @@ class BidManagerTests: XCTestCase { } loadAdSuccesfulException = expectation(description: "\(#function)") waitForExpectations(timeout: timeoutForImpbusRequest, handler: nil) - + } - - func testBidManagerRequestForBidResponeTwoBidsOnTheSameSeat(){ + + func testBidManagerRequestForBidResponeTwoBidsOnTheSameSeat() { stubRequestWithResponse("responseValidTwoBidsOnTheSameSeat") let bannerUnit = BannerAdUnit(configId: "6ace8c7d-88c0-4623-8117-75bc3f0a2e45", size: CGSize(width: 300, height: 250)) - let manager:BidManager = BidManager(adUnit: bannerUnit) - manager.requestBidsForAdUnit() { (bidResponse, resultCode) in + let manager: BidManager = BidManager(adUnit: bannerUnit) + manager.requestBidsForAdUnit { (bidResponse, resultCode) in XCTAssertEqual(resultCode, ResultCode.prebidDemandFetchSuccess) XCTAssertNotNil(bidResponse) let keywords = bidResponse?.customKeywords @@ -113,14 +116,14 @@ class BidManagerTests: XCTestCase { } loadAdSuccesfulException = expectation(description: "\(#function)") waitForExpectations(timeout: timeoutForImpbusRequest, handler: nil) - + } - - func testBidManagerRequestForBidResponseTopBidNoCacheId(){ + + func testBidManagerRequestForBidResponseTopBidNoCacheId() { stubRequestWithResponse("responseInvalidNoTopCacheId") let bannerUnit = BannerAdUnit(configId: "6ace8c7d-88c0-4623-8117-75bc3f0a2e45", size: CGSize(width: 300, height: 250)) - let manager:BidManager = BidManager(adUnit: bannerUnit) - manager.requestBidsForAdUnit() { (bidResponse, resultCode) in + let manager: BidManager = BidManager(adUnit: bannerUnit) + manager.requestBidsForAdUnit { (bidResponse, resultCode) in XCTAssertEqual(resultCode, ResultCode.prebidDemandNoBids) XCTAssertNil(bidResponse) self.loadAdSuccesfulException?.fulfill() @@ -128,25 +131,25 @@ class BidManagerTests: XCTestCase { loadAdSuccesfulException = expectation(description: "\(#function)") waitForExpectations(timeout: timeoutForImpbusRequest, handler: nil) } - + func testBidManagerRequestForNoBidResponse() { stubRequestWithResponse("noBidResponse") let bannerUnit = BannerAdUnit(configId: "6ace8c7d-88c0-4623-8117-75bc3f0a2e45", size: CGSize(width: 300, height: 250)) - let manager:BidManager = BidManager(adUnit: bannerUnit) - manager.requestBidsForAdUnit() { (bidResponse, resultCode) in + let manager: BidManager = BidManager(adUnit: bannerUnit) + manager.requestBidsForAdUnit { (bidResponse, _) in XCTAssertNil(bidResponse) self.loadAdSuccesfulException?.fulfill() - } + } loadAdSuccesfulException = expectation(description: "\(#function)") waitForExpectations(timeout: timeoutForImpbusRequest, handler: nil) } - + func testBidManagerRequestForSuccessfulBidResponse() { stubRequestWithResponse("responsePBM") let bannerUnit = BannerAdUnit(configId: "6ace8c7d-88c0-4623-8117-75bc3f0a2e45", size: CGSize(width: 300, height: 250)) - let manager:BidManager = BidManager(adUnit: bannerUnit) - manager.requestBidsForAdUnit() { (bidResponse, resultCode) in - if(bidResponse != nil){ + let manager: BidManager = BidManager(adUnit: bannerUnit) + manager.requestBidsForAdUnit { (bidResponse, _) in + if (bidResponse != nil) { XCTAssertEqual("appnexus", bidResponse?.customKeywords["hb_bidder"]) XCTAssertEqual("appnexus", bidResponse?.customKeywords["hb_bidder_appnexus"]) XCTAssertEqual("7008d51d-af2a-4357-acea-1cb672ac2189", bidResponse?.customKeywords["hb_cache_id"]) @@ -165,14 +168,14 @@ class BidManagerTests: XCTestCase { loadAdSuccesfulException = expectation(description: "\(#function)") waitForExpectations(timeout: timeoutForImpbusRequest, handler: nil) } - + func testBidManagerRequestForInvalidAccountId() { stubRequestWithResponse("responseInvalidAccountId") let bannerUnit = BannerAdUnit(configId: "6ace8c7d-88c0-4623-8117-75bc3f0a2e45", size: CGSize(width: 300, height: 250)) - let manager:BidManager = BidManager(adUnit: bannerUnit) - manager.requestBidsForAdUnit() { (bidResponse, resultCode) in + let manager: BidManager = BidManager(adUnit: bannerUnit) + manager.requestBidsForAdUnit { (bidResponse, resultCode) in XCTAssertNil(bidResponse) - XCTAssertEqual(ResultCode.prebidInvalidAccountId, resultCode) + XCTAssertEqual(ResultCode.prebidInvalidAccountId, resultCode) self.loadAdSuccesfulException?.fulfill() } loadAdSuccesfulException = expectation(description: "\(#function)") @@ -182,33 +185,33 @@ class BidManagerTests: XCTestCase { func testBidManagerRequestForInvalidConfigId() { stubRequestWithResponse("responseInvalidConfigId") let bannerUnit = BannerAdUnit(configId: "6ace8c7d-88c0-4623-8117-75bc3f0a2e45", size: CGSize(width: 300, height: 250)) - let manager:BidManager = BidManager(adUnit: bannerUnit) - manager.requestBidsForAdUnit() { (bidResponse, resultCode) in + let manager: BidManager = BidManager(adUnit: bannerUnit) + manager.requestBidsForAdUnit { (bidResponse, resultCode) in XCTAssertNil(bidResponse) - XCTAssertEqual(ResultCode.prebidInvalidConfigId, resultCode) + XCTAssertEqual(ResultCode.prebidInvalidConfigId, resultCode) self.loadAdSuccesfulException?.fulfill() } loadAdSuccesfulException = expectation(description: "\(#function)") waitForExpectations(timeout: timeoutForImpbusRequest, handler: nil) } - + func testBidManagerRequestForInvalidSizeId() { stubRequestWithResponse("responseinvalidSize") let bannerUnit = BannerAdUnit(configId: "6ace8c7d-88c0-4623-8117-75bc3f0a2e45", size: CGSize(width: 0, height: 250)) - let manager:BidManager = BidManager(adUnit: bannerUnit) - manager.requestBidsForAdUnit() { (bidResponse, resultCode) in + let manager: BidManager = BidManager(adUnit: bannerUnit) + manager.requestBidsForAdUnit { (bidResponse, _) in XCTAssertNil(bidResponse) self.loadAdSuccesfulException?.fulfill() } loadAdSuccesfulException = expectation(description: "\(#function)") waitForExpectations(timeout: timeoutForImpbusRequest, handler: nil) } - + func testBidManagerRequestForIncorrectFormatOfConfigIdOrAccountId() { stubRequestWithResponse("responseIncorrectFormat") let bannerUnit = BannerAdUnit(configId: "6ace8c7d-88c0-4623-8117-75bc3f0a2e45", size: CGSize(width: 300, height: 250)) - let manager:BidManager = BidManager(adUnit: bannerUnit) - manager.requestBidsForAdUnit() { (bidResponse, resultCode) in + let manager: BidManager = BidManager(adUnit: bannerUnit) + manager.requestBidsForAdUnit { (bidResponse, resultCode) in XCTAssertNil(bidResponse) XCTAssertEqual(ResultCode.prebidServerError, resultCode) self.loadAdSuccesfulException?.fulfill() @@ -216,17 +219,17 @@ class BidManagerTests: XCTestCase { loadAdSuccesfulException = expectation(description: "\(#function)") waitForExpectations(timeout: timeoutForImpbusRequest, handler: nil) } - + func requestCompleted(_ notification: Notification?) { var incomingRequest = notification?.userInfo![kPBHTTPStubURLProtocolRequest] as? URLRequest let requestString = incomingRequest?.url?.absoluteString let searchString = Constants.utAdRequestBaseUrl - if request == nil && requestString?.range(of:searchString) != nil { + if request == nil && requestString?.range(of: searchString) != nil { request = notification!.userInfo![kPBHTTPStubURLProtocolRequest] as? URLRequest - jsonRequestBody = PBHTTPStubbingManager.jsonBodyOfURLRequest(asDictionary: request) as! [String : Any] + jsonRequestBody = PBHTTPStubbingManager.jsonBodyOfURLRequest(asDictionary: request) as! [String: Any] } } - + // MARK: - Stubbing func stubRequestWithResponse(_ responseName: String?) { let currentBundle = Bundle(for: type(of: self)) @@ -237,73 +240,73 @@ class BidManagerTests: XCTestCase { requestStub.responseBody = baseResponse PBHTTPStubbingManager.shared().add(requestStub) } - - func testTimeoutMillisUpdate(){ + + func testTimeoutMillisUpdate() { let loadAdSuccesfulException = expectation(description: "\(#function)") stubRequestWithResponse("noBidResponse") Prebid.shared.prebidServerHost = PrebidHost.Appnexus XCTAssertTrue(!Prebid.shared.timeoutUpdated) XCTAssertTrue(Prebid.shared.timeoutMillis == 2000) let bannerUnit = BannerAdUnit(configId: "6ace8c7d-88c0-4623-8117-75bc3f0a2e45", size: CGSize(width: 300, height: 250)) - let manager:BidManager = BidManager(adUnit: bannerUnit) - manager.requestBidsForAdUnit() { (bidResponse, resultCode) in + let manager: BidManager = BidManager(adUnit: bannerUnit) + manager.requestBidsForAdUnit { (_, _) in XCTAssertTrue(Prebid.shared.timeoutUpdated) XCTAssertTrue(Prebid.shared.timeoutMillis > 700 && Prebid.shared.timeoutMillis < 800) loadAdSuccesfulException.fulfill() } - + waitForExpectations(timeout: 10.0, handler: nil) } - - func testTimeoutMillisUpdate2(){ + + func testTimeoutMillisUpdate2() { let loadAdSuccesfulException = expectation(description: "\(#function)") stubRequestWithResponse("noBidResponseNoTmax") Prebid.shared.prebidServerHost = PrebidHost.Appnexus XCTAssertTrue(!Prebid.shared.timeoutUpdated) XCTAssertTrue(Prebid.shared.timeoutMillis == 2000) let bannerUnit = BannerAdUnit(configId: "6ace8c7d-88c0-4623-8117-75bc3f0a2e45", size: CGSize(width: 300, height: 250)) - let manager:BidManager = BidManager(adUnit: bannerUnit) - manager.requestBidsForAdUnit() { (bidResponse, resultCode) in + let manager: BidManager = BidManager(adUnit: bannerUnit) + manager.requestBidsForAdUnit { (_, _) in XCTAssertTrue(!Prebid.shared.timeoutUpdated) XCTAssertTrue(Prebid.shared.timeoutMillis == 2000) loadAdSuccesfulException.fulfill() } - + waitForExpectations(timeout: 10.0, handler: nil) } - - func testTimeoutMillisUpdate3(){ + + func testTimeoutMillisUpdate3() { let loadAdSuccesfulException = expectation(description: "\(#function)") stubRequestWithResponse("noBidResponseTmaxTooLarge") Prebid.shared.prebidServerHost = PrebidHost.Appnexus XCTAssertTrue(!Prebid.shared.timeoutUpdated) XCTAssertTrue(Prebid.shared.timeoutMillis == 2000) let bannerUnit = BannerAdUnit(configId: "6ace8c7d-88c0-4623-8117-75bc3f0a2e45", size: CGSize(width: 300, height: 250)) - let manager:BidManager = BidManager(adUnit: bannerUnit) - manager.requestBidsForAdUnit() { (bidResponse, resultCode) in + let manager: BidManager = BidManager(adUnit: bannerUnit) + manager.requestBidsForAdUnit { (_, _) in XCTAssertTrue(Prebid.shared.timeoutUpdated) XCTAssertTrue(Prebid.shared.timeoutMillis == 2000) loadAdSuccesfulException.fulfill() } - + waitForExpectations(timeout: 10.0, handler: nil) } - - func testTimeoutMillisUpdate4(){ + + func testTimeoutMillisUpdate4() { let loadAdSuccesfulException = expectation(description: "\(#function)") stubRequestWithResponse("noBidResponseNoTmaxEdite") Prebid.shared.prebidServerHost = PrebidHost.Appnexus - Prebid.shared.timeoutMillis = 1000; + Prebid.shared.timeoutMillis = 1000 XCTAssertTrue(!Prebid.shared.timeoutUpdated) XCTAssertTrue(Prebid.shared.timeoutMillis == 1000) let bannerUnit = BannerAdUnit(configId: "6ace8c7d-88c0-4623-8117-75bc3f0a2e45", size: CGSize(width: 300, height: 250)) - let manager:BidManager = BidManager(adUnit: bannerUnit) - manager.requestBidsForAdUnit() { (bidResponse, resultCode) in + let manager: BidManager = BidManager(adUnit: bannerUnit) + manager.requestBidsForAdUnit { (_, _) in XCTAssertTrue(!Prebid.shared.timeoutUpdated) XCTAssertTrue(Prebid.shared.timeoutMillis == 1000) loadAdSuccesfulException.fulfill() } - + waitForExpectations(timeout: 10.0, handler: nil) } } diff --git a/src/PrebidMobile/PrebidMobileTests/FetchingLogictests/CLLocationManager+Swizzle.swift b/src/PrebidMobile/PrebidMobileTests/FetchingLogictests/CLLocationManager+Swizzle.swift index b25bef263..782541851 100644 --- a/src/PrebidMobile/PrebidMobileTests/FetchingLogictests/CLLocationManager+Swizzle.swift +++ b/src/PrebidMobile/PrebidMobileTests/FetchingLogictests/CLLocationManager+Swizzle.swift @@ -1,11 +1,11 @@ /* Copyright 2018-2019 Prebid.org, Inc. - + 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. @@ -16,8 +16,7 @@ import Foundation import MapKit - -private let swizzling: (AnyClass, Selector, Selector) -> () = { forClass, originalSelector, swizzledSelector in +private let swizzling: (AnyClass, Selector, Selector) -> Void = { forClass, originalSelector, swizzledSelector in if let originalMethod = class_getInstanceMethod(forClass, originalSelector), let swizzledMethod = class_getInstanceMethod(forClass, swizzledSelector) { method_exchangeImplementations(originalMethod, swizzledMethod) @@ -29,12 +28,12 @@ extension CLLocationManager { let originalSelector = #selector(CLLocationManager.startUpdatingLocation) let swizzledSelector = #selector(swizzledStartLocation) swizzling(CLLocationManager.self, originalSelector, swizzledSelector) - + let originalStopSelector = #selector(CLLocationManager.stopUpdatingLocation) let swizzledStopSelector = #selector(swizzledStopLocation) swizzling(CLLocationManager.self, originalStopSelector, swizzledStopSelector) }() - + @objc func swizzledStartLocation() { print("swizzled start location") if !MockCLLocationManager.shared.isRunning { @@ -43,12 +42,12 @@ extension CLLocationManager { MockCLLocationManager.shared.delegate = self.delegate MockCLLocationManager.shared.startUpdatingLocation() } - + @objc func swizzledStopLocation() { print("swizzled stop location") MockCLLocationManager.shared.stopUpdatingLocation() } - + @objc func swizzedRequestLocation() { print("swizzled request location") MockCLLocationManager.shared.requestLocation() diff --git a/src/PrebidMobile/PrebidMobileTests/FetchingLogictests/DispatcherTests.swift b/src/PrebidMobile/PrebidMobileTests/FetchingLogictests/DispatcherTests.swift index bd56a9b3b..6189dc6de 100644 --- a/src/PrebidMobile/PrebidMobileTests/FetchingLogictests/DispatcherTests.swift +++ b/src/PrebidMobile/PrebidMobileTests/FetchingLogictests/DispatcherTests.swift @@ -1,11 +1,11 @@ /* Copyright 2018-2019 Prebid.org, Inc. - + 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. @@ -20,7 +20,7 @@ class DispatcherTests: XCTestCase, DispatcherDelegate { var loadSuccesfulException: XCTestExpectation? var timeoutForRequest: TimeInterval = 0.0 - + override func setUp() { // Put setup code here. This method is called before the invocation of each test method in the class. timeoutForRequest = 10.0 @@ -31,15 +31,13 @@ class DispatcherTests: XCTestCase, DispatcherDelegate { loadSuccesfulException = nil } - func testDispatcherIsNotNil() - { + func testDispatcherIsNotNil() { let dispatcher = Dispatcher(withDelegate: self, autoRefreshMillies: 0.0) XCTAssertNotNil(dispatcher) XCTAssertNil(dispatcher.timer) } - - func testStartDispatcherWithRefreshMiliseconds() - { + + func testStartDispatcherWithRefreshMiliseconds() { let dispatcher = Dispatcher(withDelegate: self, autoRefreshMillies: 10.0) dispatcher.start() XCTAssertNotNil(dispatcher.timer) @@ -47,9 +45,8 @@ class DispatcherTests: XCTestCase, DispatcherDelegate { loadSuccesfulException = expectation(description: "\(#function)") waitForExpectations(timeout: timeoutForRequest, handler: nil) } - - func testStopDispatcher() - { + + func testStopDispatcher() { let dispatcher = Dispatcher(withDelegate: self, autoRefreshMillies: 10.0) dispatcher.start() XCTAssertNotNil(dispatcher.timer) @@ -57,8 +54,8 @@ class DispatcherTests: XCTestCase, DispatcherDelegate { dispatcher.stop() XCTAssertNil(dispatcher.timer) } - - //MARK:- DispatcherDelegate method + + // MARK: - DispatcherDelegate method func refreshDemand() { loadSuccesfulException?.fulfill() } diff --git a/src/PrebidMobile/PrebidMobileTests/FetchingLogictests/MockCLLocationManager.swift b/src/PrebidMobile/PrebidMobileTests/FetchingLogictests/MockCLLocationManager.swift index 4a5c6042c..ff2622176 100644 --- a/src/PrebidMobile/PrebidMobileTests/FetchingLogictests/MockCLLocationManager.swift +++ b/src/PrebidMobile/PrebidMobileTests/FetchingLogictests/MockCLLocationManager.swift @@ -1,11 +1,11 @@ /* Copyright 2018-2019 Prebid.org, Inc. - + 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. @@ -18,13 +18,13 @@ import CoreLocation import MapKit class RepeatingTimer { - + let timeInterval: TimeInterval - + init(timeInterval: TimeInterval) { self.timeInterval = timeInterval } - + private lazy var timer: DispatchSourceTimer = { let t = DispatchSource.makeTimerSource() t.schedule(deadline: .now() + self.timeInterval, repeating: self.timeInterval) @@ -33,16 +33,16 @@ class RepeatingTimer { }) return t }() - + var eventHandler: (() -> Void)? - + private enum State { case suspended case resumed } - + private var state: State = .suspended - + deinit { timer.setEventHandler {} timer.cancel() @@ -53,7 +53,7 @@ class RepeatingTimer { resume() eventHandler = nil } - + func resume() { if state == .resumed { return @@ -61,7 +61,7 @@ class RepeatingTimer { state = .resumed timer.resume() } - + func suspend() { if state == .suspended { return @@ -71,35 +71,31 @@ class RepeatingTimer { } } - class MockCLLocationManager: CLLocationManager { private var timer: Timer? - private var locations: CLLocation? = nil - private var _isRunning:Bool = false + private var locations: CLLocation? + private var _isRunning: Bool = false var updateInterval: TimeInterval = 0.1 var isRunning: Bool { - get { return _isRunning - } } static let shared = MockCLLocationManager() private override init() { - + } func startMocks(usingGpx fileName: String) { - + } func stopMocking() { self.stopUpdatingLocation() } private func updateLocation() { delegate?.locationManager?(self, didUpdateLocations: [locations!]) - + } override func startUpdatingLocation() { - - timer = Timer(timeInterval: updateInterval, repeats: true, block: { - [unowned self](_) in + + timer = Timer(timeInterval: updateInterval, repeats: true, block: { [unowned self](_) in self.locations = CLLocation(latitude: 28.5388, longitude: -81.3756) self.updateLocation() }) @@ -115,6 +111,6 @@ class MockCLLocationManager: CLLocationManager { override func requestLocation() { self.locations = CLLocation(latitude: 28.5388, longitude: -81.3756) delegate?.locationManager?(self, didUpdateLocations: [locations!]) - + } } diff --git a/src/PrebidMobile/PrebidMobileTests/FetchingLogictests/RequestBuilderTests.swift b/src/PrebidMobile/PrebidMobileTests/FetchingLogictests/RequestBuilderTests.swift index af198358e..c59b607bc 100644 --- a/src/PrebidMobile/PrebidMobileTests/FetchingLogictests/RequestBuilderTests.swift +++ b/src/PrebidMobile/PrebidMobileTests/FetchingLogictests/RequestBuilderTests.swift @@ -1,11 +1,11 @@ /* Copyright 2018-2019 Prebid.org, Inc. - + 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. @@ -20,106 +20,98 @@ import AdSupport import WebKit @testable import PrebidMobile -class RequestBuilderTests: XCTestCase,CLLocationManagerDelegate { - - var app:XCUIApplication? - var coreLocation:CLLocationManager? = nil - var adUnit : BannerAdUnit! +class RequestBuilderTests: XCTestCase, CLLocationManagerDelegate { + + var app: XCUIApplication? + var coreLocation: CLLocationManager? + var adUnit: BannerAdUnit! override func setUp() { // Put setup code here. This method is called before the invocation of each test method in the class. Prebid.shared.prebidServerAccountId = "bfa84af2-bd16-4d35-96ad-31c6bb888df0" Prebid.shared.prebidServerHost = PrebidHost.Appnexus - + // app = XCUIApplication() -// +// // addUIInterruptionMonitor(withDescription: "Location authorization") { (alert) -> Bool in // if alert.buttons["OK"].exists { // alert.buttons["OK"].tap() // } // return true // } -// +// // app?.launch() - + let targeting = Targeting.shared targeting.gender = Gender.male targeting.subjectToGDPR = true targeting.itunesID = "12345" targeting.gdprConsentString = "testGDPR" - + adUnit = BannerAdUnit(configId: Constants.configID1, size: CGSize(width: Constants.width2, height: Constants.height2)) adUnit.identifier = "PrebidMobile" } - + override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. adUnit = nil } - - func testPostData() - { + + func testPostData() { let targeting = Targeting.shared try! targeting.setYearOfBirth(yob: 1990) - + do { try RequestBuilder.shared.buildPrebidRequest(adUnit: adUnit) { (urlRequest) in - let jsonRequestBody = PBHTTPStubbingManager.jsonBodyOfURLRequest(asDictionary: urlRequest) as! [String : Any] + let jsonRequestBody = PBHTTPStubbingManager.jsonBodyOfURLRequest(asDictionary: urlRequest) as! [String: Any] XCTAssertNotNil(jsonRequestBody["regs"]) - if let regs = jsonRequestBody["regs"] as? [String : Any] - { - if let ext = regs["ext"] as? [String : Any] - { + if let regs = jsonRequestBody["regs"] as? [String: Any] { + if let ext = regs["ext"] as? [String: Any] { XCTAssertEqual(1, ext["gdpr"] as! Int) } } - if let user = jsonRequestBody["user"] as? [String : Any] - { - if let ext = user["ext"] as? [String : Any] - { + if let user = jsonRequestBody["user"] as? [String: Any] { + if let ext = user["ext"] as? [String: Any] { XCTAssertEqual("testGDPR", ext["consent"] as! String) } XCTAssertEqual("M", user["gender"] as! String) XCTAssertEqual(1990, user["yob"] as! Int) } self.validationResponse(jsonRequestBody: jsonRequestBody) - + } } catch let error { print(error.localizedDescription) } } - - func testPostDataWithCustomHost() - { + + func testPostDataWithCustomHost() { let targeting = Targeting.shared try! targeting.setYearOfBirth(yob: 1990) - + XCTAssertThrowsError(try Prebid.shared.setCustomPrebidServer(url: "http://www.rubicon.org")) Prebid.shared.prebidServerAccountId = "bfa84af2-bd16-4d35-96ad-31c6bb888df0" Prebid.shared.prebidServerHost = PrebidHost.Custom - + do { try RequestBuilder.shared.buildPrebidRequest(adUnit: adUnit) { (urlRequest) in - let jsonRequestBody = PBHTTPStubbingManager.jsonBodyOfURLRequest(asDictionary: urlRequest) as! [String : Any] + let jsonRequestBody = PBHTTPStubbingManager.jsonBodyOfURLRequest(asDictionary: urlRequest) as! [String: Any] self.validationResponse(jsonRequestBody: jsonRequestBody) } } catch let error { print(error.localizedDescription) } } - - func testPostDataWithNoGDPR() - { + + func testPostDataWithNoGDPR() { let targeting = Targeting.shared targeting.subjectToGDPR = false try! targeting.setYearOfBirth(yob: 1990) - + do { try RequestBuilder.shared.buildPrebidRequest(adUnit: adUnit) { (urlRequest) in - let jsonRequestBody = PBHTTPStubbingManager.jsonBodyOfURLRequest(asDictionary: urlRequest) as! [String : Any] + let jsonRequestBody = PBHTTPStubbingManager.jsonBodyOfURLRequest(asDictionary: urlRequest) as! [String: Any] XCTAssertNil(jsonRequestBody["regs"]) - if let user = jsonRequestBody["user"] as? [String : Any] - { + if let user = jsonRequestBody["user"] as? [String: Any] { XCTAssertNil(user["ext"]) XCTAssertEqual("M", user["gender"] as! String) XCTAssertEqual(1990, user["yob"] as! Int) @@ -130,22 +122,20 @@ class RequestBuilderTests: XCTestCase,CLLocationManagerDelegate { print(error.localizedDescription) } } - - func testPostDataWithNoTargetingKeys() - { + + func testPostDataWithNoTargetingKeys() { let targeting = Targeting.shared targeting.gender = Gender.unknown targeting.subjectToGDPR = false targeting.itunesID = nil targeting.clearYearOfBirth() - + do { try RequestBuilder.shared.buildPrebidRequest(adUnit: adUnit) { (urlRequest) in - let jsonRequestBody = PBHTTPStubbingManager.jsonBodyOfURLRequest(asDictionary: urlRequest) as! [String : Any] + let jsonRequestBody = PBHTTPStubbingManager.jsonBodyOfURLRequest(asDictionary: urlRequest) as! [String: Any] print(jsonRequestBody) XCTAssertNil(jsonRequestBody["regs"]) - if let user = jsonRequestBody["user"] as? [String : Any] - { + if let user = jsonRequestBody["user"] as? [String: Any] { XCTAssertNil(user["ext"]) XCTAssertEqual("O", user["gender"] as! String) XCTAssertNil(user["yob"]) @@ -156,9 +146,8 @@ class RequestBuilderTests: XCTestCase,CLLocationManagerDelegate { print(error.localizedDescription) } } - - func testPostDataWithCustomKeyword() - { + + func testPostDataWithCustomKeyword() { let targeting = Targeting.shared targeting.gender = Gender.unknown targeting.subjectToGDPR = false @@ -167,16 +156,15 @@ class RequestBuilderTests: XCTestCase,CLLocationManagerDelegate { adUnit.addUserKeyword(key: "key1", value: "value1") do { try RequestBuilder.shared.buildPrebidRequest(adUnit: adUnit) { (urlRequest) in - let jsonRequestBody = PBHTTPStubbingManager.jsonBodyOfURLRequest(asDictionary: urlRequest) as! [String : Any] + let jsonRequestBody = PBHTTPStubbingManager.jsonBodyOfURLRequest(asDictionary: urlRequest) as! [String: Any] XCTAssertNil(jsonRequestBody["regs"]) - if let user = jsonRequestBody["user"] as? [String : Any] - { + if let user = jsonRequestBody["user"] as? [String: Any] { XCTAssertNil(user["ext"]) XCTAssertEqual("O", user["gender"] as! String) XCTAssertNil(user["yob"]) XCTAssertNotNil(user["keywords"]) XCTAssertEqual("key1=value1", user["keywords"] as! String) - + } self.validationResponse(jsonRequestBody: jsonRequestBody) } @@ -184,24 +172,23 @@ class RequestBuilderTests: XCTestCase,CLLocationManagerDelegate { print(error.localizedDescription) } } - - func testPostDataWithShareLocationOn() - { + + func testPostDataWithShareLocationOn() { coreLocation = CLLocationManager() coreLocation?.delegate = self - + coreLocation!.swizzledStartLocation() - + coreLocation?.swizzedRequestLocation() - + Prebid.shared.shareGeoLocation = true do { sleep(10) try RequestBuilder.shared.buildPrebidRequest(adUnit: adUnit) { (urlRequest) in - let jsonRequestBody = PBHTTPStubbingManager.jsonBodyOfURLRequest(asDictionary: urlRequest) as! [String : Any] - let device = jsonRequestBody["device"] as? [String : Any] + let jsonRequestBody = PBHTTPStubbingManager.jsonBodyOfURLRequest(asDictionary: urlRequest) as! [String: Any] + let device = jsonRequestBody["device"] as? [String: Any] XCTAssertNotNil(device!["geo"]) - let geo = device!["geo"] as? [String : Any] + let geo = device!["geo"] as? [String: Any] XCTAssertNotNil(geo!["accuracy"]) XCTAssertNotNil(geo!["lastfix"]) XCTAssertNotNil(geo!["lat"]) @@ -210,63 +197,59 @@ class RequestBuilderTests: XCTestCase,CLLocationManagerDelegate { } catch let error { print(error.localizedDescription) } - - + } - - func testPostDataWithShareLocationOff() - { + + func testPostDataWithShareLocationOff() { Prebid.shared.shareGeoLocation = false do { sleep(10) try RequestBuilder.shared.buildPrebidRequest(adUnit: adUnit) { (urlRequest) in - let jsonRequestBody = PBHTTPStubbingManager.jsonBodyOfURLRequest(asDictionary: urlRequest) as! [String : Any] - let device = jsonRequestBody["device"] as? [String : Any] + let jsonRequestBody = PBHTTPStubbingManager.jsonBodyOfURLRequest(asDictionary: urlRequest) as! [String: Any] + let device = jsonRequestBody["device"] as? [String: Any] XCTAssertNil(device!["geo"]) } } catch let error { print(error.localizedDescription) } } - - func testYOBWith1855() - { + + func testYOBWith1855() { let targeting = Targeting.shared XCTAssertThrowsError(try targeting.setYearOfBirth(yob: 1855)) let value = Targeting.shared.yearOfBirth XCTAssertFalse(value == 1855) - + do { try RequestBuilder.shared.buildPrebidRequest(adUnit: adUnit) { (urlRequest) in - let jsonRequestBody = PBHTTPStubbingManager.jsonBodyOfURLRequest(asDictionary: urlRequest) as! [String : Any] - let user = jsonRequestBody["user"] as? [String : Any] + let jsonRequestBody = PBHTTPStubbingManager.jsonBodyOfURLRequest(asDictionary: urlRequest) as! [String: Any] + let user = jsonRequestBody["user"] as? [String: Any] XCTAssertNil(user!["yob"]) } } catch let error { print(error.localizedDescription) } } - - func testYOBWithNegative1() - { + + func testYOBWithNegative1() { let targeting = Targeting.shared XCTAssertThrowsError(try targeting.setYearOfBirth(yob: -1)) let value = Targeting.shared.yearOfBirth XCTAssertFalse(value == -1) - + do { try RequestBuilder.shared.buildPrebidRequest(adUnit: adUnit) { (urlRequest) in - let jsonRequestBody = PBHTTPStubbingManager.jsonBodyOfURLRequest(asDictionary: urlRequest) as! [String : Any] - let user = jsonRequestBody["user"] as? [String : Any] + let jsonRequestBody = PBHTTPStubbingManager.jsonBodyOfURLRequest(asDictionary: urlRequest) as! [String: Any] + let user = jsonRequestBody["user"] as? [String: Any] XCTAssertNil(user!["yob"]) } } catch let error { print(error.localizedDescription) } - + } - - func validationResponse(jsonRequestBody : [String : Any]) { + + func validationResponse(jsonRequestBody: [String: Any]) { XCTAssertNotNil(jsonRequestBody["id"]) XCTAssertNotNil(jsonRequestBody["source"]) @@ -275,29 +258,25 @@ class RequestBuilderTests: XCTestCase,CLLocationManagerDelegate { XCTAssertNotNil(jsonRequestBody["app"]) XCTAssertNotNil(jsonRequestBody["user"]) XCTAssertNotNil(jsonRequestBody["ext"]) - - if let impArray = jsonRequestBody["imp"] as? [Any], let impDic = impArray[0] as? [String : Any] - { + + if let impArray = jsonRequestBody["imp"] as? [Any], let impDic = impArray[0] as? [String: Any] { XCTAssertEqual("PrebidMobile", impDic["id"] as! String) XCTAssertEqual(1, impDic["secure"] as! Int) - if let ext = impDic["ext"] as? [String:Any], let prebid = ext["prebid"] as? [String:Any], let storedrequest = prebid["storedrequest"] as? [String:Any] - { + if let ext = impDic["ext"] as? [String: Any], let prebid = ext["prebid"] as? [String: Any], let storedrequest = prebid["storedrequest"] as? [String: Any] { XCTAssertEqual("6ace8c7d-88c0-4623-8117-75bc3f0a2e45", storedrequest["id"] as! String) } - if let banner = impDic["banner"] as? [String:Any], let format = banner["format"] as? [Any], let size = format[0] as? [String:Any] - { + if let banner = impDic["banner"] as? [String: Any], let format = banner["format"] as? [Any], let size = format[0] as? [String: Any] { XCTAssertEqual(250, size["h"] as! Int) XCTAssertEqual(300, size["w"] as! Int) } } - - if let device = jsonRequestBody["device"] as? [String : Any] - { - let reachability:Reachability = Reachability()! - var connectionType:Int = 0 - if (reachability.connection == .wifi){ + + if let device = jsonRequestBody["device"] as? [String: Any] { + let reachability: Reachability = Reachability()! + var connectionType: Int = 0 + if (reachability.connection == .wifi) { connectionType = 1 - }else if(reachability.connection == .cellular){ + } else if (reachability.connection == .cellular) { connectionType = 2 } XCTAssertEqual(connectionType, device["connectiontype"] as! Int) @@ -312,60 +291,47 @@ class RequestBuilderTests: XCTestCase,CLLocationManagerDelegate { XCTAssertEqual(carrier?.carrierName ?? "", device["carrier"] as! String) } XCTAssertEqual(RequestBuilder.DeviceUUID(), device["ifa"] as! String) - let lmtAd:Bool = !ASIdentifierManager.shared().isAdvertisingTrackingEnabled - XCTAssertEqual(NSNumber(value:lmtAd).intValue, device["lmt"] as! Int) + let lmtAd: Bool = !ASIdentifierManager.shared().isAdvertisingTrackingEnabled + XCTAssertEqual(NSNumber(value: lmtAd).intValue, device["lmt"] as! Int) XCTAssertEqual(UIScreen.main.scale, device["pxratio"] as! CGFloat) } - if let ext = jsonRequestBody["ext"] as? [String : Any] - { + if let ext = jsonRequestBody["ext"] as? [String: Any] { XCTAssertNotNil(ext["prebid"]) - if let prebid = ext["prebid"] as? [String : Any] - { + if let prebid = ext["prebid"] as? [String: Any] { XCTAssertNotNil(prebid["cache"]) - if let cache = prebid["cache"] as? [String : Any] - { + if let cache = prebid["cache"] as? [String: Any] { XCTAssertNotNil(cache["bids"]) } - if let storedrequest = prebid["storedrequest"] as? [String : Any] - { - if let id = storedrequest["id"] as? String - { + if let storedrequest = prebid["storedrequest"] as? [String: Any] { + if let id = storedrequest["id"] as? String { XCTAssertEqual("bfa84af2-bd16-4d35-96ad-31c6bb888df0", id) } } XCTAssertNotNil(prebid["targeting"]) } } - if let app = jsonRequestBody["app"] as? [String : Any] - { - if let ext = app["ext"] as? [String : Any] - { - if let prebid = ext["prebid"] as? [String : Any] - { + if let app = jsonRequestBody["app"] as? [String: Any] { + if let ext = app["ext"] as? [String: Any] { + if let prebid = ext["prebid"] as? [String: Any] { XCTAssertEqual("prebid-mobile", prebid["source"] as! String) XCTAssertEqual("1.0", prebid["version"] as! String) } } - if let publisher = app["publisher"] as? [String : Any] - { - if let id = publisher["id"] as? String - { + if let publisher = app["publisher"] as? [String: Any] { + if let id = publisher["id"] as? String { XCTAssertEqual("bfa84af2-bd16-4d35-96ad-31c6bb888df0", id) } } } - if let source = jsonRequestBody["source"] as? [String : Any] - { + if let source = jsonRequestBody["source"] as? [String: Any] { let tid = source["tid"] as? String XCTAssertNotNil(tid) } } - - func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]){ + + func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { Location.shared.location = locations.last! - + } } - - diff --git a/src/PrebidMobile/PrebidMobileTests/FetchingLogictests/UtilsTests.swift b/src/PrebidMobile/PrebidMobileTests/FetchingLogictests/UtilsTests.swift index 6616161d1..80732b8c0 100644 --- a/src/PrebidMobile/PrebidMobileTests/FetchingLogictests/UtilsTests.swift +++ b/src/PrebidMobile/PrebidMobileTests/FetchingLogictests/UtilsTests.swift @@ -1,11 +1,11 @@ /* Copyright 2018-2019 Prebid.org, Inc. - + 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. @@ -16,114 +16,111 @@ import XCTest @testable import PrebidMobile -@objcMembers public class DFPORequest:NSObject { - var name:String! - private(set) var p_customKeywords:[String:AnyObject] - - @objc var customTargeting:[String:AnyObject] { - - get { +@objcMembers public class DFPORequest: NSObject { + var name: String! + private(set) var p_customKeywords: [String: AnyObject] + + var customTargeting: [String: AnyObject] { return p_customKeywords - } } - + override init() { - self.p_customKeywords = [String:AnyObject]() + self.p_customKeywords = [String: AnyObject]() } } -@objcMembers public class DFPNRequest:NSObject { - var name:String! - private(set) var p_customKeywords:[String:AnyObject] - - @objc var customTargeting:[String:AnyObject] { - +@objcMembers public class DFPNRequest: NSObject { + var name: String! + private(set) var p_customKeywords: [String: AnyObject] + + var customTargeting: [String: AnyObject] { + get { return p_customKeywords } - + set { self.p_customKeywords = newValue } - + } - + override init() { - self.p_customKeywords = [String:AnyObject]() + self.p_customKeywords = [String: AnyObject]() } } -@objcMembers public class MPAdView:NSObject { - var name:String! - private(set) var p_customKeywords:String = "" - - @objc var keywords:String { - +@objcMembers public class MPAdView: NSObject { + var name: String! + private(set) var p_customKeywords: String = "" + + var keywords: String { + get { return p_customKeywords } - + set { self.p_customKeywords = newValue } - + } } -@objcMembers public class InvalidMPAdView:NSObject { - var name:String! - private(set) var p_customKeywords:String = "" - - @objc var keywords:String { - +@objcMembers public class InvalidMPAdView: NSObject { + var name: String! + private(set) var p_customKeywords: String = "" + + var keywords: String { + get { return p_customKeywords } - + set { self.p_customKeywords = newValue } - + } } class UtilsTests: XCTestCase { - - var dfpAdObject:DFPNRequest? - var invalidDfpAdObject:DFPORequest? - var mopubObject:MPAdView? - var invalidMopubObject:InvalidMPAdView? - + + var dfpAdObject: DFPNRequest? + var invalidDfpAdObject: DFPORequest? + var mopubObject: MPAdView? + var invalidMopubObject: InvalidMPAdView? + override func setUp() { dfpAdObject = DFPNRequest() mopubObject = MPAdView() } - + override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. } - + func testAttachDFPKeywords() { - let utils:Utils = Utils.shared - - let prebidKeywords:[String:String] = ["hb_env":"mobile-app", - "hb_bidder_appnexus":"appnexus", - "hb_size_appnexus":"300x250", - "hb_pb_appnexus":"0.50", - "hb_env_appnexus":"mobile-app", - "hb_cache_id":"d6e43a95-5ee2-4d74-ae85-e4b602b7f88d", - "hb_cache_id_appnexus":"d6e43a95-5ee2-4d74-ae85-e4b602b7f88d", - "hb_pb":"0.50", - "hb_bidder":"appnexus", - "hb_size":"300x250"] - dfpAdObject?.customTargeting = ["test_key":"test_value"] as [String : AnyObject] - - let bidResponse = BidResponse(adId: "test", adServerTargeting: prebidKeywords as [String : AnyObject]) - + let utils: Utils = Utils.shared + + let prebidKeywords: [String: String] = ["hb_env": "mobile-app", + "hb_bidder_appnexus": "appnexus", + "hb_size_appnexus": "300x250", + "hb_pb_appnexus": "0.50", + "hb_env_appnexus": "mobile-app", + "hb_cache_id": "d6e43a95-5ee2-4d74-ae85-e4b602b7f88d", + "hb_cache_id_appnexus": "d6e43a95-5ee2-4d74-ae85-e4b602b7f88d", + "hb_pb": "0.50", + "hb_bidder": "appnexus", + "hb_size": "300x250"] + dfpAdObject?.customTargeting = ["test_key": "test_value"] as [String: AnyObject] + + let bidResponse = BidResponse(adId: "test", adServerTargeting: prebidKeywords as [String: AnyObject]) + utils.validateAndAttachKeywords(adObject: dfpAdObject as AnyObject, bidResponse: bidResponse) - + XCTAssertTrue(((dfpAdObject?.description) != nil), "DFPNRequest") - + XCTAssertNotNil(dfpAdObject?.customTargeting) XCTAssertEqual(11, dfpAdObject?.customTargeting.count) XCTAssertEqual(dfpAdObject?.customTargeting["test_key"] as! String, "test_value") @@ -137,21 +134,21 @@ class UtilsTests: XCTestCase { XCTAssertEqual(dfpAdObject!.customTargeting["hb_pb_appnexus"] as! String, "0.50") XCTAssertEqual(dfpAdObject!.customTargeting["hb_cache_id_appnexus"] as! String, "d6e43a95-5ee2-4d74-ae85-e4b602b7f88d") XCTAssertEqual(dfpAdObject!.customTargeting["hb_env_appnexus"] as! String, "mobile-app") - let prebidKeywords2:[String:String] = ["hb_env":"mobile-app", - "hb_bidder_rubicon":"rubicon", - "hb_size_rubicon":"300x250", - "hb_pb_rubicon":"0.50", - "hb_env_rubicon":"mobile-app", - "hb_cache_id":"ffffffff-5ee2-4d74-ae85-e4b602b7f88d", - "hb_cache_id_rubicon":"ffffffff-5ee2-4d74-ae85-e4b602b7f88d", - "hb_pb":"0.50", - "hb_bidder":"rubicon", - "hb_size":"300x250"] - let bidResponse2 = BidResponse(adId: "test", adServerTargeting: prebidKeywords2 as [String : AnyObject]) - utils.removeHBKeywords(adObject:dfpAdObject!) + let prebidKeywords2: [String: String] = ["hb_env": "mobile-app", + "hb_bidder_rubicon": "rubicon", + "hb_size_rubicon": "300x250", + "hb_pb_rubicon": "0.50", + "hb_env_rubicon": "mobile-app", + "hb_cache_id": "ffffffff-5ee2-4d74-ae85-e4b602b7f88d", + "hb_cache_id_rubicon": "ffffffff-5ee2-4d74-ae85-e4b602b7f88d", + "hb_pb": "0.50", + "hb_bidder": "rubicon", + "hb_size": "300x250"] + let bidResponse2 = BidResponse(adId: "test", adServerTargeting: prebidKeywords2 as [String: AnyObject]) + utils.removeHBKeywords(adObject: dfpAdObject!) utils.validateAndAttachKeywords(adObject: dfpAdObject as AnyObject, bidResponse: bidResponse2) XCTAssertTrue(((dfpAdObject?.description) != nil), "DFPNRequest") - + XCTAssertNotNil(dfpAdObject?.customTargeting) XCTAssertEqual(11, dfpAdObject?.customTargeting.count) XCTAssertEqual(dfpAdObject?.customTargeting["test_key"] as! String, "test_value") @@ -171,28 +168,28 @@ class UtilsTests: XCTestCase { XCTAssertNil(dfpAdObject!.customTargeting["hb_cache_id_appnexus"]) XCTAssertNil(dfpAdObject!.customTargeting["hb_env_appnexus"]) } - + func testRemoveDFPKeywords() { - let utils:Utils = Utils.shared - - let prebidKeywords:[String:String] = ["hb_env":"mobile-app", - "hb_bidder_appnexus":"appnexus", - "hb_size_appnexus":"300x250", - "hb_pb_appnexus":"0.50", - "hb_env_appnexus":"mobile-app", - "hb_cache_id":"d6e43a95-5ee2-4d74-ae85-e4b602b7f88d", - "hb_cache_id_appnexus":"d6e43a95-5ee2-4d74-ae85-e4b602b7f88d", - "hb_pb":"0.50", - "hb_bidder":"appnexus", - "hb_size":"300x250"] - dfpAdObject?.customTargeting = ["test_key":"test_value"] as [String : AnyObject] - - let bidResponse = BidResponse(adId: "test", adServerTargeting: prebidKeywords as [String : AnyObject]) - + let utils: Utils = Utils.shared + + let prebidKeywords: [String: String] = ["hb_env": "mobile-app", + "hb_bidder_appnexus": "appnexus", + "hb_size_appnexus": "300x250", + "hb_pb_appnexus": "0.50", + "hb_env_appnexus": "mobile-app", + "hb_cache_id": "d6e43a95-5ee2-4d74-ae85-e4b602b7f88d", + "hb_cache_id_appnexus": "d6e43a95-5ee2-4d74-ae85-e4b602b7f88d", + "hb_pb": "0.50", + "hb_bidder": "appnexus", + "hb_size": "300x250"] + dfpAdObject?.customTargeting = ["test_key": "test_value"] as [String: AnyObject] + + let bidResponse = BidResponse(adId: "test", adServerTargeting: prebidKeywords as [String: AnyObject]) + utils.validateAndAttachKeywords(adObject: dfpAdObject as AnyObject, bidResponse: bidResponse) - + XCTAssertTrue(((dfpAdObject?.description) != nil), "DFPNRequest") - + XCTAssertNotNil(dfpAdObject?.customTargeting) XCTAssertEqual(11, dfpAdObject?.customTargeting.count) XCTAssertEqual(dfpAdObject?.customTargeting["test_key"] as! String, "test_value") @@ -206,9 +203,9 @@ class UtilsTests: XCTestCase { XCTAssertEqual(dfpAdObject!.customTargeting["hb_pb_appnexus"] as! String, "0.50") XCTAssertEqual(dfpAdObject!.customTargeting["hb_cache_id_appnexus"] as! String, "d6e43a95-5ee2-4d74-ae85-e4b602b7f88d") XCTAssertEqual(dfpAdObject!.customTargeting["hb_env_appnexus"] as! String, "mobile-app") - + utils.removeHBKeywords(adObject: dfpAdObject!) - + XCTAssertTrue(((dfpAdObject?.description) != nil), "DFPNRequest") XCTAssertNotNil(dfpAdObject?.customTargeting) XCTAssertEqual(1, dfpAdObject?.customTargeting.count) @@ -223,20 +220,20 @@ class UtilsTests: XCTestCase { XCTAssertNil(dfpAdObject?.customTargeting["hb_pb_appnexus"]) XCTAssertNil(dfpAdObject?.customTargeting["hb_cache_id_appnexus"]) XCTAssertNil(dfpAdObject?.customTargeting["hb_env_appnexus"]) - - let prebidKeywords2:[String:String] = ["hb_env":"mobile-app", - "hb_bidder_rubicon":"rubicon", - "hb_size_rubicon":"300x250", - "hb_pb_rubicon":"0.50", - "hb_env_rubicon":"mobile-app", - "hb_cache_id":"ffffffff-5ee2-4d74-ae85-e4b602b7f88d", - "hb_cache_id_rubicon":"ffffffff-5ee2-4d74-ae85-e4b602b7f88d", - "hb_pb":"0.50", - "hb_bidder":"rubicon", - "hb_size":"300x250"] - let bidResponse2 = BidResponse(adId: "test", adServerTargeting: prebidKeywords2 as [String : AnyObject]) + + let prebidKeywords2: [String: String] = ["hb_env": "mobile-app", + "hb_bidder_rubicon": "rubicon", + "hb_size_rubicon": "300x250", + "hb_pb_rubicon": "0.50", + "hb_env_rubicon": "mobile-app", + "hb_cache_id": "ffffffff-5ee2-4d74-ae85-e4b602b7f88d", + "hb_cache_id_rubicon": "ffffffff-5ee2-4d74-ae85-e4b602b7f88d", + "hb_pb": "0.50", + "hb_bidder": "rubicon", + "hb_size": "300x250"] + let bidResponse2 = BidResponse(adId: "test", adServerTargeting: prebidKeywords2 as [String: AnyObject]) utils.validateAndAttachKeywords(adObject: dfpAdObject as AnyObject, bidResponse: bidResponse2) - + XCTAssertTrue(((dfpAdObject?.description) != nil), "DFPNRequest") XCTAssertNotNil(dfpAdObject?.customTargeting) XCTAssertEqual(11, dfpAdObject?.customTargeting.count) @@ -256,9 +253,9 @@ class UtilsTests: XCTestCase { XCTAssertNil(dfpAdObject!.customTargeting["hb_pb_appnexus"]) XCTAssertNil(dfpAdObject!.customTargeting["hb_cache_id_appnexus"]) XCTAssertNil(dfpAdObject!.customTargeting["hb_env_appnexus"]) - + utils.removeHBKeywords(adObject: dfpAdObject!) - + XCTAssertTrue(((dfpAdObject?.description) != nil), "DFPNRequest") XCTAssertNotNil(dfpAdObject?.customTargeting) XCTAssertEqual(1, dfpAdObject?.customTargeting.count) @@ -279,79 +276,78 @@ class UtilsTests: XCTestCase { XCTAssertNil(dfpAdObject?.customTargeting["hb_cache_id_appnexus"]) XCTAssertNil(dfpAdObject?.customTargeting["hb_env_appnexus"]) } - + func testDFPKeywordsAbsent() { - let utils:Utils = Utils.shared - let prebidKeywords:[String:String] = [:] - dfpAdObject?.customTargeting = ["test_key":"test_value"] as [String : AnyObject] - let bidResponse = BidResponse(adId: "test", adServerTargeting: prebidKeywords as [String : AnyObject]) + let utils: Utils = Utils.shared + let prebidKeywords: [String: String] = [:] + dfpAdObject?.customTargeting = ["test_key": "test_value"] as [String: AnyObject] + let bidResponse = BidResponse(adId: "test", adServerTargeting: prebidKeywords as [String: AnyObject]) utils.validateAndAttachKeywords(adObject: dfpAdObject as AnyObject, bidResponse: bidResponse) - + XCTAssertTrue(((dfpAdObject?.description) != nil), "DFPNRequest") XCTAssertNotNil(dfpAdObject?.customTargeting) XCTAssertEqual(1, dfpAdObject?.customTargeting.count) XCTAssertEqual(dfpAdObject?.customTargeting["test_key"] as! String, "test_value") } - + func testDFPInvalidObject() { - let utils:Utils = Utils.shared - let prebidKeywords:[String:String] = ["hb_env":"mobile-app","hb_bidder_appnexus":"appnexus","hb_size_appnexus":"300x250","hb_pb_appnexus": - "0.50","hb_env_appnexus":"mobile-app","hb_cache_id":"d6e43a95-5ee2-4d74-ae85-e4b602b7f88d","hb_cache_id_appnexus":"d6e43a95-5ee2-4d74-ae85-e4b602b7f88d","hb_pb":"0.50","hb_bidder":"appnexus","hb_size":"300x250"] - let bidResponse = BidResponse(adId: "test", adServerTargeting: prebidKeywords as [String : AnyObject]) + let utils: Utils = Utils.shared + let prebidKeywords: [String: String] = ["hb_env": "mobile-app", "hb_bidder_appnexus": "appnexus", "hb_size_appnexus": "300x250", "hb_pb_appnexus": + "0.50", "hb_env_appnexus": "mobile-app", "hb_cache_id": "d6e43a95-5ee2-4d74-ae85-e4b602b7f88d", "hb_cache_id_appnexus": "d6e43a95-5ee2-4d74-ae85-e4b602b7f88d", "hb_pb": "0.50", "hb_bidder": "appnexus", "hb_size": "300x250"] + let bidResponse = BidResponse(adId: "test", adServerTargeting: prebidKeywords as [String: AnyObject]) utils.validateAndAttachKeywords(adObject: invalidDfpAdObject as AnyObject, bidResponse: bidResponse) XCTAssertNil(invalidDfpAdObject?.customTargeting) - + } - + func testExistingAndRemovingPrebidKeywords() { - let utils:Utils = Utils.shared - - var prebidKeywords:[String:String] = ["hb_env":"mobile-app"] - dfpAdObject?.customTargeting = ["test_key":"test_value"] as [String : AnyObject] - - var bidResponse = BidResponse(adId: "test", adServerTargeting: prebidKeywords as [String : AnyObject]) - + let utils: Utils = Utils.shared + + var prebidKeywords: [String: String] = ["hb_env": "mobile-app"] + dfpAdObject?.customTargeting = ["test_key": "test_value"] as [String: AnyObject] + + var bidResponse = BidResponse(adId: "test", adServerTargeting: prebidKeywords as [String: AnyObject]) + utils.validateAndAttachKeywords(adObject: dfpAdObject as AnyObject, bidResponse: bidResponse) - + XCTAssertTrue(((dfpAdObject?.description) != nil), "DFPNRequest") - + XCTAssertNotNil(dfpAdObject?.customTargeting) XCTAssertEqual(2, dfpAdObject?.customTargeting.count) XCTAssertEqual(dfpAdObject?.customTargeting["test_key"] as! String, "test_value") XCTAssertEqual(dfpAdObject!.customTargeting["hb_env"] as! String, "mobile-app") - - prebidKeywords = ["app" : "prebid"] - bidResponse = BidResponse(adId: "test", adServerTargeting: prebidKeywords as [String : AnyObject]) - + + prebidKeywords = ["app": "prebid"] + bidResponse = BidResponse(adId: "test", adServerTargeting: prebidKeywords as [String: AnyObject]) + utils.validateAndAttachKeywords(adObject: dfpAdObject as AnyObject, bidResponse: bidResponse) XCTAssertEqual(3, dfpAdObject?.customTargeting.count) XCTAssertEqual(dfpAdObject?.customTargeting["test_key"] as! String, "test_value") XCTAssertEqual(dfpAdObject!.customTargeting["hb_env"] as! String, "mobile-app") XCTAssertEqual(dfpAdObject!.customTargeting["app"] as! String, "prebid") - + utils.removeHBKeywords(adObject: dfpAdObject!) XCTAssertEqual(2, dfpAdObject?.customTargeting.count) XCTAssertNil(dfpAdObject?.customTargeting["hb_env"]) XCTAssertEqual(dfpAdObject?.customTargeting["test_key"] as! String, "test_value") XCTAssertEqual(dfpAdObject!.customTargeting["app"] as! String, "prebid") } - + func testAttachMoPubKeywords() { - let utils:Utils = Utils.shared - - let prebidKeywords:[String:String] = ["hb_env":"mobile-app","hb_bidder_appnexus":"appnexus","hb_size_appnexus":"300x250","hb_pb_appnexus": - "0.50","hb_env_appnexus":"mobile-app","hb_cache_id":"d6e43a95-5ee2-4d74-ae85-e4b602b7f88d","hb_cache_id_appnexus":"d6e43a95-5ee2-4d74-ae85-e4b602b7f88d","hb_pb":"0.50","hb_bidder":"appnexus","hb_size":"300x250"] - - - let bidResponse = BidResponse(adId: "test1", adServerTargeting: prebidKeywords as [String : AnyObject]) + let utils: Utils = Utils.shared + + let prebidKeywords: [String: String] = ["hb_env": "mobile-app", "hb_bidder_appnexus": "appnexus", "hb_size_appnexus": "300x250", "hb_pb_appnexus": + "0.50", "hb_env_appnexus": "mobile-app", "hb_cache_id": "d6e43a95-5ee2-4d74-ae85-e4b602b7f88d", "hb_cache_id_appnexus": "d6e43a95-5ee2-4d74-ae85-e4b602b7f88d", "hb_pb": "0.50", "hb_bidder": "appnexus", "hb_size": "300x250"] + + let bidResponse = BidResponse(adId: "test1", adServerTargeting: prebidKeywords as [String: AnyObject]) mopubObject?.keywords = "test_key:test_value" utils.validateAndAttachKeywords(adObject: mopubObject as AnyObject, bidResponse: bidResponse) - + DispatchQueue.main.async { XCTAssertTrue(((self.mopubObject?.description) != nil), "MPAdView") XCTAssertNotNil(self.mopubObject?.keywords) - var keywords = self.mopubObject?.keywords - var keywordsArray = keywords!.components(separatedBy: ",") + let keywords = self.mopubObject?.keywords + let keywordsArray = keywords!.components(separatedBy: ",") XCTAssertEqual(11, keywordsArray.count) XCTAssertTrue (keywordsArray.contains("hb_env:mobile-app")) XCTAssertTrue (keywordsArray.contains("hb_bidder_appnexus:appnexus")) @@ -364,24 +360,23 @@ class UtilsTests: XCTestCase { XCTAssertTrue (keywordsArray.contains("hb_bidder:appnexus")) XCTAssertTrue (keywordsArray.contains("hb_size:300x250")) XCTAssertTrue (keywordsArray.contains("test_key:test_value")) - - + } - let prebidKeywords2:[String:String] = ["hb_env":"mobile-app", - "hb_bidder_rubicon":"rubicon", - "hb_size_rubicon":"300x250", - "hb_pb_rubicon":"0.50", - "hb_env_rubicon":"mobile-app", - "hb_cache_id":"ffffffff-5ee2-4d74-ae85-e4b602b7f88d", - "hb_cache_id_rubicon":"ffffffff-5ee2-4d74-ae85-e4b602b7f88d", - "hb_pb":"0.50", - "hb_bidder":"rubicon", - "hb_size":"300x250"] - - let bidResponse2 = BidResponse(adId: "test2", adServerTargeting: prebidKeywords2 as [String : AnyObject]) + let prebidKeywords2: [String: String] = ["hb_env": "mobile-app", + "hb_bidder_rubicon": "rubicon", + "hb_size_rubicon": "300x250", + "hb_pb_rubicon": "0.50", + "hb_env_rubicon": "mobile-app", + "hb_cache_id": "ffffffff-5ee2-4d74-ae85-e4b602b7f88d", + "hb_cache_id_rubicon": "ffffffff-5ee2-4d74-ae85-e4b602b7f88d", + "hb_pb": "0.50", + "hb_bidder": "rubicon", + "hb_size": "300x250"] + + let bidResponse2 = BidResponse(adId: "test2", adServerTargeting: prebidKeywords2 as [String: AnyObject]) utils.removeHBKeywords(adObject: self.mopubObject!) utils.validateAndAttachKeywords(adObject: self.mopubObject as AnyObject, bidResponse: bidResponse2) - + DispatchQueue.main.async { XCTAssertTrue(((self.mopubObject?.description) != nil), "MPAdView") XCTAssertNotNil(self.mopubObject?.keywords) @@ -400,25 +395,21 @@ class UtilsTests: XCTestCase { XCTAssertTrue (keywordsArray.contains("hb_size:300x250")) XCTAssertTrue (keywordsArray.contains("test_key:test_value")) } - - - - + } - + func testRemoveMoPubKeywords() { - let utils:Utils = Utils.shared - - let prebidKeywords:[String:String] = ["hb_env":"mobile-app","hb_bidder_appnexus":"appnexus","hb_size_appnexus":"300x250","hb_pb_appnexus": - "0.50","hb_env_appnexus":"mobile-app","hb_cache_id":"d6e43a95-5ee2-4d74-ae85-e4b602b7f88d","hb_cache_id_appnexus":"d6e43a95-5ee2-4d74-ae85-e4b602b7f88d","hb_pb":"0.50","hb_bidder":"appnexus","hb_size":"300x250"] - - - let bidResponse = BidResponse(adId: "test1", adServerTargeting: prebidKeywords as [String : AnyObject]) + let utils: Utils = Utils.shared + + let prebidKeywords: [String: String] = ["hb_env": "mobile-app", "hb_bidder_appnexus": "appnexus", "hb_size_appnexus": "300x250", "hb_pb_appnexus": + "0.50", "hb_env_appnexus": "mobile-app", "hb_cache_id": "d6e43a95-5ee2-4d74-ae85-e4b602b7f88d", "hb_cache_id_appnexus": "d6e43a95-5ee2-4d74-ae85-e4b602b7f88d", "hb_pb": "0.50", "hb_bidder": "appnexus", "hb_size": "300x250"] + + let bidResponse = BidResponse(adId: "test1", adServerTargeting: prebidKeywords as [String: AnyObject]) mopubObject?.keywords = "test_key:test_value" utils.validateAndAttachKeywords(adObject: mopubObject as AnyObject, bidResponse: bidResponse) - + DispatchQueue.main.async { - + XCTAssertTrue(((self.mopubObject?.description) != nil), "MPAdView") XCTAssertNotNil(self.mopubObject?.keywords) let keywords = self.mopubObject?.keywords @@ -436,7 +427,7 @@ class UtilsTests: XCTestCase { XCTAssertTrue (keywordsArray.contains("hb_size:300x250")) XCTAssertTrue (keywordsArray.contains("test_key:test_value")) } - + utils.removeHBKeywords(adObject: self.mopubObject!) DispatchQueue.main.async { XCTAssertTrue(((self.mopubObject?.description) != nil), "MPAdView") @@ -456,17 +447,17 @@ class UtilsTests: XCTestCase { XCTAssertFalse(keywordsArray.contains("hb_size:300x250")) XCTAssertTrue(keywordsArray.contains("test_key:test_value")) } - let prebidKeywords2:[String:String] = ["hb_env":"mobile-app", - "hb_bidder_rubicon":"rubicon", - "hb_size_rubicon":"300x250", - "hb_pb_rubicon":"0.50", - "hb_env_rubicon":"mobile-app", - "hb_cache_id":"ffffffff-5ee2-4d74-ae85-e4b602b7f88d", - "hb_cache_id_rubicon":"ffffffff-5ee2-4d74-ae85-e4b602b7f88d", - "hb_pb":"0.50", - "hb_bidder":"rubicon", - "hb_size":"300x250"] - let bidResponse2 = BidResponse(adId: "test2", adServerTargeting: prebidKeywords2 as [String : AnyObject]) + let prebidKeywords2: [String: String] = ["hb_env": "mobile-app", + "hb_bidder_rubicon": "rubicon", + "hb_size_rubicon": "300x250", + "hb_pb_rubicon": "0.50", + "hb_env_rubicon": "mobile-app", + "hb_cache_id": "ffffffff-5ee2-4d74-ae85-e4b602b7f88d", + "hb_cache_id_rubicon": "ffffffff-5ee2-4d74-ae85-e4b602b7f88d", + "hb_pb": "0.50", + "hb_bidder": "rubicon", + "hb_size": "300x250"] + let bidResponse2 = BidResponse(adId: "test2", adServerTargeting: prebidKeywords2 as [String: AnyObject]) utils.validateAndAttachKeywords(adObject: self.mopubObject as AnyObject, bidResponse: bidResponse2) DispatchQueue.main.async { XCTAssertTrue(((self.mopubObject?.description) != nil), "MPAdView") @@ -506,11 +497,11 @@ class UtilsTests: XCTestCase { XCTAssertTrue(keywordsArray.contains("test_key:test_value")) } } - + func testMoPubKeywordsAbsent() { - let utils:Utils = Utils.shared - let prebidKeywords:[String:String] = [:] - let bidResponse = BidResponse(adId: "test", adServerTargeting: prebidKeywords as [String : AnyObject]) + let utils: Utils = Utils.shared + let prebidKeywords: [String: String] = [:] + let bidResponse = BidResponse(adId: "test", adServerTargeting: prebidKeywords as [String: AnyObject]) mopubObject?.keywords = "test_key:test_value" utils.validateAndAttachKeywords(adObject: mopubObject as AnyObject, bidResponse: bidResponse) DispatchQueue.main.async { @@ -522,12 +513,12 @@ class UtilsTests: XCTestCase { XCTAssertTrue(keywordsArray.contains("test_key:test_value")) } } - + func testMoPubInvalidObject() { - let utils:Utils = Utils.shared - let prebidKeywords:[String:String] = ["hb_env":"mobile-app","hb_bidder_appnexus":"appnexus","hb_size_appnexus":"300x250","hb_pb_appnexus": - "0.50","hb_env_appnexus":"mobile-app","hb_cache_id":"d6e43a95-5ee2-4d74-ae85-e4b602b7f88d","hb_cache_id_appnexus":"d6e43a95-5ee2-4d74-ae85-e4b602b7f88d","hb_pb":"0.50","hb_bidder":"appnexus","hb_size":"300x250"] - let bidResponse = BidResponse(adId: "test", adServerTargeting: prebidKeywords as [String : AnyObject]) + let utils: Utils = Utils.shared + let prebidKeywords: [String: String] = ["hb_env": "mobile-app", "hb_bidder_appnexus": "appnexus", "hb_size_appnexus": "300x250", "hb_pb_appnexus": + "0.50", "hb_env_appnexus": "mobile-app", "hb_cache_id": "d6e43a95-5ee2-4d74-ae85-e4b602b7f88d", "hb_cache_id_appnexus": "d6e43a95-5ee2-4d74-ae85-e4b602b7f88d", "hb_pb": "0.50", "hb_bidder": "appnexus", "hb_size": "300x250"] + let bidResponse = BidResponse(adId: "test", adServerTargeting: prebidKeywords as [String: AnyObject]) invalidMopubObject?.keywords = "test_key:test_value" utils.validateAndAttachKeywords(adObject: invalidMopubObject as AnyObject, bidResponse: bidResponse) DispatchQueue.main.async { diff --git a/src/PrebidMobile/PrebidMobileTests/PrebidMobileTests.swift b/src/PrebidMobile/PrebidMobileTests/PrebidMobileTests.swift index d338dea64..e36047104 100644 --- a/src/PrebidMobile/PrebidMobileTests/PrebidMobileTests.swift +++ b/src/PrebidMobile/PrebidMobileTests/PrebidMobileTests.swift @@ -1,11 +1,11 @@ /* Copyright 2018-2019 Prebid.org, Inc. - + 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. @@ -17,15 +17,15 @@ import XCTest @testable import PrebidMobile class PrebidMobileTests: XCTestCase { - + override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } - + override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } - + } diff --git a/src/PrebidMobile/PrebidMobileTests/PrebidTests.swift b/src/PrebidMobile/PrebidMobileTests/PrebidTests.swift index 258671f00..6f2180014 100644 --- a/src/PrebidMobile/PrebidMobileTests/PrebidTests.swift +++ b/src/PrebidMobile/PrebidMobileTests/PrebidTests.swift @@ -1,11 +1,11 @@ /* Copyright 2018-2019 Prebid.org, Inc. - + 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. @@ -31,32 +31,32 @@ class PrebidTests: XCTestCase { XCTAssertEqual(Prebid.shared.prebidServerAccountId, "123") XCTAssertNotEqual(Prebid.shared.prebidServerAccountId, "456") } - + func testShareGeoLocation() { Prebid.shared.shareGeoLocation = true XCTAssertTrue(Prebid.shared.shareGeoLocation) - + Prebid.shared.shareGeoLocation = false XCTAssertFalse(Prebid.shared.shareGeoLocation) } - + func testServerHost() { Prebid.shared.prebidServerHost = PrebidHost.Appnexus XCTAssertEqual(Prebid.shared.prebidServerHost, PrebidHost.Appnexus) - + Prebid.shared.prebidServerHost = PrebidHost.Rubicon XCTAssertEqual(Prebid.shared.prebidServerHost, PrebidHost.Rubicon) } - + func testServerCustomHost() { - + XCTAssertEqual(Prebid.shared.prebidServerHost, PrebidHost.Appnexus) - + Prebid.shared.prebidServerHost = PrebidHost.Custom XCTAssertEqual(Prebid.shared.prebidServerHost, PrebidHost.Custom) - + XCTAssertThrowsError(try Prebid.shared.setCustomPrebidServer(url: "http://www.rubicon.org")) - + XCTAssertThrowsError(try Prebid.shared.setCustomPrebidServer(url: "abc")) } diff --git a/src/PrebidMobile/PrebidMobileTests/TargetingTests.swift b/src/PrebidMobile/PrebidMobileTests/TargetingTests.swift index e854d6aac..ab7c86285 100644 --- a/src/PrebidMobile/PrebidMobileTests/TargetingTests.swift +++ b/src/PrebidMobile/PrebidMobileTests/TargetingTests.swift @@ -1,11 +1,11 @@ /* Copyright 2018-2019 Prebid.org, Inc. - + 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. @@ -21,32 +21,32 @@ class TargetingTests: XCTestCase { override func setUp() { super.setUp() - + } - + override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. } - + func testYOB() { XCTAssertNoThrow(try Targeting.shared.setYearOfBirth(yob: 1985)) let value = Targeting.shared.yearOfBirth - + XCTAssertTrue((value == 1985)) - + } - + func testInvalidYOB() { XCTAssertThrowsError(try Targeting.shared.setYearOfBirth(yob: -1)) - + XCTAssertThrowsError(try Targeting.shared.setYearOfBirth(yob: 999)) - + XCTAssertThrowsError(try Targeting.shared.setYearOfBirth(yob: 10000)) - + } func testSetGenderTargeting() { - + Targeting.shared.gender = .female XCTAssertEqual(Gender.female, Targeting.shared.gender) Targeting.shared.gender = .male @@ -56,32 +56,32 @@ class TargetingTests: XCTestCase { } func testSetLocationTargeting() { - + let location = CLLocation(latitude: CLLocationDegrees(100.0), longitude: CLLocationDegrees(100.0)) Targeting.shared.location = location Targeting.shared.locationPrecision = 2 XCTAssertEqual(location, Targeting.shared.location) XCTAssertEqual(2, Targeting.shared.locationPrecision) } - + func testGDPRConsentString() { Targeting.shared.gdprConsentString = "testconsent" let value = Targeting.shared.gdprConsentString - + XCTAssertTrue((value == "testconsent")) } - + func testGDPREnable() { Targeting.shared.subjectToGDPR = false let testGDPR = Targeting.shared.subjectToGDPR - + XCTAssertFalse(testGDPR) } - + func testItuneIDTargeting() { Targeting.shared.itunesID = "54673893" let testItuneID = Targeting.shared.itunesID - + XCTAssertTrue((testItuneID == "54673893")) }