Repository: IvanRublev/PersistentStorageSerializable
Branch: master
Commit: 55233686ef4a
Files: 244
Total size: 883.7 KB
Directory structure:
gitextract_z6r8nz93/
├── .gitignore
├── .swift-version
├── .travis.yml
├── Cartfile
├── Cartfile.private
├── Cartfile.resolved
├── Example/
│ ├── ExamplesOfUsage.playground/
│ │ ├── Contents.swift
│ │ ├── contents.xcplayground
│ │ └── timeline.xctimeline
│ ├── PersistentStorageSerializable/
│ │ ├── AppDelegate.swift
│ │ ├── Base.lproj/
│ │ │ ├── LaunchScreen.xib
│ │ │ └── Main.storyboard
│ │ ├── Images.xcassets/
│ │ │ └── AppIcon.appiconset/
│ │ │ └── Contents.json
│ │ ├── Info.plist
│ │ ├── Settings.swift
│ │ └── ViewController.swift
│ ├── PersistentStorageSerializable.xcodeproj/
│ │ ├── project.pbxproj
│ │ ├── project.xcworkspace/
│ │ │ └── contents.xcworkspacedata
│ │ └── xcshareddata/
│ │ └── xcschemes/
│ │ ├── PersistentStorageSerializable-MacExample.xcscheme
│ │ ├── PersistentStorageSerializable-Tests.xcscheme
│ │ └── PersistentStorageSerializable-iOSExample.xcscheme
│ ├── PersistentStorageSerializable.xcworkspace/
│ │ └── contents.xcworkspacedata
│ ├── PersistentStorageSerializable_MacExample/
│ │ ├── AppDelegate.swift
│ │ ├── AppSettings.swift
│ │ ├── Assets.xcassets/
│ │ │ └── AppIcon.appiconset/
│ │ │ └── Contents.json
│ │ ├── Base.lproj/
│ │ │ └── Main.storyboard
│ │ ├── Info.plist
│ │ └── ViewController.swift
│ ├── Podfile
│ ├── Pods/
│ │ ├── Local Podspecs/
│ │ │ └── PersistentStorageSerializable.podspec.json
│ │ ├── Manifest.lock
│ │ ├── Nimble/
│ │ │ ├── LICENSE.md
│ │ │ ├── README.md
│ │ │ └── Sources/
│ │ │ ├── Lib/
│ │ │ │ └── CwlPreconditionTesting/
│ │ │ │ ├── CwlCatchException/
│ │ │ │ │ └── CwlCatchException/
│ │ │ │ │ ├── CwlCatchException.h
│ │ │ │ │ ├── CwlCatchException.m
│ │ │ │ │ └── CwlCatchException.swift
│ │ │ │ └── CwlPreconditionTesting/
│ │ │ │ ├── CwlBadInstructionException.swift
│ │ │ │ ├── CwlCatchBadInstruction.h
│ │ │ │ ├── CwlCatchBadInstruction.m
│ │ │ │ ├── CwlCatchBadInstruction.swift
│ │ │ │ ├── CwlDarwinDefinitions.swift
│ │ │ │ ├── mach_excServer.c
│ │ │ │ └── mach_excServer.h
│ │ │ ├── Nimble/
│ │ │ │ ├── Adapters/
│ │ │ │ │ ├── AdapterProtocols.swift
│ │ │ │ │ ├── AssertionDispatcher.swift
│ │ │ │ │ ├── AssertionRecorder.swift
│ │ │ │ │ ├── NMBExpectation.swift
│ │ │ │ │ ├── NMBObjCMatcher.swift
│ │ │ │ │ ├── NimbleEnvironment.swift
│ │ │ │ │ └── NimbleXCTestHandler.swift
│ │ │ │ ├── DSL+Wait.swift
│ │ │ │ ├── DSL.swift
│ │ │ │ ├── Expectation.swift
│ │ │ │ ├── Expression.swift
│ │ │ │ ├── FailureMessage.swift
│ │ │ │ ├── Matchers/
│ │ │ │ │ ├── AllPass.swift
│ │ │ │ │ ├── AsyncMatcherWrapper.swift
│ │ │ │ │ ├── BeAKindOf.swift
│ │ │ │ │ ├── BeAnInstanceOf.swift
│ │ │ │ │ ├── BeCloseTo.swift
│ │ │ │ │ ├── BeEmpty.swift
│ │ │ │ │ ├── BeGreaterThan.swift
│ │ │ │ │ ├── BeGreaterThanOrEqualTo.swift
│ │ │ │ │ ├── BeIdenticalTo.swift
│ │ │ │ │ ├── BeLessThan.swift
│ │ │ │ │ ├── BeLessThanOrEqual.swift
│ │ │ │ │ ├── BeLogical.swift
│ │ │ │ │ ├── BeNil.swift
│ │ │ │ │ ├── BeVoid.swift
│ │ │ │ │ ├── BeginWith.swift
│ │ │ │ │ ├── Contain.swift
│ │ │ │ │ ├── EndWith.swift
│ │ │ │ │ ├── Equal.swift
│ │ │ │ │ ├── HaveCount.swift
│ │ │ │ │ ├── Match.swift
│ │ │ │ │ ├── MatchError.swift
│ │ │ │ │ ├── MatcherFunc.swift
│ │ │ │ │ ├── MatcherProtocols.swift
│ │ │ │ │ ├── PostNotification.swift
│ │ │ │ │ ├── RaisesException.swift
│ │ │ │ │ ├── SatisfyAnyOf.swift
│ │ │ │ │ ├── ThrowAssertion.swift
│ │ │ │ │ └── ThrowError.swift
│ │ │ │ ├── Nimble.h
│ │ │ │ └── Utils/
│ │ │ │ ├── Async.swift
│ │ │ │ ├── Errors.swift
│ │ │ │ ├── Functional.swift
│ │ │ │ ├── SourceLocation.swift
│ │ │ │ └── Stringers.swift
│ │ │ └── NimbleObjectiveC/
│ │ │ ├── CurrentTestCaseTracker.h
│ │ │ ├── DSL.h
│ │ │ ├── DSL.m
│ │ │ ├── NMBExceptionCapture.h
│ │ │ ├── NMBExceptionCapture.m
│ │ │ ├── NMBStringify.h
│ │ │ ├── NMBStringify.m
│ │ │ └── XCTestObservationCenter+Register.m
│ │ ├── Pods.xcodeproj/
│ │ │ ├── project.pbxproj
│ │ │ ├── project.xcworkspace/
│ │ │ │ └── contents.xcworkspacedata
│ │ │ └── xcshareddata/
│ │ │ └── xcschemes/
│ │ │ ├── PersistentStorageSerializable-OSX.xcscheme
│ │ │ ├── PersistentStorageSerializable-iOS.xcscheme
│ │ │ ├── Reflection-OSX.xcscheme
│ │ │ └── Reflection-iOS.xcscheme
│ │ ├── Quick/
│ │ │ ├── LICENSE
│ │ │ ├── README.md
│ │ │ └── Sources/
│ │ │ ├── Quick/
│ │ │ │ ├── Callsite.swift
│ │ │ │ ├── Configuration/
│ │ │ │ │ └── Configuration.swift
│ │ │ │ ├── DSL/
│ │ │ │ │ ├── DSL.swift
│ │ │ │ │ └── World+DSL.swift
│ │ │ │ ├── ErrorUtility.swift
│ │ │ │ ├── Example.swift
│ │ │ │ ├── ExampleGroup.swift
│ │ │ │ ├── ExampleMetadata.swift
│ │ │ │ ├── Filter.swift
│ │ │ │ ├── Hooks/
│ │ │ │ │ ├── Closures.swift
│ │ │ │ │ ├── ExampleHooks.swift
│ │ │ │ │ ├── HooksPhase.swift
│ │ │ │ │ └── SuiteHooks.swift
│ │ │ │ ├── NSBundle+CurrentTestBundle.swift
│ │ │ │ ├── QuickSelectedTestSuiteBuilder.swift
│ │ │ │ ├── QuickTestSuite.swift
│ │ │ │ ├── URL+FileName.swift
│ │ │ │ └── World.swift
│ │ │ └── QuickObjectiveC/
│ │ │ ├── Configuration/
│ │ │ │ ├── QuickConfiguration.h
│ │ │ │ └── QuickConfiguration.m
│ │ │ ├── DSL/
│ │ │ │ ├── QCKDSL.h
│ │ │ │ ├── QCKDSL.m
│ │ │ │ └── World+DSL.h
│ │ │ ├── NSString+QCKSelectorName.h
│ │ │ ├── NSString+QCKSelectorName.m
│ │ │ ├── Quick.h
│ │ │ ├── QuickSpec.h
│ │ │ ├── QuickSpec.m
│ │ │ ├── World.h
│ │ │ └── XCTestSuite+QuickTestSuiteBuilder.m
│ │ ├── Reflection/
│ │ │ ├── LICENSE
│ │ │ ├── README.md
│ │ │ └── Sources/
│ │ │ └── Reflection/
│ │ │ ├── Advance.swift
│ │ │ ├── Any+Extensions.swift
│ │ │ ├── Array+Extensions.swift
│ │ │ ├── Construct.swift
│ │ │ ├── Get.swift
│ │ │ ├── Identity.swift
│ │ │ ├── MemoryProperties.swift
│ │ │ ├── Metadata+Class.swift
│ │ │ ├── Metadata+Kind.swift
│ │ │ ├── Metadata+Struct.swift
│ │ │ ├── Metadata+Tuple.swift
│ │ │ ├── Metadata.swift
│ │ │ ├── MetadataType.swift
│ │ │ ├── NominalType.swift
│ │ │ ├── NominalTypeDescriptor.swift
│ │ │ ├── PointerType.swift
│ │ │ ├── Properties.swift
│ │ │ ├── ReflectionError.swift
│ │ │ ├── RelativePointer.swift
│ │ │ ├── Set.swift
│ │ │ ├── Storage.swift
│ │ │ ├── UnsafePointer+Extensions.swift
│ │ │ └── ValueWitnessTable.swift
│ │ └── Target Support Files/
│ │ ├── Nimble/
│ │ │ ├── Info.plist
│ │ │ ├── Nimble-dummy.m
│ │ │ ├── Nimble-prefix.pch
│ │ │ ├── Nimble-umbrella.h
│ │ │ ├── Nimble.modulemap
│ │ │ └── Nimble.xcconfig
│ │ ├── PersistentStorageSerializable-OSX/
│ │ │ ├── Info.plist
│ │ │ ├── PersistentStorageSerializable-OSX-dummy.m
│ │ │ ├── PersistentStorageSerializable-OSX-prefix.pch
│ │ │ ├── PersistentStorageSerializable-OSX-umbrella.h
│ │ │ ├── PersistentStorageSerializable-OSX.modulemap
│ │ │ └── PersistentStorageSerializable-OSX.xcconfig
│ │ ├── PersistentStorageSerializable-iOS/
│ │ │ ├── Info.plist
│ │ │ ├── PersistentStorageSerializable-iOS-dummy.m
│ │ │ ├── PersistentStorageSerializable-iOS-prefix.pch
│ │ │ ├── PersistentStorageSerializable-iOS-umbrella.h
│ │ │ ├── PersistentStorageSerializable-iOS.modulemap
│ │ │ └── PersistentStorageSerializable-iOS.xcconfig
│ │ ├── Pods-PersistentStorageSerializable_MacExample/
│ │ │ ├── Info.plist
│ │ │ ├── Pods-PersistentStorageSerializable_MacExample-acknowledgements.markdown
│ │ │ ├── Pods-PersistentStorageSerializable_MacExample-acknowledgements.plist
│ │ │ ├── Pods-PersistentStorageSerializable_MacExample-dummy.m
│ │ │ ├── Pods-PersistentStorageSerializable_MacExample-frameworks.sh
│ │ │ ├── Pods-PersistentStorageSerializable_MacExample-resources.sh
│ │ │ ├── Pods-PersistentStorageSerializable_MacExample-umbrella.h
│ │ │ ├── Pods-PersistentStorageSerializable_MacExample.debug.xcconfig
│ │ │ ├── Pods-PersistentStorageSerializable_MacExample.modulemap
│ │ │ └── Pods-PersistentStorageSerializable_MacExample.release.xcconfig
│ │ ├── Pods-PersistentStorageSerializable_Tests/
│ │ │ ├── Info.plist
│ │ │ ├── Pods-PersistentStorageSerializable_Tests-acknowledgements.markdown
│ │ │ ├── Pods-PersistentStorageSerializable_Tests-acknowledgements.plist
│ │ │ ├── Pods-PersistentStorageSerializable_Tests-dummy.m
│ │ │ ├── Pods-PersistentStorageSerializable_Tests-frameworks.sh
│ │ │ ├── Pods-PersistentStorageSerializable_Tests-resources.sh
│ │ │ ├── Pods-PersistentStorageSerializable_Tests-umbrella.h
│ │ │ ├── Pods-PersistentStorageSerializable_Tests.debug.xcconfig
│ │ │ ├── Pods-PersistentStorageSerializable_Tests.modulemap
│ │ │ └── Pods-PersistentStorageSerializable_Tests.release.xcconfig
│ │ ├── Pods-PersistentStorageSerializable_iOSExample/
│ │ │ ├── Info.plist
│ │ │ ├── Pods-PersistentStorageSerializable_iOSExample-acknowledgements.markdown
│ │ │ ├── Pods-PersistentStorageSerializable_iOSExample-acknowledgements.plist
│ │ │ ├── Pods-PersistentStorageSerializable_iOSExample-dummy.m
│ │ │ ├── Pods-PersistentStorageSerializable_iOSExample-frameworks.sh
│ │ │ ├── Pods-PersistentStorageSerializable_iOSExample-resources.sh
│ │ │ ├── Pods-PersistentStorageSerializable_iOSExample-umbrella.h
│ │ │ ├── Pods-PersistentStorageSerializable_iOSExample.debug.xcconfig
│ │ │ ├── Pods-PersistentStorageSerializable_iOSExample.modulemap
│ │ │ └── Pods-PersistentStorageSerializable_iOSExample.release.xcconfig
│ │ ├── Quick/
│ │ │ ├── Info.plist
│ │ │ ├── Quick-dummy.m
│ │ │ ├── Quick-prefix.pch
│ │ │ ├── Quick-umbrella.h
│ │ │ ├── Quick.modulemap
│ │ │ └── Quick.xcconfig
│ │ ├── Reflection-OSX/
│ │ │ ├── Info.plist
│ │ │ ├── Reflection-OSX-dummy.m
│ │ │ ├── Reflection-OSX-prefix.pch
│ │ │ ├── Reflection-OSX-umbrella.h
│ │ │ ├── Reflection-OSX.modulemap
│ │ │ └── Reflection-OSX.xcconfig
│ │ └── Reflection-iOS/
│ │ ├── Info.plist
│ │ ├── Reflection-iOS-dummy.m
│ │ ├── Reflection-iOS-prefix.pch
│ │ ├── Reflection-iOS-umbrella.h
│ │ ├── Reflection-iOS.modulemap
│ │ └── Reflection-iOS.xcconfig
│ └── Tests/
│ ├── Car.plist
│ ├── Info.plist
│ ├── PersistentStorageMock.swift
│ ├── PersistentStorageSerializableTests.swift
│ └── SupportedSerializableTypeTests.swift
├── LICENSE
├── PersistentStorageSerializable/
│ ├── Assets/
│ │ └── .gitkeep
│ └── Classes/
│ ├── .gitkeep
│ ├── PersistentStorage.swift
│ ├── PersistentStorageSerializable.swift
│ ├── PlistStorage.swift
│ ├── PropertiesIteration.swift
│ ├── SupportedSerializableType.swift
│ ├── SwiftTryCatch.h
│ ├── SwiftTryCatch.m
│ └── UserDefaultsStorage.swift
├── PersistentStorageSerializable.podspec
└── README.md
================================================
FILE CONTENTS
================================================
================================================
FILE: .gitignore
================================================
# OS X
.DS_Store
# Xcode
build/
*.pbxuser
!default.pbxuser
*.mode1v3
!default.mode1v3
*.mode2v3
!default.mode2v3
*.perspectivev3
!default.perspectivev3
xcuserdata/
*.xccheckout
profile
*.moved-aside
DerivedData
*.hmap
*.ipa
# Bundler
.bundle
Carthage
# We recommend against adding the Pods directory to your .gitignore. However
# you should judge for yourself, the pros and cons are mentioned at:
# http://guides.cocoapods.org/using/using-cocoapods.html#should-i-ignore-the-pods-directory-in-source-control
#
# Note: if you ignore the Pods directory, make sure to uncomment
# `pod install` in .travis.yml
#
!Pods/
Pods/*
!Pods/Pods.xcodeproj/
Podfile.lock
================================================
FILE: .swift-version
================================================
3.1
================================================
FILE: .travis.yml
================================================
# references:
# * http://www.objc.io/issue-6/travis-ci.html
# * https://github.com/supermarin/xcpretty#usage
osx_image: xcode8.3
language: objective-c
# cache: cocoapods
# podfile: Example/Podfile
# before_install:
# - gem install cocoapods # Since Travis is not always on latest version
# - pod install --project-directory=Example
before_install: cd Example && pod install && cd -
install:
- gem install xcpretty --no-rdoc --no-ri --no-document --quiet
script:
- set -o pipefail && xcodebuild test -workspace Example/PersistentStorageSerializable.xcworkspace -scheme PersistentStorageSerializable-Tests -sdk iphonesimulator10.0 -destination 'platform=iOS Simulator,name=iPhone SE,OS=10.0' ONLY_ACTIVE_ARCH=NO | xcpretty
- pod lib lint
================================================
FILE: Cartfile
================================================
github "Zewo/Reflection" ~> 0.14
================================================
FILE: Cartfile.private
================================================
github "jspahrsummers/xcconfigs" "2055f18"
================================================
FILE: Cartfile.resolved
================================================
github "Zewo/Reflection" "0.14.3"
github "jspahrsummers/xcconfigs" "2055f18efbe18e77408f7f43947f7ad92b2d4ff0"
================================================
FILE: Example/ExamplesOfUsage.playground/Contents.swift
================================================
//: # PersistentStorageSerializable library.
import UIKit
import PersistentStorageSerializable
/*:
## Custom persistent storage
Usually, we use `UserDefaultsStorage` class provided by the library to serialize type values with the system user defaults.
We can define a custom persistent storage by adopting `PersistentStorage` protocol. Let's define a memory storage and use it instead `UserDefaultsStorage` for demonstration purposes.
*/
final class MemoryStorage {
var dictionary = [String : Any]()
}
extension MemoryStorage: PersistentStorage {
func beginTransaction() throws {}
func register(defaultValues: [String : Any]) {}
func get(valueOf key: String) -> Any? {
return dictionary[key]
}
func set(value: Any?, for key: String) throws {
dictionary[key] = value
}
func finishTransaction() throws {}
}
let memoryStorage = MemoryStorage()
/*:
---
## Serializing a struct type
Declare struct type for your user preferences and adopt `PersistentStorageSerializable` protocol.
*/
struct UserPreferences: PersistentStorageSerializable {
var myString = "Hello"
var myBool = false
// MARK: Adopt PersistentStorageSerializable
var persistentStorage: PersistentStorage!
var persistentStorageKeyPrefix: String! = "UserPreferences"
}
memoryStorage.dictionary
var preferences = try! UserPreferences(from: memoryStorage)
preferences.myString = "Greetings"
preferences.myBool = true
try! preferences.persist()
//: Preferences values are persisted in storage.
memoryStorage.dictionary
/*:
---
## Serializing a class type
If we use classes as a data structure for settings then we can use a custom subclass to adopt serialization functionality.
*/
class Serializable: PersistentStorageSerializable {
var persistentStorage: PersistentStorage!
var persistentStorageKeyPrefix: String!
required init() {}
}
class AppSettings: Serializable {
var myUInt = UInt.max
var myDouble = 125.76
//: - We can use only plist types and collections of such types for properties. If we have to persist some other type we should convert it to plist one as shown below.
var _myColor = [Float](arrayLiteral: 0, 0, 0, 0)
var myColor: UIColor {
get {
return UIColor(colorLiteralRed: _myColor[0], green: _myColor[1], blue: _myColor[2], alpha: _myColor[3])
}
set {
var r: CGFloat = 0, g: CGFloat = 0, b: CGFloat = 0, a: CGFloat = 0
newValue.getRed(&r, green: &g, blue: &b, alpha: &a)
_myColor = [Float(r), Float(g), Float(b), Float(a)]
}
}
}
var settings = try! AppSettings(from: memoryStorage, keyPrefix: "AppSettings")
settings.myColor = UIColor.red
try! settings.persist()
//: The memory storage contains values of both `preferences` and `settings` instances.
memoryStorage.dictionary
/*:
---
## Reading data stored by the previous version of the app
When you have some data persisted in user defaults by the previous version of the app and want `PersistentStorageSerializable` library to read that data into your structure you need to provide a mapping between properties names and User Defaults keys.
Say we have our data persisted in storage.
*/
memoryStorage.dictionary.removeAll()
memoryStorage.dictionary["oldGoogTitle"] = "Superhero"
memoryStorage.dictionary["well.persisted.option"] = true
memoryStorage.dictionary
//: We want those to be serialized with the following class.
final class ApplicationConfiguration: PersistentStorageSerializable {
var title = ""
var showIntro = false
// MARK: Adopt PersistentStorageSerializable
var persistentStorage: PersistentStorage!
var persistentStorageKeyPrefix: String!
}
//: Provide key mapping by overloading `persistentStorageKey(for:)` function.
extension ApplicationConfiguration {
func persistentStorageKey(for propertyName: String) -> String {
let keyMap = ["title" : "oldGoogTitle", "showIntro" : "well.persisted.option"]
return keyMap[propertyName]!
}
}
//: Now we can load data persisted in the storage.
let configuration = try! ApplicationConfiguration(from: memoryStorage, keyPrefix: "")
configuration.title
configuration.showIntro
//: ### Same with a custom subclass
class SerializableWithKeyMap: PersistentStorageSerializable {
var persistentStorage: PersistentStorage!
var persistentStorageKeyPrefix: String!
required init() {}
var keyMap: [String : String]!
func persistentStorageKey(for propertyName: String) -> String {
return keyMap[propertyName]!
}
}
class ApplicationConfiguration2: SerializableWithKeyMap {
var title = ""
var showIntro = false
required init() {
super.init()
keyMap = ["title" : "oldGoogTitle", "showIntro" : "well.persisted.option"]
}
}
let configuration2 = try! ApplicationConfiguration2(from: memoryStorage, keyPrefix: "")
configuration2.title
configuration2.showIntro
/*:
---
*/
================================================
FILE: Example/ExamplesOfUsage.playground/contents.xcplayground
================================================
================================================
FILE: Example/ExamplesOfUsage.playground/timeline.xctimeline
================================================
================================================
FILE: Example/PersistentStorageSerializable/AppDelegate.swift
================================================
//
// AppDelegate.swift
// PersistentStorageSerializable
//
// Created by IvanRublev on 04/05/2017.
// Copyright (c) 2017 IvanRublev. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
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 throttle down OpenGL ES frame rates. 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.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
================================================
FILE: Example/PersistentStorageSerializable/Base.lproj/LaunchScreen.xib
================================================
================================================
FILE: Example/PersistentStorageSerializable/Base.lproj/Main.storyboard
================================================
================================================
FILE: Example/PersistentStorageSerializable/Images.xcassets/AppIcon.appiconset/Contents.json
================================================
{
"images" : [
{
"idiom" : "iphone",
"size" : "29x29",
"scale" : "2x"
},
{
"idiom" : "iphone",
"size" : "29x29",
"scale" : "3x"
},
{
"idiom" : "iphone",
"size" : "40x40",
"scale" : "2x"
},
{
"idiom" : "iphone",
"size" : "40x40",
"scale" : "3x"
},
{
"idiom" : "iphone",
"size" : "60x60",
"scale" : "2x"
},
{
"idiom" : "iphone",
"size" : "60x60",
"scale" : "3x"
}
],
"info" : {
"version" : 1,
"author" : "xcode"
}
}
================================================
FILE: Example/PersistentStorageSerializable/Info.plist
================================================
CFBundleDevelopmentRegion
en
CFBundleExecutable
$(EXECUTABLE_NAME)
CFBundleIdentifier
$(PRODUCT_BUNDLE_IDENTIFIER)
CFBundleInfoDictionaryVersion
6.0
CFBundleName
$(PRODUCT_NAME)
CFBundlePackageType
APPL
CFBundleShortVersionString
1.0
CFBundleSignature
????
CFBundleVersion
1
LSRequiresIPhoneOS
UILaunchStoryboardName
LaunchScreen
UIMainStoryboardFile
Main
UIRequiredDeviceCapabilities
armv7
UISupportedInterfaceOrientations
UIInterfaceOrientationPortrait
================================================
FILE: Example/PersistentStorageSerializable/Settings.swift
================================================
//
// Settings.swift
// PersistentStorageSerializable
//
// Created by Ivan Rublev on 4/5/17.
// Copyright © 2017 CocoaPods. All rights reserved.
//
import Foundation
import PersistentStorageSerializable
struct Settings: PersistentStorageSerializable {
var flag = false
var title = ""
var number = 1
// MARK: Adopt PersistentStorageSerializable
var persistentStorage: PersistentStorage!
var persistentStorageKeyPrefix: String!
}
================================================
FILE: Example/PersistentStorageSerializable/ViewController.swift
================================================
//
// ViewController.swift
// PersistentStorageSerializable
//
// Created by IvanRublev on 04/05/2017.
// Copyright (c) 2017 IvanRublev. All rights reserved.
//
import UIKit
import PersistentStorageSerializable
class ViewController: UIViewController {
@IBOutlet var flagSwitch: UISwitch!
@IBOutlet var textField: UITextField!
@IBOutlet var numberStepper: UIStepper!
@IBOutlet var numberLabel: UILabel!
@IBOutlet var userDefaultsLabel: UILabel!
var settings: Settings!
override func viewDidLoad() {
super.viewDidLoad()
load(0)
}
func updateViews() {
flagSwitch.isOn = settings.flag
textField.text = settings.title
numberStepper.value = Double(settings.number)
numberLabel.text = String(Int(numberStepper.value))
userDefaultsLabel.text = try! String(describing: settings.persistedDictionaryRepresentation())
}
}
// MARK: - Input controls actions
extension ViewController {
@IBAction func updateSettings(_ sender: Any) {
settings.flag = flagSwitch.isOn
settings.title = textField.text ?? ""
settings.number = Int(numberStepper.value)
updateViews()
}
@IBAction func donePressed(_ sender: Any) {
textField.resignFirstResponder()
}
}
// MARK: - Buttons actions
extension ViewController {
@IBAction func load(_ sender: Any) {
settings = try! Settings(from: UserDefaultsStorage.standard, keyPrefix: "Settings")
updateViews()
}
@IBAction func save(_ sender: Any) {
try! settings.persist()
updateViews()
}
@IBAction func reset(_ sender: Any) {
try! settings.removeFromPersistentStorage()
updateViews()
}
}
================================================
FILE: Example/PersistentStorageSerializable.xcodeproj/project.pbxproj
================================================
// !$*UTF8*$!
{
archiveVersion = 1;
classes = {
};
objectVersion = 46;
objects = {
/* Begin PBXBuildFile section */
607FACD61AFB9204008FA782 /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 607FACD51AFB9204008FA782 /* AppDelegate.swift */; };
607FACD81AFB9204008FA782 /* ViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 607FACD71AFB9204008FA782 /* ViewController.swift */; };
607FACDB1AFB9204008FA782 /* Main.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 607FACD91AFB9204008FA782 /* Main.storyboard */; };
607FACDD1AFB9204008FA782 /* Images.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 607FACDC1AFB9204008FA782 /* Images.xcassets */; };
607FACE01AFB9204008FA782 /* LaunchScreen.xib in Resources */ = {isa = PBXBuildFile; fileRef = 607FACDE1AFB9204008FA782 /* LaunchScreen.xib */; };
607FACEC1AFB9204008FA782 /* PersistentStorageSerializableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 607FACEB1AFB9204008FA782 /* PersistentStorageSerializableTests.swift */; };
80E924A82C6F4D136EF6DAFB /* Pods_PersistentStorageSerializable_iOSExample.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 095426B6186FB283A8442B6E /* Pods_PersistentStorageSerializable_iOSExample.framework */; };
98D5D52F222783CA20C2F8FD /* Pods_PersistentStorageSerializable_Tests.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = C6F0D1E550D38F1ACE0CFCF6 /* Pods_PersistentStorageSerializable_Tests.framework */; };
AB2E65E91E97E506009A8531 /* Car.plist in Resources */ = {isa = PBXBuildFile; fileRef = AB2E65E81E97E506009A8531 /* Car.plist */; };
AB6AC3AF1E950D5300F735CB /* PersistentStorageMock.swift in Sources */ = {isa = PBXBuildFile; fileRef = AB6AC3AD1E950C5E00F735CB /* PersistentStorageMock.swift */; };
AB6AC3B61E95513E00F735CB /* Settings.swift in Sources */ = {isa = PBXBuildFile; fileRef = AB6AC3B51E95513E00F735CB /* Settings.swift */; };
AB6AC3C01E9680AE00F735CB /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = AB6AC3BF1E9680AE00F735CB /* AppDelegate.swift */; };
AB6AC3C21E9680AE00F735CB /* ViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = AB6AC3C11E9680AE00F735CB /* ViewController.swift */; };
AB6AC3C41E9680AE00F735CB /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = AB6AC3C31E9680AE00F735CB /* Assets.xcassets */; };
AB6AC3C71E9680AE00F735CB /* Main.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = AB6AC3C51E9680AE00F735CB /* Main.storyboard */; };
AB6AC3CD1E96819C00F735CB /* AppSettings.swift in Sources */ = {isa = PBXBuildFile; fileRef = AB6AC3CC1E96819C00F735CB /* AppSettings.swift */; };
AB76415C1E97CD57007279BE /* SupportedSerializableTypeTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = AB76415A1E97CD54007279BE /* SupportedSerializableTypeTests.swift */; };
B057D67654FF5F791A3E93A6 /* Pods_PersistentStorageSerializable_MacExample.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = B107F7FEBC35A8A1C3631674 /* Pods_PersistentStorageSerializable_MacExample.framework */; };
/* End PBXBuildFile section */
/* Begin PBXFileReference section */
095426B6186FB283A8442B6E /* Pods_PersistentStorageSerializable_iOSExample.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_PersistentStorageSerializable_iOSExample.framework; sourceTree = BUILT_PRODUCTS_DIR; };
1430E68C73DA958AEE435B2B /* Pods-PersistentStorageSerializable_iOSExample.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-PersistentStorageSerializable_iOSExample.debug.xcconfig"; path = "Pods/Target Support Files/Pods-PersistentStorageSerializable_iOSExample/Pods-PersistentStorageSerializable_iOSExample.debug.xcconfig"; sourceTree = ""; };
2588AA89C5187E3CEA89DD6E /* Pods-PersistentStorageSerializable_iOSExample.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-PersistentStorageSerializable_iOSExample.release.xcconfig"; path = "Pods/Target Support Files/Pods-PersistentStorageSerializable_iOSExample/Pods-PersistentStorageSerializable_iOSExample.release.xcconfig"; sourceTree = ""; };
410ED040FF5FC9E233E71DA9 /* Pods-PersistentStorageSerializable_MacExample.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-PersistentStorageSerializable_MacExample.debug.xcconfig"; path = "Pods/Target Support Files/Pods-PersistentStorageSerializable_MacExample/Pods-PersistentStorageSerializable_MacExample.debug.xcconfig"; sourceTree = ""; };
607FACD01AFB9204008FA782 /* PersistentStorageSerializable_iOSExample.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = PersistentStorageSerializable_iOSExample.app; sourceTree = BUILT_PRODUCTS_DIR; };
607FACD41AFB9204008FA782 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; };
607FACD51AFB9204008FA782 /* AppDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AppDelegate.swift; sourceTree = ""; };
607FACD71AFB9204008FA782 /* ViewController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ViewController.swift; sourceTree = ""; };
607FACDA1AFB9204008FA782 /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/Main.storyboard; sourceTree = ""; };
607FACDC1AFB9204008FA782 /* Images.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Images.xcassets; sourceTree = ""; };
607FACDF1AFB9204008FA782 /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.xib; name = Base; path = Base.lproj/LaunchScreen.xib; sourceTree = ""; };
607FACE51AFB9204008FA782 /* PersistentStorageSerializable_Tests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = PersistentStorageSerializable_Tests.xctest; sourceTree = BUILT_PRODUCTS_DIR; };
607FACEA1AFB9204008FA782 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; };
607FACEB1AFB9204008FA782 /* PersistentStorageSerializableTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PersistentStorageSerializableTests.swift; sourceTree = ""; };
6C1240DEA24D615B61502A9B /* README.md */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = net.daringfireball.markdown; name = README.md; path = ../README.md; sourceTree = ""; };
77A4C7A9C48761BFB96E9009 /* LICENSE */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text; name = LICENSE; path = ../LICENSE; sourceTree = ""; };
AB2E65E81E97E506009A8531 /* Car.plist */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.xml; path = Car.plist; sourceTree = ""; };
AB2E65EA1E98C6E2009A8531 /* ExamplesOfUsage.playground */ = {isa = PBXFileReference; lastKnownFileType = file.playground; path = ExamplesOfUsage.playground; sourceTree = ""; };
AB6AC3AD1E950C5E00F735CB /* PersistentStorageMock.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PersistentStorageMock.swift; sourceTree = ""; };
AB6AC3B51E95513E00F735CB /* Settings.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Settings.swift; sourceTree = ""; };
AB6AC3BD1E9680AE00F735CB /* PersistentStorageSerializable_MacExample.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = PersistentStorageSerializable_MacExample.app; sourceTree = BUILT_PRODUCTS_DIR; };
AB6AC3BF1E9680AE00F735CB /* AppDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AppDelegate.swift; sourceTree = ""; };
AB6AC3C11E9680AE00F735CB /* ViewController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ViewController.swift; sourceTree = ""; };
AB6AC3C31E9680AE00F735CB /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Assets.xcassets; sourceTree = ""; };
AB6AC3C61E9680AE00F735CB /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/Main.storyboard; sourceTree = ""; };
AB6AC3C81E9680AE00F735CB /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; };
AB6AC3CC1E96819C00F735CB /* AppSettings.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AppSettings.swift; sourceTree = ""; };
AB76415A1E97CD54007279BE /* SupportedSerializableTypeTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SupportedSerializableTypeTests.swift; sourceTree = ""; };
B107F7FEBC35A8A1C3631674 /* Pods_PersistentStorageSerializable_MacExample.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_PersistentStorageSerializable_MacExample.framework; sourceTree = BUILT_PRODUCTS_DIR; };
C6F0D1E550D38F1ACE0CFCF6 /* Pods_PersistentStorageSerializable_Tests.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_PersistentStorageSerializable_Tests.framework; sourceTree = BUILT_PRODUCTS_DIR; };
D0F7B87E59D17DF5674E4175 /* Pods-PersistentStorageSerializable_Tests.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-PersistentStorageSerializable_Tests.release.xcconfig"; path = "Pods/Target Support Files/Pods-PersistentStorageSerializable_Tests/Pods-PersistentStorageSerializable_Tests.release.xcconfig"; sourceTree = ""; };
D61EE2F47F5FCAFA282DF7DD /* Pods-PersistentStorageSerializable_Tests.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-PersistentStorageSerializable_Tests.debug.xcconfig"; path = "Pods/Target Support Files/Pods-PersistentStorageSerializable_Tests/Pods-PersistentStorageSerializable_Tests.debug.xcconfig"; sourceTree = ""; };
DDAF776488859913631134E6 /* PersistentStorageSerializable.podspec */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text; name = PersistentStorageSerializable.podspec; path = ../PersistentStorageSerializable.podspec; sourceTree = ""; };
E1CCB00B943B4FE159A27022 /* Pods-PersistentStorageSerializable_MacExample.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-PersistentStorageSerializable_MacExample.release.xcconfig"; path = "Pods/Target Support Files/Pods-PersistentStorageSerializable_MacExample/Pods-PersistentStorageSerializable_MacExample.release.xcconfig"; sourceTree = ""; };
/* End PBXFileReference section */
/* Begin PBXFrameworksBuildPhase section */
607FACCD1AFB9204008FA782 /* Frameworks */ = {
isa = PBXFrameworksBuildPhase;
buildActionMask = 2147483647;
files = (
80E924A82C6F4D136EF6DAFB /* Pods_PersistentStorageSerializable_iOSExample.framework in Frameworks */,
);
runOnlyForDeploymentPostprocessing = 0;
};
607FACE21AFB9204008FA782 /* Frameworks */ = {
isa = PBXFrameworksBuildPhase;
buildActionMask = 2147483647;
files = (
98D5D52F222783CA20C2F8FD /* Pods_PersistentStorageSerializable_Tests.framework in Frameworks */,
);
runOnlyForDeploymentPostprocessing = 0;
};
AB6AC3BA1E9680AE00F735CB /* Frameworks */ = {
isa = PBXFrameworksBuildPhase;
buildActionMask = 2147483647;
files = (
B057D67654FF5F791A3E93A6 /* Pods_PersistentStorageSerializable_MacExample.framework in Frameworks */,
);
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXFrameworksBuildPhase section */
/* Begin PBXGroup section */
607FACC71AFB9204008FA782 = {
isa = PBXGroup;
children = (
AB2E65EA1E98C6E2009A8531 /* ExamplesOfUsage.playground */,
607FACF51AFB993E008FA782 /* Podspec Metadata */,
607FACD21AFB9204008FA782 /* iOS Example for PersistentStorageSerializable */,
AB6AC3BE1E9680AE00F735CB /* macOS Example for PersistentStorageSerializable */,
607FACE81AFB9204008FA782 /* Tests */,
607FACD11AFB9204008FA782 /* Products */,
D03860B7B98A1F763B5BB4CC /* Pods */,
9A2B6143D980D7AC4AA0886D /* Frameworks */,
);
sourceTree = "";
};
607FACD11AFB9204008FA782 /* Products */ = {
isa = PBXGroup;
children = (
607FACD01AFB9204008FA782 /* PersistentStorageSerializable_iOSExample.app */,
607FACE51AFB9204008FA782 /* PersistentStorageSerializable_Tests.xctest */,
AB6AC3BD1E9680AE00F735CB /* PersistentStorageSerializable_MacExample.app */,
);
name = Products;
sourceTree = "";
};
607FACD21AFB9204008FA782 /* iOS Example for PersistentStorageSerializable */ = {
isa = PBXGroup;
children = (
607FACD51AFB9204008FA782 /* AppDelegate.swift */,
607FACD71AFB9204008FA782 /* ViewController.swift */,
AB6AC3B51E95513E00F735CB /* Settings.swift */,
607FACD91AFB9204008FA782 /* Main.storyboard */,
607FACDC1AFB9204008FA782 /* Images.xcassets */,
607FACDE1AFB9204008FA782 /* LaunchScreen.xib */,
607FACD31AFB9204008FA782 /* Supporting Files */,
);
name = "iOS Example for PersistentStorageSerializable";
path = PersistentStorageSerializable;
sourceTree = "";
};
607FACD31AFB9204008FA782 /* Supporting Files */ = {
isa = PBXGroup;
children = (
607FACD41AFB9204008FA782 /* Info.plist */,
);
name = "Supporting Files";
sourceTree = "";
};
607FACE81AFB9204008FA782 /* Tests */ = {
isa = PBXGroup;
children = (
607FACEB1AFB9204008FA782 /* PersistentStorageSerializableTests.swift */,
AB76415A1E97CD54007279BE /* SupportedSerializableTypeTests.swift */,
AB6AC3AD1E950C5E00F735CB /* PersistentStorageMock.swift */,
AB2E65E81E97E506009A8531 /* Car.plist */,
607FACE91AFB9204008FA782 /* Supporting Files */,
);
path = Tests;
sourceTree = "";
};
607FACE91AFB9204008FA782 /* Supporting Files */ = {
isa = PBXGroup;
children = (
607FACEA1AFB9204008FA782 /* Info.plist */,
);
name = "Supporting Files";
sourceTree = "";
};
607FACF51AFB993E008FA782 /* Podspec Metadata */ = {
isa = PBXGroup;
children = (
DDAF776488859913631134E6 /* PersistentStorageSerializable.podspec */,
6C1240DEA24D615B61502A9B /* README.md */,
77A4C7A9C48761BFB96E9009 /* LICENSE */,
);
name = "Podspec Metadata";
sourceTree = "";
};
9A2B6143D980D7AC4AA0886D /* Frameworks */ = {
isa = PBXGroup;
children = (
C6F0D1E550D38F1ACE0CFCF6 /* Pods_PersistentStorageSerializable_Tests.framework */,
B107F7FEBC35A8A1C3631674 /* Pods_PersistentStorageSerializable_MacExample.framework */,
095426B6186FB283A8442B6E /* Pods_PersistentStorageSerializable_iOSExample.framework */,
);
name = Frameworks;
sourceTree = "";
};
AB6AC3BE1E9680AE00F735CB /* macOS Example for PersistentStorageSerializable */ = {
isa = PBXGroup;
children = (
AB6AC3BF1E9680AE00F735CB /* AppDelegate.swift */,
AB6AC3C11E9680AE00F735CB /* ViewController.swift */,
AB6AC3CC1E96819C00F735CB /* AppSettings.swift */,
AB6AC3C31E9680AE00F735CB /* Assets.xcassets */,
AB6AC3C51E9680AE00F735CB /* Main.storyboard */,
AB6AC3C81E9680AE00F735CB /* Info.plist */,
);
name = "macOS Example for PersistentStorageSerializable";
path = PersistentStorageSerializable_MacExample;
sourceTree = "";
};
D03860B7B98A1F763B5BB4CC /* Pods */ = {
isa = PBXGroup;
children = (
D61EE2F47F5FCAFA282DF7DD /* Pods-PersistentStorageSerializable_Tests.debug.xcconfig */,
D0F7B87E59D17DF5674E4175 /* Pods-PersistentStorageSerializable_Tests.release.xcconfig */,
410ED040FF5FC9E233E71DA9 /* Pods-PersistentStorageSerializable_MacExample.debug.xcconfig */,
E1CCB00B943B4FE159A27022 /* Pods-PersistentStorageSerializable_MacExample.release.xcconfig */,
1430E68C73DA958AEE435B2B /* Pods-PersistentStorageSerializable_iOSExample.debug.xcconfig */,
2588AA89C5187E3CEA89DD6E /* Pods-PersistentStorageSerializable_iOSExample.release.xcconfig */,
);
name = Pods;
sourceTree = "";
};
/* End PBXGroup section */
/* Begin PBXNativeTarget section */
607FACCF1AFB9204008FA782 /* PersistentStorageSerializable_iOSExample */ = {
isa = PBXNativeTarget;
buildConfigurationList = 607FACEF1AFB9204008FA782 /* Build configuration list for PBXNativeTarget "PersistentStorageSerializable_iOSExample" */;
buildPhases = (
66755897DE9E279750DF07F9 /* [CP] Check Pods Manifest.lock */,
607FACCC1AFB9204008FA782 /* Sources */,
607FACCD1AFB9204008FA782 /* Frameworks */,
607FACCE1AFB9204008FA782 /* Resources */,
236D08738204335D7A43DEF1 /* [CP] Embed Pods Frameworks */,
27432223C0DD7682AC675BDF /* [CP] Copy Pods Resources */,
);
buildRules = (
);
dependencies = (
);
name = PersistentStorageSerializable_iOSExample;
productName = PersistentStorageSerializable;
productReference = 607FACD01AFB9204008FA782 /* PersistentStorageSerializable_iOSExample.app */;
productType = "com.apple.product-type.application";
};
607FACE41AFB9204008FA782 /* PersistentStorageSerializable_Tests */ = {
isa = PBXNativeTarget;
buildConfigurationList = 607FACF21AFB9204008FA782 /* Build configuration list for PBXNativeTarget "PersistentStorageSerializable_Tests" */;
buildPhases = (
82A9B6DE26A7AA265E46262D /* [CP] Check Pods Manifest.lock */,
607FACE11AFB9204008FA782 /* Sources */,
607FACE21AFB9204008FA782 /* Frameworks */,
607FACE31AFB9204008FA782 /* Resources */,
33157687998EEACBC2651DA7 /* [CP] Embed Pods Frameworks */,
389211693118A2DFD7B74393 /* [CP] Copy Pods Resources */,
);
buildRules = (
);
dependencies = (
);
name = PersistentStorageSerializable_Tests;
productName = Tests;
productReference = 607FACE51AFB9204008FA782 /* PersistentStorageSerializable_Tests.xctest */;
productType = "com.apple.product-type.bundle.unit-test";
};
AB6AC3BC1E9680AE00F735CB /* PersistentStorageSerializable_MacExample */ = {
isa = PBXNativeTarget;
buildConfigurationList = AB6AC3CB1E9680AE00F735CB /* Build configuration list for PBXNativeTarget "PersistentStorageSerializable_MacExample" */;
buildPhases = (
83656AD5AD449BE38007FB5D /* [CP] Check Pods Manifest.lock */,
AB6AC3B91E9680AE00F735CB /* Sources */,
AB6AC3BA1E9680AE00F735CB /* Frameworks */,
AB6AC3BB1E9680AE00F735CB /* Resources */,
BB48EDF876C9F1A254792873 /* [CP] Embed Pods Frameworks */,
69E40D21BFAF5A6983432BE8 /* [CP] Copy Pods Resources */,
);
buildRules = (
);
dependencies = (
);
name = PersistentStorageSerializable_MacExample;
productName = PersistentStorageSerializable_MacExample;
productReference = AB6AC3BD1E9680AE00F735CB /* PersistentStorageSerializable_MacExample.app */;
productType = "com.apple.product-type.application";
};
/* End PBXNativeTarget section */
/* Begin PBXProject section */
607FACC81AFB9204008FA782 /* Project object */ = {
isa = PBXProject;
attributes = {
LastSwiftUpdateCheck = 0830;
LastUpgradeCheck = 0830;
ORGANIZATIONNAME = CocoaPods;
TargetAttributes = {
607FACCF1AFB9204008FA782 = {
CreatedOnToolsVersion = 6.3.1;
LastSwiftMigration = 0820;
};
607FACE41AFB9204008FA782 = {
CreatedOnToolsVersion = 6.3.1;
LastSwiftMigration = 0820;
};
AB6AC3BC1E9680AE00F735CB = {
CreatedOnToolsVersion = 8.3;
ProvisioningStyle = Automatic;
};
};
};
buildConfigurationList = 607FACCB1AFB9204008FA782 /* Build configuration list for PBXProject "PersistentStorageSerializable" */;
compatibilityVersion = "Xcode 3.2";
developmentRegion = English;
hasScannedForEncodings = 0;
knownRegions = (
en,
Base,
);
mainGroup = 607FACC71AFB9204008FA782;
productRefGroup = 607FACD11AFB9204008FA782 /* Products */;
projectDirPath = "";
projectRoot = "";
targets = (
607FACCF1AFB9204008FA782 /* PersistentStorageSerializable_iOSExample */,
AB6AC3BC1E9680AE00F735CB /* PersistentStorageSerializable_MacExample */,
607FACE41AFB9204008FA782 /* PersistentStorageSerializable_Tests */,
);
};
/* End PBXProject section */
/* Begin PBXResourcesBuildPhase section */
607FACCE1AFB9204008FA782 /* Resources */ = {
isa = PBXResourcesBuildPhase;
buildActionMask = 2147483647;
files = (
607FACDB1AFB9204008FA782 /* Main.storyboard in Resources */,
607FACE01AFB9204008FA782 /* LaunchScreen.xib in Resources */,
607FACDD1AFB9204008FA782 /* Images.xcassets in Resources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
607FACE31AFB9204008FA782 /* Resources */ = {
isa = PBXResourcesBuildPhase;
buildActionMask = 2147483647;
files = (
AB2E65E91E97E506009A8531 /* Car.plist in Resources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
AB6AC3BB1E9680AE00F735CB /* Resources */ = {
isa = PBXResourcesBuildPhase;
buildActionMask = 2147483647;
files = (
AB6AC3C41E9680AE00F735CB /* Assets.xcassets in Resources */,
AB6AC3C71E9680AE00F735CB /* Main.storyboard in Resources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXResourcesBuildPhase section */
/* Begin PBXShellScriptBuildPhase section */
236D08738204335D7A43DEF1 /* [CP] Embed Pods Frameworks */ = {
isa = PBXShellScriptBuildPhase;
buildActionMask = 2147483647;
files = (
);
inputPaths = (
);
name = "[CP] Embed Pods Frameworks";
outputPaths = (
);
runOnlyForDeploymentPostprocessing = 0;
shellPath = /bin/sh;
shellScript = "\"${SRCROOT}/Pods/Target Support Files/Pods-PersistentStorageSerializable_iOSExample/Pods-PersistentStorageSerializable_iOSExample-frameworks.sh\"\n";
showEnvVarsInLog = 0;
};
27432223C0DD7682AC675BDF /* [CP] Copy Pods Resources */ = {
isa = PBXShellScriptBuildPhase;
buildActionMask = 2147483647;
files = (
);
inputPaths = (
);
name = "[CP] Copy Pods Resources";
outputPaths = (
);
runOnlyForDeploymentPostprocessing = 0;
shellPath = /bin/sh;
shellScript = "\"${SRCROOT}/Pods/Target Support Files/Pods-PersistentStorageSerializable_iOSExample/Pods-PersistentStorageSerializable_iOSExample-resources.sh\"\n";
showEnvVarsInLog = 0;
};
33157687998EEACBC2651DA7 /* [CP] Embed Pods Frameworks */ = {
isa = PBXShellScriptBuildPhase;
buildActionMask = 2147483647;
files = (
);
inputPaths = (
);
name = "[CP] Embed Pods Frameworks";
outputPaths = (
);
runOnlyForDeploymentPostprocessing = 0;
shellPath = /bin/sh;
shellScript = "\"${SRCROOT}/Pods/Target Support Files/Pods-PersistentStorageSerializable_Tests/Pods-PersistentStorageSerializable_Tests-frameworks.sh\"\n";
showEnvVarsInLog = 0;
};
389211693118A2DFD7B74393 /* [CP] Copy Pods Resources */ = {
isa = PBXShellScriptBuildPhase;
buildActionMask = 2147483647;
files = (
);
inputPaths = (
);
name = "[CP] Copy Pods Resources";
outputPaths = (
);
runOnlyForDeploymentPostprocessing = 0;
shellPath = /bin/sh;
shellScript = "\"${SRCROOT}/Pods/Target Support Files/Pods-PersistentStorageSerializable_Tests/Pods-PersistentStorageSerializable_Tests-resources.sh\"\n";
showEnvVarsInLog = 0;
};
66755897DE9E279750DF07F9 /* [CP] Check Pods Manifest.lock */ = {
isa = PBXShellScriptBuildPhase;
buildActionMask = 2147483647;
files = (
);
inputPaths = (
);
name = "[CP] Check Pods Manifest.lock";
outputPaths = (
);
runOnlyForDeploymentPostprocessing = 0;
shellPath = /bin/sh;
shellScript = "diff \"${PODS_ROOT}/../Podfile.lock\" \"${PODS_ROOT}/Manifest.lock\" > /dev/null\nif [ $? != 0 ] ; then\n # print error to STDERR\n echo \"error: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.\" >&2\n exit 1\nfi\n";
showEnvVarsInLog = 0;
};
69E40D21BFAF5A6983432BE8 /* [CP] Copy Pods Resources */ = {
isa = PBXShellScriptBuildPhase;
buildActionMask = 2147483647;
files = (
);
inputPaths = (
);
name = "[CP] Copy Pods Resources";
outputPaths = (
);
runOnlyForDeploymentPostprocessing = 0;
shellPath = /bin/sh;
shellScript = "\"${SRCROOT}/Pods/Target Support Files/Pods-PersistentStorageSerializable_MacExample/Pods-PersistentStorageSerializable_MacExample-resources.sh\"\n";
showEnvVarsInLog = 0;
};
82A9B6DE26A7AA265E46262D /* [CP] Check Pods Manifest.lock */ = {
isa = PBXShellScriptBuildPhase;
buildActionMask = 2147483647;
files = (
);
inputPaths = (
);
name = "[CP] Check Pods Manifest.lock";
outputPaths = (
);
runOnlyForDeploymentPostprocessing = 0;
shellPath = /bin/sh;
shellScript = "diff \"${PODS_ROOT}/../Podfile.lock\" \"${PODS_ROOT}/Manifest.lock\" > /dev/null\nif [ $? != 0 ] ; then\n # print error to STDERR\n echo \"error: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.\" >&2\n exit 1\nfi\n";
showEnvVarsInLog = 0;
};
83656AD5AD449BE38007FB5D /* [CP] Check Pods Manifest.lock */ = {
isa = PBXShellScriptBuildPhase;
buildActionMask = 2147483647;
files = (
);
inputPaths = (
);
name = "[CP] Check Pods Manifest.lock";
outputPaths = (
);
runOnlyForDeploymentPostprocessing = 0;
shellPath = /bin/sh;
shellScript = "diff \"${PODS_ROOT}/../Podfile.lock\" \"${PODS_ROOT}/Manifest.lock\" > /dev/null\nif [ $? != 0 ] ; then\n # print error to STDERR\n echo \"error: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.\" >&2\n exit 1\nfi\n";
showEnvVarsInLog = 0;
};
BB48EDF876C9F1A254792873 /* [CP] Embed Pods Frameworks */ = {
isa = PBXShellScriptBuildPhase;
buildActionMask = 2147483647;
files = (
);
inputPaths = (
);
name = "[CP] Embed Pods Frameworks";
outputPaths = (
);
runOnlyForDeploymentPostprocessing = 0;
shellPath = /bin/sh;
shellScript = "\"${SRCROOT}/Pods/Target Support Files/Pods-PersistentStorageSerializable_MacExample/Pods-PersistentStorageSerializable_MacExample-frameworks.sh\"\n";
showEnvVarsInLog = 0;
};
/* End PBXShellScriptBuildPhase section */
/* Begin PBXSourcesBuildPhase section */
607FACCC1AFB9204008FA782 /* Sources */ = {
isa = PBXSourcesBuildPhase;
buildActionMask = 2147483647;
files = (
AB6AC3B61E95513E00F735CB /* Settings.swift in Sources */,
607FACD81AFB9204008FA782 /* ViewController.swift in Sources */,
607FACD61AFB9204008FA782 /* AppDelegate.swift in Sources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
607FACE11AFB9204008FA782 /* Sources */ = {
isa = PBXSourcesBuildPhase;
buildActionMask = 2147483647;
files = (
AB6AC3AF1E950D5300F735CB /* PersistentStorageMock.swift in Sources */,
607FACEC1AFB9204008FA782 /* PersistentStorageSerializableTests.swift in Sources */,
AB76415C1E97CD57007279BE /* SupportedSerializableTypeTests.swift in Sources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
AB6AC3B91E9680AE00F735CB /* Sources */ = {
isa = PBXSourcesBuildPhase;
buildActionMask = 2147483647;
files = (
AB6AC3CD1E96819C00F735CB /* AppSettings.swift in Sources */,
AB6AC3C21E9680AE00F735CB /* ViewController.swift in Sources */,
AB6AC3C01E9680AE00F735CB /* AppDelegate.swift in Sources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXSourcesBuildPhase section */
/* Begin PBXVariantGroup section */
607FACD91AFB9204008FA782 /* Main.storyboard */ = {
isa = PBXVariantGroup;
children = (
607FACDA1AFB9204008FA782 /* Base */,
);
name = Main.storyboard;
sourceTree = "";
};
607FACDE1AFB9204008FA782 /* LaunchScreen.xib */ = {
isa = PBXVariantGroup;
children = (
607FACDF1AFB9204008FA782 /* Base */,
);
name = LaunchScreen.xib;
sourceTree = "";
};
AB6AC3C51E9680AE00F735CB /* Main.storyboard */ = {
isa = PBXVariantGroup;
children = (
AB6AC3C61E9680AE00F735CB /* Base */,
);
name = Main.storyboard;
sourceTree = "";
};
/* End PBXVariantGroup section */
/* Begin XCBuildConfiguration section */
607FACED1AFB9204008FA782 /* Debug */ = {
isa = XCBuildConfiguration;
buildSettings = {
ALWAYS_SEARCH_USER_PATHS = NO;
CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x";
CLANG_CXX_LIBRARY = "libc++";
CLANG_ENABLE_MODULES = YES;
CLANG_ENABLE_OBJC_ARC = YES;
CLANG_WARN_BOOL_CONVERSION = YES;
CLANG_WARN_CONSTANT_CONVERSION = YES;
CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR;
CLANG_WARN_EMPTY_BODY = YES;
CLANG_WARN_ENUM_CONVERSION = YES;
CLANG_WARN_INFINITE_RECURSION = YES;
CLANG_WARN_INT_CONVERSION = YES;
CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR;
CLANG_WARN_SUSPICIOUS_MOVE = YES;
CLANG_WARN_UNREACHABLE_CODE = YES;
CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;
"CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer";
COPY_PHASE_STRIP = NO;
DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym";
ENABLE_STRICT_OBJC_MSGSEND = YES;
ENABLE_TESTABILITY = YES;
GCC_C_LANGUAGE_STANDARD = gnu99;
GCC_DYNAMIC_NO_PIC = NO;
GCC_NO_COMMON_BLOCKS = YES;
GCC_OPTIMIZATION_LEVEL = 0;
GCC_PREPROCESSOR_DEFINITIONS = (
"DEBUG=1",
"$(inherited)",
);
GCC_SYMBOLS_PRIVATE_EXTERN = NO;
GCC_WARN_64_TO_32_BIT_CONVERSION = YES;
GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR;
GCC_WARN_UNDECLARED_SELECTOR = YES;
GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
GCC_WARN_UNUSED_FUNCTION = YES;
GCC_WARN_UNUSED_VARIABLE = YES;
IPHONEOS_DEPLOYMENT_TARGET = 9.0;
MACOSX_DEPLOYMENT_TARGET = 10.11;
MTL_ENABLE_DEBUG_INFO = YES;
ONLY_ACTIVE_ARCH = YES;
SDKROOT = iphoneos;
SWIFT_OPTIMIZATION_LEVEL = "-Onone";
};
name = Debug;
};
607FACEE1AFB9204008FA782 /* Release */ = {
isa = XCBuildConfiguration;
buildSettings = {
ALWAYS_SEARCH_USER_PATHS = NO;
CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x";
CLANG_CXX_LIBRARY = "libc++";
CLANG_ENABLE_MODULES = YES;
CLANG_ENABLE_OBJC_ARC = YES;
CLANG_WARN_BOOL_CONVERSION = YES;
CLANG_WARN_CONSTANT_CONVERSION = YES;
CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR;
CLANG_WARN_EMPTY_BODY = YES;
CLANG_WARN_ENUM_CONVERSION = YES;
CLANG_WARN_INFINITE_RECURSION = YES;
CLANG_WARN_INT_CONVERSION = YES;
CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR;
CLANG_WARN_SUSPICIOUS_MOVE = YES;
CLANG_WARN_UNREACHABLE_CODE = YES;
CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;
"CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer";
COPY_PHASE_STRIP = NO;
DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym";
ENABLE_NS_ASSERTIONS = NO;
ENABLE_STRICT_OBJC_MSGSEND = YES;
GCC_C_LANGUAGE_STANDARD = gnu99;
GCC_NO_COMMON_BLOCKS = YES;
GCC_WARN_64_TO_32_BIT_CONVERSION = YES;
GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR;
GCC_WARN_UNDECLARED_SELECTOR = YES;
GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
GCC_WARN_UNUSED_FUNCTION = YES;
GCC_WARN_UNUSED_VARIABLE = YES;
IPHONEOS_DEPLOYMENT_TARGET = 9.0;
MACOSX_DEPLOYMENT_TARGET = 10.11;
MTL_ENABLE_DEBUG_INFO = NO;
SDKROOT = iphoneos;
SWIFT_OPTIMIZATION_LEVEL = "-Owholemodule";
VALIDATE_PRODUCT = YES;
};
name = Release;
};
607FACF01AFB9204008FA782 /* Debug */ = {
isa = XCBuildConfiguration;
baseConfigurationReference = 1430E68C73DA958AEE435B2B /* Pods-PersistentStorageSerializable_iOSExample.debug.xcconfig */;
buildSettings = {
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
INFOPLIST_FILE = PersistentStorageSerializable/Info.plist;
LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks";
MODULE_NAME = ExampleApp;
PRODUCT_BUNDLE_IDENTIFIER = "org.cocoapods.demo.$(PRODUCT_NAME:rfc1034identifier)";
PRODUCT_NAME = "$(TARGET_NAME)";
SWIFT_VERSION = 3.0;
};
name = Debug;
};
607FACF11AFB9204008FA782 /* Release */ = {
isa = XCBuildConfiguration;
baseConfigurationReference = 2588AA89C5187E3CEA89DD6E /* Pods-PersistentStorageSerializable_iOSExample.release.xcconfig */;
buildSettings = {
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
INFOPLIST_FILE = PersistentStorageSerializable/Info.plist;
LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks";
MODULE_NAME = ExampleApp;
PRODUCT_BUNDLE_IDENTIFIER = "org.cocoapods.demo.$(PRODUCT_NAME:rfc1034identifier)";
PRODUCT_NAME = "$(TARGET_NAME)";
SWIFT_VERSION = 3.0;
};
name = Release;
};
607FACF31AFB9204008FA782 /* Debug */ = {
isa = XCBuildConfiguration;
baseConfigurationReference = D61EE2F47F5FCAFA282DF7DD /* Pods-PersistentStorageSerializable_Tests.debug.xcconfig */;
buildSettings = {
GCC_PREPROCESSOR_DEFINITIONS = (
"DEBUG=1",
"$(inherited)",
);
INFOPLIST_FILE = Tests/Info.plist;
LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks";
PRODUCT_BUNDLE_IDENTIFIER = "org.cocoapods.$(PRODUCT_NAME:rfc1034identifier)";
PRODUCT_NAME = "$(TARGET_NAME)";
SWIFT_VERSION = 3.0;
};
name = Debug;
};
607FACF41AFB9204008FA782 /* Release */ = {
isa = XCBuildConfiguration;
baseConfigurationReference = D0F7B87E59D17DF5674E4175 /* Pods-PersistentStorageSerializable_Tests.release.xcconfig */;
buildSettings = {
INFOPLIST_FILE = Tests/Info.plist;
LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks";
PRODUCT_BUNDLE_IDENTIFIER = "org.cocoapods.$(PRODUCT_NAME:rfc1034identifier)";
PRODUCT_NAME = "$(TARGET_NAME)";
SWIFT_VERSION = 3.0;
};
name = Release;
};
AB6AC3C91E9680AE00F735CB /* Debug */ = {
isa = XCBuildConfiguration;
baseConfigurationReference = 410ED040FF5FC9E233E71DA9 /* Pods-PersistentStorageSerializable_MacExample.debug.xcconfig */;
buildSettings = {
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
CLANG_ANALYZER_NONNULL = YES;
CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE;
CLANG_WARN_DOCUMENTATION_COMMENTS = YES;
CODE_SIGN_IDENTITY = "Mac Developer";
COMBINE_HIDPI_IMAGES = YES;
DEBUG_INFORMATION_FORMAT = dwarf;
DEVELOPMENT_TEAM = "";
INFOPLIST_FILE = PersistentStorageSerializable_MacExample/Info.plist;
LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/../Frameworks";
PRODUCT_BUNDLE_IDENTIFIER = "org.cocoapods.demo.PersistentStorageSerializable-MacExample";
PRODUCT_NAME = "$(TARGET_NAME)";
PROVISIONING_PROFILE_SPECIFIER = "";
SDKROOT = macosx;
SWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG;
SWIFT_VERSION = 3.0;
};
name = Debug;
};
AB6AC3CA1E9680AE00F735CB /* Release */ = {
isa = XCBuildConfiguration;
baseConfigurationReference = E1CCB00B943B4FE159A27022 /* Pods-PersistentStorageSerializable_MacExample.release.xcconfig */;
buildSettings = {
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
CLANG_ANALYZER_NONNULL = YES;
CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE;
CLANG_WARN_DOCUMENTATION_COMMENTS = YES;
CODE_SIGN_IDENTITY = "Mac Developer";
COMBINE_HIDPI_IMAGES = YES;
DEVELOPMENT_TEAM = "";
INFOPLIST_FILE = PersistentStorageSerializable_MacExample/Info.plist;
LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/../Frameworks";
PRODUCT_BUNDLE_IDENTIFIER = "org.cocoapods.demo.PersistentStorageSerializable-MacExample";
PRODUCT_NAME = "$(TARGET_NAME)";
PROVISIONING_PROFILE_SPECIFIER = "";
SDKROOT = macosx;
SWIFT_VERSION = 3.0;
};
name = Release;
};
/* End XCBuildConfiguration section */
/* Begin XCConfigurationList section */
607FACCB1AFB9204008FA782 /* Build configuration list for PBXProject "PersistentStorageSerializable" */ = {
isa = XCConfigurationList;
buildConfigurations = (
607FACED1AFB9204008FA782 /* Debug */,
607FACEE1AFB9204008FA782 /* Release */,
);
defaultConfigurationIsVisible = 0;
defaultConfigurationName = Release;
};
607FACEF1AFB9204008FA782 /* Build configuration list for PBXNativeTarget "PersistentStorageSerializable_iOSExample" */ = {
isa = XCConfigurationList;
buildConfigurations = (
607FACF01AFB9204008FA782 /* Debug */,
607FACF11AFB9204008FA782 /* Release */,
);
defaultConfigurationIsVisible = 0;
defaultConfigurationName = Release;
};
607FACF21AFB9204008FA782 /* Build configuration list for PBXNativeTarget "PersistentStorageSerializable_Tests" */ = {
isa = XCConfigurationList;
buildConfigurations = (
607FACF31AFB9204008FA782 /* Debug */,
607FACF41AFB9204008FA782 /* Release */,
);
defaultConfigurationIsVisible = 0;
defaultConfigurationName = Release;
};
AB6AC3CB1E9680AE00F735CB /* Build configuration list for PBXNativeTarget "PersistentStorageSerializable_MacExample" */ = {
isa = XCConfigurationList;
buildConfigurations = (
AB6AC3C91E9680AE00F735CB /* Debug */,
AB6AC3CA1E9680AE00F735CB /* Release */,
);
defaultConfigurationIsVisible = 0;
defaultConfigurationName = Release;
};
/* End XCConfigurationList section */
};
rootObject = 607FACC81AFB9204008FA782 /* Project object */;
}
================================================
FILE: Example/PersistentStorageSerializable.xcodeproj/project.xcworkspace/contents.xcworkspacedata
================================================
================================================
FILE: Example/PersistentStorageSerializable.xcodeproj/xcshareddata/xcschemes/PersistentStorageSerializable-MacExample.xcscheme
================================================
================================================
FILE: Example/PersistentStorageSerializable.xcodeproj/xcshareddata/xcschemes/PersistentStorageSerializable-Tests.xcscheme
================================================
================================================
FILE: Example/PersistentStorageSerializable.xcodeproj/xcshareddata/xcschemes/PersistentStorageSerializable-iOSExample.xcscheme
================================================
================================================
FILE: Example/PersistentStorageSerializable.xcworkspace/contents.xcworkspacedata
================================================
================================================
FILE: Example/PersistentStorageSerializable_MacExample/AppDelegate.swift
================================================
//
// AppDelegate.swift
// PersistentStorageSerializable_MacExample
//
// Created by Ivan Rublev on 4/6/17.
// Copyright © 2017 CocoaPods. All rights reserved.
//
import Cocoa
@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {
func applicationDidFinishLaunching(_ aNotification: Notification) {
// Insert code here to initialize your application
}
func applicationWillTerminate(_ aNotification: Notification) {
// Insert code here to tear down your application
}
}
================================================
FILE: Example/PersistentStorageSerializable_MacExample/AppSettings.swift
================================================
//
// AppSettings.swift
// PersistentStorageSerializable
//
// Created by Ivan Rublev on 4/6/17.
// Copyright © 2017 CocoaPods. All rights reserved.
//
import Foundation
import PersistentStorageSerializable
final class AppSettings: NSObject, PersistentStorageSerializable {
dynamic var flag = false
dynamic var title = "Default text"
dynamic var number = 1
// MARK: Adopt PersistentStorageSerializable
var persistentStorage: PersistentStorage! = PlistStorage(at: FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).last!.appendingPathComponent("storage.plist"))
var persistentStorageKeyPrefix: String! = "AppSettings"
}
================================================
FILE: Example/PersistentStorageSerializable_MacExample/Assets.xcassets/AppIcon.appiconset/Contents.json
================================================
{
"images" : [
{
"idiom" : "mac",
"size" : "16x16",
"scale" : "1x"
},
{
"idiom" : "mac",
"size" : "16x16",
"scale" : "2x"
},
{
"idiom" : "mac",
"size" : "32x32",
"scale" : "1x"
},
{
"idiom" : "mac",
"size" : "32x32",
"scale" : "2x"
},
{
"idiom" : "mac",
"size" : "128x128",
"scale" : "1x"
},
{
"idiom" : "mac",
"size" : "128x128",
"scale" : "2x"
},
{
"idiom" : "mac",
"size" : "256x256",
"scale" : "1x"
},
{
"idiom" : "mac",
"size" : "256x256",
"scale" : "2x"
},
{
"idiom" : "mac",
"size" : "512x512",
"scale" : "1x"
},
{
"idiom" : "mac",
"size" : "512x512",
"scale" : "2x"
}
],
"info" : {
"version" : 1,
"author" : "xcode"
}
}
================================================
FILE: Example/PersistentStorageSerializable_MacExample/Base.lproj/Main.storyboard
================================================
================================================
FILE: Example/PersistentStorageSerializable_MacExample/Info.plist
================================================
CFBundleDevelopmentRegion
en
CFBundleExecutable
$(EXECUTABLE_NAME)
CFBundleIconFile
CFBundleIdentifier
$(PRODUCT_BUNDLE_IDENTIFIER)
CFBundleInfoDictionaryVersion
6.0
CFBundleName
$(PRODUCT_NAME)
CFBundlePackageType
APPL
CFBundleShortVersionString
1.0
CFBundleVersion
1
LSMinimumSystemVersion
$(MACOSX_DEPLOYMENT_TARGET)
NSHumanReadableCopyright
Copyright © 2017 CocoaPods. All rights reserved.
NSMainStoryboardFile
Main
NSPrincipalClass
NSApplication
================================================
FILE: Example/PersistentStorageSerializable_MacExample/ViewController.swift
================================================
//
// ViewController.swift
// PersistentStorageSerializable_MacExample
//
// Created by Ivan Rublev on 4/6/17.
// Copyright © 2017 CocoaPods. All rights reserved.
//
import Cocoa
class ViewController: NSViewController {
@IBOutlet var userDefaultsText: NSTextField!
dynamic var settings = AppSettings()
override func viewDidLoad() {
super.viewDidLoad()
load(0)
}
func updateUserDefaultsText() {
userDefaultsText.stringValue = try! String(describing: settings.persistedDictionaryRepresentation())
}
@IBAction func load(_ sender: Any) {
view.window?.makeFirstResponder(nil)
var loadedSettings = AppSettings()
try! loadedSettings.pullFromPersistentStorage()
settings = loadedSettings
updateUserDefaultsText()
}
@IBAction func save(_ sender: Any) {
view.window?.makeFirstResponder(nil)
try! settings.pushToPersistentStorage()
updateUserDefaultsText()
}
@IBAction func reset(_ sender: Any) {
view.window?.makeFirstResponder(nil)
try! settings.removeFromPersistentStorage()
updateUserDefaultsText()
}
}
================================================
FILE: Example/Podfile
================================================
use_frameworks!
target 'PersistentStorageSerializable_iOSExample' do
platform :ios, '9.0'
pod 'PersistentStorageSerializable', :path => '../'
end
target 'PersistentStorageSerializable_Tests' do
platform :ios, '9.0'
pod 'PersistentStorageSerializable', :path => '../'
pod 'Quick', '~> 1.0.0'
pod 'Nimble', '~> 5.1.1'
end
target 'PersistentStorageSerializable_MacExample' do
platform :osx, '10.11'
pod 'PersistentStorageSerializable', :path => '../'
end
================================================
FILE: Example/Pods/Local Podspecs/PersistentStorageSerializable.podspec.json
================================================
{
"name": "PersistentStorageSerializable",
"version": "1.1.0",
"summary": "Bunch of protocols to make a class or structure to be serializable to persistent system storage like UserDefaults or Keychain. Useful to store app configuration or settings.",
"description": "Number of protocols from this pod helps to serialize swift class or structure to persistent storage like User Defaults or Keychain. The class/structure must contain properties of simple data type only. These types are: Data, String, Int, Float, Double, Bool, URL, Date, Array, or Dictionary.\nAdopt the PersistentStorageSerializable protocol from your struct. Then call pullFromUserDefaults() or pushToUserDefaults() on instance of your struct.",
"homepage": "https://github.com/IvanRublev/PersistentStorageSerializable",
"license": {
"type": "MIT",
"file": "LICENSE"
},
"authors": {
"IvanRublev": "ivan@ivanrublev.me"
},
"source": {
"git": "https://github.com/IvanRublev/PersistentStorageSerializable.git",
"tag": "1.1.0"
},
"platforms": {
"ios": "9.0",
"osx": "10.11"
},
"source_files": "PersistentStorageSerializable/Classes/**/*",
"frameworks": "Foundation",
"dependencies": {
"Reflection": [
"~> 0.14"
]
}
}
================================================
FILE: Example/Pods/Manifest.lock
================================================
PODS:
- Nimble (5.1.1)
- PersistentStorageSerializable (1.1.0):
- Reflection (~> 0.14)
- Quick (1.0.0)
- Reflection (0.14.3)
DEPENDENCIES:
- Nimble (~> 5.1.1)
- PersistentStorageSerializable (from `../`)
- Quick (~> 1.0.0)
EXTERNAL SOURCES:
PersistentStorageSerializable:
:path: "../"
SPEC CHECKSUMS:
Nimble: 415e3aa3267e7bc2c96b05fa814ddea7bb686a29
PersistentStorageSerializable: d941980a136f85a546b3378c6228526ad4fd7d51
Quick: 8024e4a47e6cc03a9d5245ef0948264fc6d27cff
Reflection: 93327e50981227ac33c18274fcbaed33b1127811
PODFILE CHECKSUM: 1725b222e0b97edb7fa20facee56f57f70eaa39d
COCOAPODS: 1.1.1
================================================
FILE: Example/Pods/Nimble/LICENSE.md
================================================
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "{}"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright 2014 Quick Team
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
================================================
FILE: Example/Pods/Nimble/README.md
================================================
# Nimble
Use Nimble to express the expected outcomes of Swift
or Objective-C expressions. Inspired by
[Cedar](https://github.com/pivotal/cedar).
```swift
// Swift
expect(1 + 1).to(equal(2))
expect(1.2).to(beCloseTo(1.1, within: 0.1))
expect(3) > 2
expect("seahorse").to(contain("sea"))
expect(["Atlantic", "Pacific"]).toNot(contain("Mississippi"))
expect(ocean.isClean).toEventually(beTruthy())
```
# How to Use Nimble
**Table of Contents** *generated with [DocToc](https://github.com/thlorenz/doctoc)*
- [Some Background: Expressing Outcomes Using Assertions in XCTest](#some-background-expressing-outcomes-using-assertions-in-xctest)
- [Nimble: Expectations Using `expect(...).to`](#nimble-expectations-using-expectto)
- [Custom Failure Messages](#custom-failure-messages)
- [Type Checking](#type-checking)
- [Operator Overloads](#operator-overloads)
- [Lazily Computed Values](#lazily-computed-values)
- [C Primitives](#c-primitives)
- [Asynchronous Expectations](#asynchronous-expectations)
- [Objective-C Support](#objective-c-support)
- [Disabling Objective-C Shorthand](#disabling-objective-c-shorthand)
- [Built-in Matcher Functions](#built-in-matcher-functions)
- [Equivalence](#equivalence)
- [Identity](#identity)
- [Comparisons](#comparisons)
- [Types/Classes](#typesclasses)
- [Truthiness](#truthiness)
- [Swift Assertions](#swift-assertions)
- [Swift Error Handling](#swift-error-handling)
- [Exceptions](#exceptions)
- [Collection Membership](#collection-membership)
- [Strings](#strings)
- [Checking if all elements of a collection pass a condition](#checking-if-all-elements-of-a-collection-pass-a-condition)
- [Verify collection count](#verify-collection-count)
- [Verify a notification was posted](#verifying-a-notification-was-posted)
- [Matching a value to any of a group of matchers](#matching-a-value-to-any-of-a-group-of-matchers)
- [Writing Your Own Matchers](#writing-your-own-matchers)
- [Lazy Evaluation](#lazy-evaluation)
- [Type Checking via Swift Generics](#type-checking-via-swift-generics)
- [Customizing Failure Messages](#customizing-failure-messages)
- [Supporting Objective-C](#supporting-objective-c)
- [Properly Handling `nil` in Objective-C Matchers](#properly-handling-nil-in-objective-c-matchers)
- [Installing Nimble](#installing-nimble)
- [Installing Nimble as a Submodule](#installing-nimble-as-a-submodule)
- [Installing Nimble via CocoaPods](#installing-nimble-via-cocoapods)
- [Using Nimble without XCTest](#using-nimble-without-xctest)
# Some Background: Expressing Outcomes Using Assertions in XCTest
Apple's Xcode includes the XCTest framework, which provides
assertion macros to test whether code behaves properly.
For example, to assert that `1 + 1 = 2`, XCTest has you write:
```swift
// Swift
XCTAssertEqual(1 + 1, 2, "expected one plus one to equal two")
```
Or, in Objective-C:
```objc
// Objective-C
XCTAssertEqual(1 + 1, 2, @"expected one plus one to equal two");
```
XCTest assertions have a couple of drawbacks:
1. **Not enough macros.** There's no easy way to assert that a string
contains a particular substring, or that a number is less than or
equal to another.
2. **It's hard to write asynchronous tests.** XCTest forces you to write
a lot of boilerplate code.
Nimble addresses these concerns.
# Nimble: Expectations Using `expect(...).to`
Nimble allows you to express expectations using a natural,
easily understood language:
```swift
// Swift
import Nimble
expect(seagull.squawk).to(equal("Squee!"))
```
```objc
// Objective-C
@import Nimble;
expect(seagull.squawk).to(equal(@"Squee!"));
```
> The `expect` function autocompletes to include `file:` and `line:`,
but these parameters are optional. Use the default values to have
Xcode highlight the correct line when an expectation is not met.
To perform the opposite expectation--to assert something is *not*
equal--use `toNot` or `notTo`:
```swift
// Swift
import Nimble
expect(seagull.squawk).toNot(equal("Oh, hello there!"))
expect(seagull.squawk).notTo(equal("Oh, hello there!"))
```
```objc
// Objective-C
@import Nimble;
expect(seagull.squawk).toNot(equal(@"Oh, hello there!"));
expect(seagull.squawk).notTo(equal(@"Oh, hello there!"));
```
## Custom Failure Messages
Would you like to add more information to the test's failure messages? Use the `description` optional argument to add your own text:
```swift
// Swift
expect(1 + 1).to(equal(3))
// failed - expected to equal <3>, got <2>
expect(1 + 1).to(equal(3), description: "Make sure libKindergartenMath is loaded")
// failed - Make sure libKindergartenMath is loaded
// expected to equal <3>, got <2>
```
Or the *WithDescription version in Objective-C:
```objc
// Objective-C
@import Nimble;
expect(@(1+1)).to(equal(@3));
// failed - expected to equal <3.0000>, got <2.0000>
expect(@(1+1)).toWithDescription(equal(@3), @"Make sure libKindergartenMath is loaded");
// failed - Make sure libKindergartenMath is loaded
// expected to equal <3.0000>, got <2.0000>
```
## Type Checking
Nimble makes sure you don't compare two types that don't match:
```swift
// Swift
// Does not compile:
expect(1 + 1).to(equal("Squee!"))
```
> Nimble uses generics--only available in Swift--to ensure
type correctness. That means type checking is
not available when using Nimble in Objective-C. :sob:
## Operator Overloads
Tired of so much typing? With Nimble, you can use overloaded operators
like `==` for equivalence, or `>` for comparisons:
```swift
// Swift
// Passes if squawk does not equal "Hi!":
expect(seagull.squawk) != "Hi!"
// Passes if 10 is greater than 2:
expect(10) > 2
```
> Operator overloads are only available in Swift, so you won't be able
to use this syntax in Objective-C. :broken_heart:
## Lazily Computed Values
The `expect` function doesn't evaluate the value it's given until it's
time to match. So Nimble can test whether an expression raises an
exception once evaluated:
```swift
// Swift
// Note: Swift currently doesn't have exceptions.
// Only Objective-C code can raise exceptions
// that Nimble will catch.
// (see https://github.com/Quick/Nimble/issues/220#issuecomment-172667064)
let exception = NSException(
name: NSInternalInconsistencyException,
reason: "Not enough fish in the sea.",
userInfo: ["something": "is fishy"])
expect { exception.raise() }.to(raiseException())
// Also, you can customize raiseException to be more specific
expect { exception.raise() }.to(raiseException(named: NSInternalInconsistencyException))
expect { exception.raise() }.to(raiseException(
named: NSInternalInconsistencyException,
reason: "Not enough fish in the sea"))
expect { exception.raise() }.to(raiseException(
named: NSInternalInconsistencyException,
reason: "Not enough fish in the sea",
userInfo: ["something": "is fishy"]))
```
Objective-C works the same way, but you must use the `expectAction`
macro when making an expectation on an expression that has no return
value:
```objc
// Objective-C
NSException *exception = [NSException exceptionWithName:NSInternalInconsistencyException
reason:@"Not enough fish in the sea."
userInfo:nil];
expectAction(^{ [exception raise]; }).to(raiseException());
// Use the property-block syntax to be more specific.
expectAction(^{ [exception raise]; }).to(raiseException().named(NSInternalInconsistencyException));
expectAction(^{ [exception raise]; }).to(raiseException().
named(NSInternalInconsistencyException).
reason("Not enough fish in the sea"));
expectAction(^{ [exception raise]; }).to(raiseException().
named(NSInternalInconsistencyException).
reason("Not enough fish in the sea").
userInfo(@{@"something": @"is fishy"}));
// You can also pass a block for custom matching of the raised exception
expectAction(exception.raise()).to(raiseException().satisfyingBlock(^(NSException *exception) {
expect(exception.name).to(beginWith(NSInternalInconsistencyException));
}));
```
## C Primitives
Some testing frameworks make it hard to test primitive C values.
In Nimble, it just works:
```swift
// Swift
let actual: CInt = 1
let expectedValue: CInt = 1
expect(actual).to(equal(expectedValue))
```
In fact, Nimble uses type inference, so you can write the above
without explicitly specifying both types:
```swift
// Swift
expect(1 as CInt).to(equal(1))
```
> In Objective-C, Nimble only supports Objective-C objects. To
make expectations on primitive C values, wrap then in an object
literal:
```objc
expect(@(1 + 1)).to(equal(@2));
```
## Asynchronous Expectations
In Nimble, it's easy to make expectations on values that are updated
asynchronously. Just use `toEventually` or `toEventuallyNot`:
```swift
// Swift
dispatch_async(dispatch_get_main_queue()) {
ocean.add("dolphins")
ocean.add("whales")
}
expect(ocean).toEventually(contain("dolphins", "whales"))
```
```objc
// Objective-C
dispatch_async(dispatch_get_main_queue(), ^{
[ocean add:@"dolphins"];
[ocean add:@"whales"];
});
expect(ocean).toEventually(contain(@"dolphins", @"whales"));
```
Note: toEventually triggers its polls on the main thread. Blocking the main
thread will cause Nimble to stop the run loop. This can cause test pollution
for whatever incomplete code that was running on the main thread. Blocking the
main thread can be caused by blocking IO, calls to sleep(), deadlocks, and
synchronous IPC.
In the above example, `ocean` is constantly re-evaluated. If it ever
contains dolphins and whales, the expectation passes. If `ocean` still
doesn't contain them, even after being continuously re-evaluated for one
whole second, the expectation fails.
Sometimes it takes more than a second for a value to update. In those
cases, use the `timeout` parameter:
```swift
// Swift
// Waits three seconds for ocean to contain "starfish":
expect(ocean).toEventually(contain("starfish"), timeout: 3)
// Evaluate someValue every 0.2 seconds repeatedly until it equals 100, or fails if it timeouts after 5.5 seconds.
expect(someValue).toEventually(equal(100), timeout: 5.5, pollInterval: 0.2)
```
```objc
// Objective-C
// Waits three seconds for ocean to contain "starfish":
expect(ocean).withTimeout(3).toEventually(contain(@"starfish"));
```
You can also provide a callback by using the `waitUntil` function:
```swift
// Swift
waitUntil { done in
// do some stuff that takes a while...
NSThread.sleepForTimeInterval(0.5)
done()
}
```
```objc
// Objective-C
waitUntil(^(void (^done)(void)){
// do some stuff that takes a while...
[NSThread sleepForTimeInterval:0.5];
done();
});
```
`waitUntil` also optionally takes a timeout parameter:
```swift
// Swift
waitUntil(timeout: 10) { done in
// do some stuff that takes a while...
NSThread.sleepForTimeInterval(1)
done()
}
```
```objc
// Objective-C
waitUntilTimeout(10, ^(void (^done)(void)){
// do some stuff that takes a while...
[NSThread sleepForTimeInterval:1];
done();
});
```
Note: waitUntil triggers its timeout code on the main thread. Blocking the main
thread will cause Nimble to stop the run loop to continue. This can cause test
pollution for whatever incomplete code that was running on the main thread.
Blocking the main thread can be caused by blocking IO, calls to sleep(),
deadlocks, and synchronous IPC.
In some cases (e.g. when running on slower machines) it can be useful to modify
the default timeout and poll interval values. This can be done as follows:
```swift
// Swift
// Increase the global timeout to 5 seconds:
Nimble.AsyncDefaults.Timeout = 5
// Slow the polling interval to 0.1 seconds:
Nimble.AsyncDefaults.PollInterval = 0.1
```
## Objective-C Support
Nimble has full support for Objective-C. However, there are two things
to keep in mind when using Nimble in Objective-C:
1. All parameters passed to the `expect` function, as well as matcher
functions like `equal`, must be Objective-C objects or can be converted into
an `NSObject` equivalent:
```objc
// Objective-C
@import Nimble;
expect(@(1 + 1)).to(equal(@2));
expect(@"Hello world").to(contain(@"world"));
// Boxed as NSNumber *
expect(2).to(equal(2));
expect(1.2).to(beLessThan(2.0));
expect(true).to(beTruthy());
// Boxed as NSString *
expect("Hello world").to(equal("Hello world"));
// Boxed as NSRange
expect(NSMakeRange(1, 10)).to(equal(NSMakeRange(1, 10)));
```
2. To make an expectation on an expression that does not return a value,
such as `-[NSException raise]`, use `expectAction` instead of
`expect`:
```objc
// Objective-C
expectAction(^{ [exception raise]; }).to(raiseException());
```
The following types are currently converted to an `NSObject` type:
- **C Numeric types** are converted to `NSNumber *`
- `NSRange` is converted to `NSValue *`
- `char *` is converted to `NSString *`
For the following matchers:
- `equal`
- `beGreaterThan`
- `beGreaterThanOrEqual`
- `beLessThan`
- `beLessThanOrEqual`
- `beCloseTo`
- `beTrue`
- `beFalse`
- `beTruthy`
- `beFalsy`
- `haveCount`
If you would like to see more, [file an issue](https://github.com/Quick/Nimble/issues).
## Disabling Objective-C Shorthand
Nimble provides a shorthand for expressing expectations using the
`expect` function. To disable this shorthand in Objective-C, define the
`NIMBLE_DISABLE_SHORT_SYNTAX` macro somewhere in your code before
importing Nimble:
```objc
#define NIMBLE_DISABLE_SHORT_SYNTAX 1
@import Nimble;
NMB_expect(^{ return seagull.squawk; }, __FILE__, __LINE__).to(NMB_equal(@"Squee!"));
```
> Disabling the shorthand is useful if you're testing functions with
names that conflict with Nimble functions, such as `expect` or
`equal`. If that's not the case, there's no point in disabling the
shorthand.
# Built-in Matcher Functions
Nimble includes a wide variety of matcher functions.
## Equivalence
```swift
// Swift
// Passes if actual is equivalent to expected:
expect(actual).to(equal(expected))
expect(actual) == expected
// Passes if actual is not equivalent to expected:
expect(actual).toNot(equal(expected))
expect(actual) != expected
```
```objc
// Objective-C
// Passes if actual is equivalent to expected:
expect(actual).to(equal(expected))
// Passes if actual is not equivalent to expected:
expect(actual).toNot(equal(expected))
```
Values must be `Equatable`, `Comparable`, or subclasses of `NSObject`.
`equal` will always fail when used to compare one or more `nil` values.
## Identity
```swift
// Swift
// Passes if actual has the same pointer address as expected:
expect(actual).to(beIdenticalTo(expected))
expect(actual) === expected
// Passes if actual does not have the same pointer address as expected:
expect(actual).toNot(beIdenticalTo(expected))
expect(actual) !== expected
```
Its important to remember that `beIdenticalTo` only makes sense when comparing types with reference semantics, which have a notion of identity. In Swift, that means a `class`. This matcher will not work with types with value semantics such as `struct` or `enum`. If you need to compare two value types, you can either compare individual properties or if it makes sense to do so, make your type implement `Equatable` and use Nimble's equivalence matchers instead.
```objc
// Objective-C
// Passes if actual has the same pointer address as expected:
expect(actual).to(beIdenticalTo(expected));
// Passes if actual does not have the same pointer address as expected:
expect(actual).toNot(beIdenticalTo(expected));
```
## Comparisons
```swift
// Swift
expect(actual).to(beLessThan(expected))
expect(actual) < expected
expect(actual).to(beLessThanOrEqualTo(expected))
expect(actual) <= expected
expect(actual).to(beGreaterThan(expected))
expect(actual) > expected
expect(actual).to(beGreaterThanOrEqualTo(expected))
expect(actual) >= expected
```
```objc
// Objective-C
expect(actual).to(beLessThan(expected));
expect(actual).to(beLessThanOrEqualTo(expected));
expect(actual).to(beGreaterThan(expected));
expect(actual).to(beGreaterThanOrEqualTo(expected));
```
> Values given to the comparison matchers above must implement
`Comparable`.
Because of how computers represent floating point numbers, assertions
that two floating point numbers be equal will sometimes fail. To express
that two numbers should be close to one another within a certain margin
of error, use `beCloseTo`:
```swift
// Swift
expect(actual).to(beCloseTo(expected, within: delta))
```
```objc
// Objective-C
expect(actual).to(beCloseTo(expected).within(delta));
```
For example, to assert that `10.01` is close to `10`, you can write:
```swift
// Swift
expect(10.01).to(beCloseTo(10, within: 0.1))
```
```objc
// Objective-C
expect(@(10.01)).to(beCloseTo(@10).within(0.1));
```
There is also an operator shortcut available in Swift:
```swift
// Swift
expect(actual) ≈ expected
expect(actual) ≈ (expected, delta)
```
(Type Option-x to get ≈ on a U.S. keyboard)
The former version uses the default delta of 0.0001. Here is yet another way to do this:
```swift
// Swift
expect(actual) ≈ expected ± delta
expect(actual) == expected ± delta
```
(Type Option-Shift-= to get ± on a U.S. keyboard)
If you are comparing arrays of floating point numbers, you'll find the following useful:
```swift
// Swift
expect([0.0, 2.0]) ≈ [0.0001, 2.0001]
expect([0.0, 2.0]).to(beCloseTo([0.1, 2.1], within: 0.1))
```
> Values given to the `beCloseTo` matcher must be coercable into a
`Double`.
## Types/Classes
```swift
// Swift
// Passes if instance is an instance of aClass:
expect(instance).to(beAnInstanceOf(aClass))
// Passes if instance is an instance of aClass or any of its subclasses:
expect(instance).to(beAKindOf(aClass))
```
```objc
// Objective-C
// Passes if instance is an instance of aClass:
expect(instance).to(beAnInstanceOf(aClass));
// Passes if instance is an instance of aClass or any of its subclasses:
expect(instance).to(beAKindOf(aClass));
```
> Instances must be Objective-C objects: subclasses of `NSObject`,
or Swift objects bridged to Objective-C with the `@objc` prefix.
For example, to assert that `dolphin` is a kind of `Mammal`:
```swift
// Swift
expect(dolphin).to(beAKindOf(Mammal))
```
```objc
// Objective-C
expect(dolphin).to(beAKindOf([Mammal class]));
```
> `beAnInstanceOf` uses the `-[NSObject isMemberOfClass:]` method to
test membership. `beAKindOf` uses `-[NSObject isKindOfClass:]`.
## Truthiness
```swift
// Passes if actual is not nil, true, or an object with a boolean value of true:
expect(actual).to(beTruthy())
// Passes if actual is only true (not nil or an object conforming to Boolean true):
expect(actual).to(beTrue())
// Passes if actual is nil, false, or an object with a boolean value of false:
expect(actual).to(beFalsy())
// Passes if actual is only false (not nil or an object conforming to Boolean false):
expect(actual).to(beFalse())
// Passes if actual is nil:
expect(actual).to(beNil())
```
```objc
// Objective-C
// Passes if actual is not nil, true, or an object with a boolean value of true:
expect(actual).to(beTruthy());
// Passes if actual is only true (not nil or an object conforming to Boolean true):
expect(actual).to(beTrue());
// Passes if actual is nil, false, or an object with a boolean value of false:
expect(actual).to(beFalsy());
// Passes if actual is only false (not nil or an object conforming to Boolean false):
expect(actual).to(beFalse());
// Passes if actual is nil:
expect(actual).to(beNil());
```
## Swift Assertions
If you're using Swift, you can use the `throwAssertion` matcher to check if an assertion is thrown (e.g. `fatalError()`). This is made possible by [@mattgallagher](https://github.com/mattgallagher)'s [CwlPreconditionTesting](https://github.com/mattgallagher/CwlPreconditionTesting) library.
```swift
// Swift
// Passes if somethingThatThrows() throws an assertion, such as calling fatalError() or precondition fails:
expect { () -> Void in fatalError() }.to(throwAssertion())
expect { precondition(false) }.to(throwAssertion())
// Passes if throwing a NSError is not equal to throwing an assertion:
expect { throw NSError(domain: "test", code: 0, userInfo: nil) }.toNot(throwAssertion())
// Passes if the post assertion code is not run:
var reachedPoint1 = false
var reachedPoint2 = false
expect {
reachedPoint1 = true
precondition(false, "condition message")
reachedPoint2 = true
}.to(throwAssertion())
expect(reachedPoint1) == true
expect(reachedPoint2) == false
```
Notes:
* This feature is only available in Swift.
* It is only supported for `x86_64` binaries, meaning _you cannot run this matcher on iOS devices, only simulators_.
* The tvOS simulator is supported, but using a different mechanism, requiring you to turn off the `Debug executable` scheme setting for your tvOS scheme's Test configuration.
## Swift Error Handling
If you're using Swift 2.0+, you can use the `throwError` matcher to check if an error is thrown.
```swift
// Swift
// Passes if somethingThatThrows() throws an ErrorProtocol:
expect{ try somethingThatThrows() }.to(throwError())
// Passes if somethingThatThrows() throws an error with a given domain:
expect{ try somethingThatThrows() }.to(throwError { (error: ErrorProtocol) in
expect(error._domain).to(equal(NSCocoaErrorDomain))
})
// Passes if somethingThatThrows() throws an error with a given case:
expect{ try somethingThatThrows() }.to(throwError(NSCocoaError.PropertyListReadCorruptError))
// Passes if somethingThatThrows() throws an error with a given type:
expect{ try somethingThatThrows() }.to(throwError(errorType: NimbleError.self))
```
If you are working directly with `ErrorProtocol` values, as is sometimes the case when using `Result` or `Promise` types, you can use the `matchError` matcher to check if the error is the same error is is supposed to be, without requiring explicit casting.
```swift
// Swift
let actual: ErrorProtocol = …
// Passes if actual contains any error value from the NimbleErrorEnum type:
expect(actual).to(matchError(NimbleErrorEnum))
// Passes if actual contains the Timeout value from the NimbleErrorEnum type:
expect(actual).to(matchError(NimbleErrorEnum.Timeout))
// Passes if actual contains an NSError equal to the given one:
expect(actual).to(matchError(NSError(domain: "err", code: 123, userInfo: nil)))
```
Note: This feature is only available in Swift.
## Exceptions
```swift
// Swift
// Passes if actual, when evaluated, raises an exception:
expect(actual).to(raiseException())
// Passes if actual raises an exception with the given name:
expect(actual).to(raiseException(named: name))
// Passes if actual raises an exception with the given name and reason:
expect(actual).to(raiseException(named: name, reason: reason))
// Passes if actual raises an exception and it passes expectations in the block
// (in this case, if name begins with 'a r')
expect { exception.raise() }.to(raiseException { (exception: NSException) in
expect(exception.name).to(beginWith("a r"))
})
```
```objc
// Objective-C
// Passes if actual, when evaluated, raises an exception:
expect(actual).to(raiseException())
// Passes if actual raises an exception with the given name
expect(actual).to(raiseException().named(name))
// Passes if actual raises an exception with the given name and reason:
expect(actual).to(raiseException().named(name).reason(reason))
// Passes if actual raises an exception and it passes expectations in the block
// (in this case, if name begins with 'a r')
expect(actual).to(raiseException().satisfyingBlock(^(NSException *exception) {
expect(exception.name).to(beginWith(@"a r"));
}));
```
Note: Swift currently doesn't have exceptions (see [#220](https://github.com/Quick/Nimble/issues/220#issuecomment-172667064)). Only Objective-C code can raise
exceptions that Nimble will catch.
## Collection Membership
```swift
// Swift
// Passes if all of the expected values are members of actual:
expect(actual).to(contain(expected...))
// Passes if actual is an empty collection (it contains no elements):
expect(actual).to(beEmpty())
```
```objc
// Objective-C
// Passes if expected is a member of actual:
expect(actual).to(contain(expected));
// Passes if actual is an empty collection (it contains no elements):
expect(actual).to(beEmpty());
```
> In Swift `contain` takes any number of arguments. The expectation
passes if all of them are members of the collection. In Objective-C,
`contain` only takes one argument [for now](https://github.com/Quick/Nimble/issues/27).
For example, to assert that a list of sea creature names contains
"dolphin" and "starfish":
```swift
// Swift
expect(["whale", "dolphin", "starfish"]).to(contain("dolphin", "starfish"))
```
```objc
// Objective-C
expect(@[@"whale", @"dolphin", @"starfish"]).to(contain(@"dolphin"));
expect(@[@"whale", @"dolphin", @"starfish"]).to(contain(@"starfish"));
```
> `contain` and `beEmpty` expect collections to be instances of
`NSArray`, `NSSet`, or a Swift collection composed of `Equatable` elements.
To test whether a set of elements is present at the beginning or end of
an ordered collection, use `beginWith` and `endWith`:
```swift
// Swift
// Passes if the elements in expected appear at the beginning of actual:
expect(actual).to(beginWith(expected...))
// Passes if the the elements in expected come at the end of actual:
expect(actual).to(endWith(expected...))
```
```objc
// Objective-C
// Passes if the elements in expected appear at the beginning of actual:
expect(actual).to(beginWith(expected));
// Passes if the the elements in expected come at the end of actual:
expect(actual).to(endWith(expected));
```
> `beginWith` and `endWith` expect collections to be instances of
`NSArray`, or ordered Swift collections composed of `Equatable`
elements.
Like `contain`, in Objective-C `beginWith` and `endWith` only support
a single argument [for now](https://github.com/Quick/Nimble/issues/27).
## Strings
```swift
// Swift
// Passes if actual contains substring expected:
expect(actual).to(contain(expected))
// Passes if actual begins with substring:
expect(actual).to(beginWith(expected))
// Passes if actual ends with substring:
expect(actual).to(endWith(expected))
// Passes if actual is an empty string, "":
expect(actual).to(beEmpty())
// Passes if actual matches the regular expression defined in expected:
expect(actual).to(match(expected))
```
```objc
// Objective-C
// Passes if actual contains substring expected:
expect(actual).to(contain(expected));
// Passes if actual begins with substring:
expect(actual).to(beginWith(expected));
// Passes if actual ends with substring:
expect(actual).to(endWith(expected));
// Passes if actual is an empty string, "":
expect(actual).to(beEmpty());
// Passes if actual matches the regular expression defined in expected:
expect(actual).to(match(expected))
```
## Checking if all elements of a collection pass a condition
```swift
// Swift
// with a custom function:
expect([1,2,3,4]).to(allPass({$0 < 5}))
// with another matcher:
expect([1,2,3,4]).to(allPass(beLessThan(5)))
```
```objc
// Objective-C
expect(@[@1, @2, @3,@4]).to(allPass(beLessThan(@5)));
```
For Swift the actual value has to be a Sequence, e.g. an array, a set or a custom seqence type.
For Objective-C the actual value has to be a NSFastEnumeration, e.g. NSArray and NSSet, of NSObjects and only the variant which
uses another matcher is available here.
## Verify collection count
```swift
// Swift
// passes if actual collection's count is equal to expected
expect(actual).to(haveCount(expected))
// passes if actual collection's count is not equal to expected
expect(actual).notTo(haveCount(expected))
```
```objc
// Objective-C
// passes if actual collection's count is equal to expected
expect(actual).to(haveCount(expected))
// passes if actual collection's count is not equal to expected
expect(actual).notTo(haveCount(expected))
```
For Swift the actual value must be a `Collection` such as array, dictionary or set.
For Objective-C the actual value has to be one of the following classes `NSArray`, `NSDictionary`, `NSSet`, `NSHashTable` or one of their subclasses.
## Foundation
### Verifying a Notification was posted
```swift
// Swift
let testNotification = Notification(name: "Foo", object: nil)
// passes if the closure in expect { ... } posts a notification to the default
// notification center.
expect {
NotificationCenter.default.postNotification(testNotification)
}.to(postNotifications(equal([testNotification]))
// passes if the closure in expect { ... } posts a notification to a given
// notification center
let notificationCenter = NotificationCenter()
expect {
notificationCenter.postNotification(testNotification)
}.to(postNotifications(equal([testNotification]), fromNotificationCenter: notificationCenter))
```
> This matcher is only available in Swift.
## Matching a value to any of a group of matchers
```swift
// passes if actual is either less than 10 or greater than 20
expect(actual).to(satisfyAnyOf(beLessThan(10), beGreaterThan(20)))
// can include any number of matchers -- the following will pass
// **be careful** -- too many matchers can be the sign of an unfocused test
expect(6).to(satisfyAnyOf(equal(2), equal(3), equal(4), equal(5), equal(6), equal(7)))
// in Swift you also have the option to use the || operator to achieve a similar function
expect(82).to(beLessThan(50) || beGreaterThan(80))
```
```objc
// passes if actual is either less than 10 or greater than 20
expect(actual).to(satisfyAnyOf(beLessThan(@10), beGreaterThan(@20)))
// can include any number of matchers -- the following will pass
// **be careful** -- too many matchers can be the sign of an unfocused test
expect(@6).to(satisfyAnyOf(equal(@2), equal(@3), equal(@4), equal(@5), equal(@6), equal(@7)))
```
Note: This matcher allows you to chain any number of matchers together. This provides flexibility,
but if you find yourself chaining many matchers together in one test, consider whether you
could instead refactor that single test into multiple, more precisely focused tests for
better coverage.
# Writing Your Own Matchers
In Nimble, matchers are Swift functions that take an expected
value and return a `MatcherFunc` closure. Take `equal`, for example:
```swift
// Swift
public func equal(expectedValue: T?) -> MatcherFunc {
return MatcherFunc { actualExpression, failureMessage in
failureMessage.postfixMessage = "equal <\(expectedValue)>"
if let actualValue = try actualExpression.evaluate() {
return actualValue == expectedValue
} else {
return false
}
}
}
```
The return value of a `MatcherFunc` closure is a `Bool` that indicates
whether the actual value matches the expectation: `true` if it does, or
`false` if it doesn't.
> The actual `equal` matcher function does not match when either
`actual` or `expected` are nil; the example above has been edited for
brevity.
Since matchers are just Swift functions, you can define them anywhere:
at the top of your test file, in a file shared by all of your tests, or
in an Xcode project you distribute to others.
> If you write a matcher you think everyone can use, consider adding it
to Nimble's built-in set of matchers by sending a pull request! Or
distribute it yourself via GitHub.
For examples of how to write your own matchers, just check out the
[`Matchers` directory](https://github.com/Quick/Nimble/tree/master/Sources/Nimble/Matchers)
to see how Nimble's built-in set of matchers are implemented. You can
also check out the tips below.
## Lazy Evaluation
`actualExpression` is a lazy, memoized closure around the value provided to the
`expect` function. The expression can either be a closure or a value directly
passed to `expect(...)`. In order to determine whether that value matches,
custom matchers should call `actualExpression.evaluate()`:
```swift
// Swift
public func beNil() -> MatcherFunc {
return MatcherFunc { actualExpression, failureMessage in
failureMessage.postfixMessage = "be nil"
return actualExpression.evaluate() == nil
}
}
```
In the above example, `actualExpression` is not `nil`--it is a closure
that returns a value. The value it returns, which is accessed via the
`evaluate()` method, may be `nil`. If that value is `nil`, the `beNil`
matcher function returns `true`, indicating that the expectation passed.
Use `expression.isClosure` to determine if the expression will be invoking
a closure to produce its value.
## Type Checking via Swift Generics
Using Swift's generics, matchers can constrain the type of the actual value
passed to the `expect` function by modifying the return type.
For example, the following matcher, `haveDescription`, only accepts actual
values that implement the `Printable` protocol. It checks their `description`
against the one provided to the matcher function, and passes if they are the same:
```swift
// Swift
public func haveDescription(description: String) -> MatcherFunc {
return MatcherFunc { actual, failureMessage in
return actual.evaluate().description == description
}
}
```
## Customizing Failure Messages
By default, Nimble outputs the following failure message when an
expectation fails:
```
expected to match, got <\(actual)>
```
You can customize this message by modifying the `failureMessage` struct
from within your `MatcherFunc` closure. To change the verb "match" to
something else, update the `postfixMessage` property:
```swift
// Swift
// Outputs: expected to be under the sea, got <\(actual)>
failureMessage.postfixMessage = "be under the sea"
```
You can change how the `actual` value is displayed by updating
`failureMessage.actualValue`. Or, to remove it altogether, set it to
`nil`:
```swift
// Swift
// Outputs: expected to be under the sea
failureMessage.actualValue = nil
failureMessage.postfixMessage = "be under the sea"
```
## Supporting Objective-C
To use a custom matcher written in Swift from Objective-C, you'll have
to extend the `NMBObjCMatcher` class, adding a new class method for your
custom matcher. The example below defines the class method
`+[NMBObjCMatcher beNilMatcher]`:
```swift
// Swift
extension NMBObjCMatcher {
public class func beNilMatcher() -> NMBObjCMatcher {
return NMBObjCMatcher { actualBlock, failureMessage, location in
let block = ({ actualBlock() as NSObject? })
let expr = Expression(expression: block, location: location)
return beNil().matches(expr, failureMessage: failureMessage)
}
}
}
```
The above allows you to use the matcher from Objective-C:
```objc
// Objective-C
expect(actual).to([NMBObjCMatcher beNilMatcher]());
```
To make the syntax easier to use, define a C function that calls the
class method:
```objc
// Objective-C
FOUNDATION_EXPORT id beNil() {
return [NMBObjCMatcher beNilMatcher];
}
```
### Properly Handling `nil` in Objective-C Matchers
When supporting Objective-C, make sure you handle `nil` appropriately.
Like [Cedar](https://github.com/pivotal/cedar/issues/100),
**most matchers do not match with nil**. This is to bring prevent test
writers from being surprised by `nil` values where they did not expect
them.
Nimble provides the `beNil` matcher function for test writer that want
to make expectations on `nil` objects:
```objc
// Objective-C
expect(nil).to(equal(nil)); // fails
expect(nil).to(beNil()); // passes
```
If your matcher does not want to match with nil, you use `NonNilMatcherFunc`
and the `canMatchNil` constructor on `NMBObjCMatcher`. Using both types will
automatically generate expected value failure messages when they're nil.
```swift
public func beginWith(startingElement: T) -> NonNilMatcherFunc {
return NonNilMatcherFunc { actualExpression, failureMessage in
failureMessage.postfixMessage = "begin with <\(startingElement)>"
if let actualValue = actualExpression.evaluate() {
var actualGenerator = actualValue.makeIterator()
return actualGenerator.next() == startingElement
}
return false
}
}
extension NMBObjCMatcher {
public class func beginWithMatcher(expected: AnyObject) -> NMBObjCMatcher {
return NMBObjCMatcher(canMatchNil: false) { actualExpression, failureMessage in
let actual = actualExpression.evaluate()
let expr = actualExpression.cast { $0 as? NMBOrderedCollection }
return beginWith(expected).matches(expr, failureMessage: failureMessage)
}
}
}
```
# Installing Nimble
> Nimble can be used on its own, or in conjunction with its sister
project, [Quick](https://github.com/Quick/Quick). To install both
Quick and Nimble, follow [the installation instructions in the Quick
Documentation](https://github.com/Quick/Quick/blob/master/Documentation/en-us/InstallingQuick.md).
Nimble can currently be installed in one of two ways: using CocoaPods, or with
git submodules.
## Installing Nimble as a Submodule
To use Nimble as a submodule to test your macOS, iOS or tvOS applications, follow
these 4 easy steps:
1. Clone the Nimble repository
2. Add Nimble.xcodeproj to the Xcode workspace for your project
3. Link Nimble.framework to your test target
4. Start writing expectations!
For more detailed instructions on each of these steps,
read [How to Install Quick](https://github.com/Quick/Quick#how-to-install-quick).
Ignore the steps involving adding Quick to your project in order to
install just Nimble.
## Installing Nimble via CocoaPods
To use Nimble in CocoaPods to test your macOS, iOS or tvOS applications, add
Nimble to your podfile and add the ```use_frameworks!``` line to enable Swift
support for CocoaPods.
```ruby
platform :ios, '8.0'
source 'https://github.com/CocoaPods/Specs.git'
# Whatever pods you need for your app go here
target 'YOUR_APP_NAME_HERE_Tests', :exclusive => true do
use_frameworks!
pod 'Nimble', '~> 5.0.0'
end
```
Finally run `pod install`.
## Using Nimble without XCTest
Nimble is integrated with XCTest to allow it work well when used in Xcode test
bundles, however it can also be used in a standalone app. After installing
Nimble using one of the above methods, there are two additional steps required
to make this work.
1. Create a custom assertion handler and assign an instance of it to the
global `NimbleAssertionHandler` variable. For example:
```swift
class MyAssertionHandler : AssertionHandler {
func assert(assertion: Bool, message: FailureMessage, location: SourceLocation) {
if (!assertion) {
print("Expectation failed: \(message.stringValue)")
}
}
}
```
```swift
// Somewhere before you use any assertions
NimbleAssertionHandler = MyAssertionHandler()
```
2. Add a post-build action to fix an issue with the Swift XCTest support
library being unnecessarily copied into your app
* Edit your scheme in Xcode, and navigate to Build -> Post-actions
* Click the "+" icon and select "New Run Script Action"
* Open the "Provide build settings from" dropdown and select your target
* Enter the following script contents:
```
rm "${SWIFT_STDLIB_TOOL_DESTINATION_DIR}/libswiftXCTest.dylib"
```
You can now use Nimble assertions in your code and handle failures as you see
fit.
================================================
FILE: Example/Pods/Nimble/Sources/Lib/CwlPreconditionTesting/CwlCatchException/CwlCatchException/CwlCatchException.h
================================================
//
// CwlCatchException.h
// CwlCatchException
//
// Created by Matt Gallagher on 2016/01/10.
// Copyright © 2016 Matt Gallagher ( http://cocoawithlove.com ). All rights reserved.
//
// Permission to use, copy, modify, and/or distribute this software for any
// purpose with or without fee is hereby granted, provided that the above
// copyright notice and this permission notice appear in all copies.
//
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
// ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR
// IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
//
#import
//! Project version number for CwlCatchException.
FOUNDATION_EXPORT double CwlCatchExceptionVersionNumber;
//! Project version string for CwlCatchException.
FOUNDATION_EXPORT const unsigned char CwlCatchExceptionVersionString[];
__attribute__((visibility("hidden")))
NSException* __nullable catchExceptionOfKind(Class __nonnull type, __attribute__((noescape)) void (^ __nonnull inBlock)());
================================================
FILE: Example/Pods/Nimble/Sources/Lib/CwlPreconditionTesting/CwlCatchException/CwlCatchException/CwlCatchException.m
================================================
//
// CwlCatchException.m
// CwlAssertionTesting
//
// Created by Matt Gallagher on 2016/01/10.
// Copyright © 2016 Matt Gallagher ( http://cocoawithlove.com ). All rights reserved.
//
// Permission to use, copy, modify, and/or distribute this software for any
// purpose with or without fee is hereby granted, provided that the above
// copyright notice and this permission notice appear in all copies.
//
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
// ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR
// IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
//
#import "CwlCatchException.h"
__attribute__((visibility("hidden")))
NSException* catchExceptionOfKind(Class __nonnull type, __attribute__((noescape)) void (^ __nonnull inBlock)()) {
@try {
inBlock();
} @catch (NSException *exception) {
if ([exception isKindOfClass:type]) {
return exception;
} else {
@throw;
}
}
return nil;
}
================================================
FILE: Example/Pods/Nimble/Sources/Lib/CwlPreconditionTesting/CwlCatchException/CwlCatchException/CwlCatchException.swift
================================================
//
// CwlCatchException.swift
// CwlAssertionTesting
//
// Created by Matt Gallagher on 2016/01/10.
// Copyright © 2016 Matt Gallagher ( http://cocoawithlove.com ). All rights reserved.
//
// Permission to use, copy, modify, and/or distribute this software for any
// purpose with or without fee is hereby granted, provided that the above
// copyright notice and this permission notice appear in all copies.
//
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
// ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR
// IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
//
import Foundation
// We can't simply cast to Self? in the catchInBlock method so we need this generic function wrapper to do the conversion for us. Mildly annoying.
private func catchReturnTypeConverter(_ type: T.Type, block: () -> Void) -> T? {
return catchExceptionOfKind(type, block) as? T
}
extension NSException {
public static func catchException(in block: () -> Void) -> Self? {
return catchReturnTypeConverter(self, block: block)
}
}
================================================
FILE: Example/Pods/Nimble/Sources/Lib/CwlPreconditionTesting/CwlPreconditionTesting/CwlBadInstructionException.swift
================================================
//
// CwlBadInstructionException.swift
// CwlPreconditionTesting
//
// Created by Matt Gallagher on 2016/01/10.
// Copyright © 2016 Matt Gallagher ( http://cocoawithlove.com ). All rights reserved.
//
// Permission to use, copy, modify, and/or distribute this software for any
// purpose with or without fee is hereby granted, provided that the above
// copyright notice and this permission notice appear in all copies.
//
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
// ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR
// IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
//
import Foundation
private func raiseBadInstructionException() {
BadInstructionException().raise()
}
/// A simple NSException subclass. It's not required to subclass NSException (since the exception type is represented in the name) but this helps for identifying the exception through runtime type.
@objc public class BadInstructionException: NSException {
static var name: String = "com.cocoawithlove.BadInstruction"
init() {
super.init(name: NSExceptionName(rawValue: BadInstructionException.name), reason: nil, userInfo: nil)
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
/// An Objective-C callable function, invoked from the `mach_exc_server` callback function `catch_mach_exception_raise_state` to push the `raiseBadInstructionException` function onto the stack.
public class func catch_mach_exception_raise_state(_ exception_port: mach_port_t, exception: exception_type_t, code: UnsafePointer, codeCnt: mach_msg_type_number_t, flavor: UnsafeMutablePointer, old_state: UnsafePointer, old_stateCnt: mach_msg_type_number_t, new_state: thread_state_t, new_stateCnt: UnsafeMutablePointer) -> kern_return_t {
#if arch(x86_64)
// Make sure we've been given enough memory
if old_stateCnt != x86_THREAD_STATE64_COUNT || new_stateCnt.pointee < x86_THREAD_STATE64_COUNT {
return KERN_INVALID_ARGUMENT
}
// Read the old thread state
var state = old_state.withMemoryRebound(to: x86_thread_state64_t.self, capacity: 1) { return $0.pointee }
// 1. Decrement the stack pointer
state.__rsp -= __uint64_t(MemoryLayout.size)
// 2. Save the old Instruction Pointer to the stack.
if let pointer = UnsafeMutablePointer<__uint64_t>(bitPattern: UInt(state.__rsp)) {
pointer.pointee = state.__rip
} else {
return KERN_INVALID_ARGUMENT
}
// 3. Set the Instruction Pointer to the new function's address
var f: @convention(c) () -> Void = raiseBadInstructionException
withUnsafePointer(to: &f) {
state.__rip = $0.withMemoryRebound(to: __uint64_t.self, capacity: 1) { return $0.pointee }
}
// Write the new thread state
new_state.withMemoryRebound(to: x86_thread_state64_t.self, capacity: 1) { $0.pointee = state }
new_stateCnt.pointee = x86_THREAD_STATE64_COUNT
return KERN_SUCCESS
#else
fatalError("Unavailable for this CPU architecture")
#endif
}
}
================================================
FILE: Example/Pods/Nimble/Sources/Lib/CwlPreconditionTesting/CwlPreconditionTesting/CwlCatchBadInstruction.h
================================================
//
// CwlCatchBadInstruction.h
// CwlPreconditionTesting
//
// Created by Matt Gallagher on 2016/01/10.
// Copyright © 2016 Matt Gallagher ( http://cocoawithlove.com ). All rights reserved.
//
// Permission to use, copy, modify, and/or distribute this software for any
// purpose with or without fee is hereby granted, provided that the above
// copyright notice and this permission notice appear in all copies.
//
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
// ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR
// IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
//
#if defined(__x86_64__)
#import
#import
NS_ASSUME_NONNULL_BEGIN
// The request_mach_exception_raise_t struct is passed to mach_msg which assumes its exact layout. To avoid problems with different layouts, we keep the definition in C rather than Swift.
typedef struct
{
mach_msg_header_t Head;
/* start of the kernel processed data */
mach_msg_body_t msgh_body;
mach_msg_port_descriptor_t thread;
mach_msg_port_descriptor_t task;
/* end of the kernel processed data */
NDR_record_t NDR;
exception_type_t exception;
mach_msg_type_number_t codeCnt;
int64_t code[2];
int flavor;
mach_msg_type_number_t old_stateCnt;
natural_t old_state[224];
} request_mach_exception_raise_t;
// The reply_mach_exception_raise_state_t struct is passed to mach_msg which assumes its exact layout. To avoid problems with different layouts, we keep the definition in C rather than Swift.
typedef struct
{
mach_msg_header_t Head;
NDR_record_t NDR;
kern_return_t RetCode;
int flavor;
mach_msg_type_number_t new_stateCnt;
natural_t new_state[224];
} reply_mach_exception_raise_state_t;
extern boolean_t mach_exc_server(mach_msg_header_t *InHeadP, mach_msg_header_t *OutHeadP);
NS_ASSUME_NONNULL_END
#endif
================================================
FILE: Example/Pods/Nimble/Sources/Lib/CwlPreconditionTesting/CwlPreconditionTesting/CwlCatchBadInstruction.m
================================================
//
// CwlCatchBadInstruction.m
// CwlPreconditionTesting
//
// Created by Matt Gallagher on 2016/01/10.
// Copyright © 2016 Matt Gallagher ( http://cocoawithlove.com ). All rights reserved.
//
// Permission to use, copy, modify, and/or distribute this software for any
// purpose with or without fee is hereby granted, provided that the above
// copyright notice and this permission notice appear in all copies.
//
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
// ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR
// IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
//
#if defined(__x86_64__)
#import "CwlCatchBadInstruction.h"
// Assuming the "PRODUCT_NAME" macro is defined, this will create the name of the Swift generated header file
#define STRINGIZE_NO_EXPANSION(A) #A
#define STRINGIZE_WITH_EXPANSION(A) STRINGIZE_NO_EXPANSION(A)
#define SWIFT_INCLUDE STRINGIZE_WITH_EXPANSION(PRODUCT_NAME-Swift.h)
// Include the Swift generated header file
#import SWIFT_INCLUDE
/// A basic function that receives callbacks from mach_exc_server and relays them to the Swift implemented BadInstructionException.catch_mach_exception_raise_state.
kern_return_t catch_mach_exception_raise_state(mach_port_t exception_port, exception_type_t exception, const mach_exception_data_t code, mach_msg_type_number_t codeCnt, int *flavor, const thread_state_t old_state, mach_msg_type_number_t old_stateCnt, thread_state_t new_state, mach_msg_type_number_t *new_stateCnt) {
return [BadInstructionException catch_mach_exception_raise_state:exception_port exception:exception code:code codeCnt:codeCnt flavor:flavor old_state:old_state old_stateCnt:old_stateCnt new_state:new_state new_stateCnt:new_stateCnt];
}
// The mach port should be configured so that this function is never used.
kern_return_t catch_mach_exception_raise(mach_port_t exception_port, mach_port_t thread, mach_port_t task, exception_type_t exception, mach_exception_data_t code, mach_msg_type_number_t codeCnt) {
assert(false);
return KERN_FAILURE;
}
// The mach port should be configured so that this function is never used.
kern_return_t catch_mach_exception_raise_state_identity(mach_port_t exception_port, mach_port_t thread, mach_port_t task, exception_type_t exception, mach_exception_data_t code, mach_msg_type_number_t codeCnt, int *flavor, thread_state_t old_state, mach_msg_type_number_t old_stateCnt, thread_state_t new_state, mach_msg_type_number_t *new_stateCnt) {
assert(false);
return KERN_FAILURE;
}
#endif
================================================
FILE: Example/Pods/Nimble/Sources/Lib/CwlPreconditionTesting/CwlPreconditionTesting/CwlCatchBadInstruction.swift
================================================
//
// CwlCatchBadInstruction.swift
// CwlPreconditionTesting
//
// Created by Matt Gallagher on 2016/01/10.
// Copyright © 2016 Matt Gallagher ( http://cocoawithlove.com ). All rights reserved.
//
// Permission to use, copy, modify, and/or distribute this software for any
// purpose with or without fee is hereby granted, provided that the above
// copyright notice and this permission notice appear in all copies.
//
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
// ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR
// IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
//
import Foundation
#if arch(x86_64)
private enum PthreadError: Error { case code(Int32) }
private enum MachExcServer: Error { case code(kern_return_t) }
/// A quick function for converting Mach error results into Swift errors
private func kernCheck(_ f: () -> Int32) throws {
let r = f()
guard r == KERN_SUCCESS else {
throw NSError(domain: NSMachErrorDomain, code: Int(r), userInfo: nil)
}
}
extension execTypesCountTuple {
mutating func pointer(in block: (UnsafeMutablePointer) -> R) -> R {
return withUnsafeMutablePointer(to: &self) { p -> R in
return p.withMemoryRebound(to: T.self, capacity: EXC_TYPES_COUNT) { ptr -> R in
return block(ptr)
}
}
}
}
extension request_mach_exception_raise_t {
mutating func withMsgHeaderPointer(in block: (UnsafeMutablePointer) -> R) -> R {
return withUnsafeMutablePointer(to: &self) { p -> R in
return p.withMemoryRebound(to: mach_msg_header_t.self, capacity: 1) { ptr -> R in
return block(ptr)
}
}
}
}
extension reply_mach_exception_raise_state_t {
mutating func withMsgHeaderPointer(in block: (UnsafeMutablePointer) -> R) -> R {
return withUnsafeMutablePointer(to: &self) { p -> R in
return p.withMemoryRebound(to: mach_msg_header_t.self, capacity: 1) { ptr -> R in
return block(ptr)
}
}
}
}
/// A structure used to store context associated with the Mach message port
private struct MachContext {
var masks = execTypesCountTuple()
var count: mach_msg_type_number_t = 0
var ports = execTypesCountTuple()
var behaviors = execTypesCountTuple()
var flavors = execTypesCountTuple()
var currentExceptionPort: mach_port_t = 0
var handlerThread: pthread_t? = nil
mutating func withUnsafeMutablePointers(in block: (UnsafeMutablePointer, UnsafeMutablePointer, UnsafeMutablePointer, UnsafeMutablePointer) -> R) -> R {
return masks.pointer { masksPtr in
return ports.pointer { portsPtr in
return behaviors.pointer { behaviorsPtr in
return flavors.pointer { flavorsPtr in
return block(masksPtr, portsPtr, behaviorsPtr, flavorsPtr)
}
}
}
}
}
}
/// A function for receiving mach messages and parsing the first with mach_exc_server (and if any others are received, throwing them away).
private func machMessageHandler(_ arg: UnsafeMutableRawPointer) -> UnsafeMutableRawPointer? {
let context = arg.assumingMemoryBound(to: MachContext.self).pointee
var request = request_mach_exception_raise_t()
var reply = reply_mach_exception_raise_state_t()
var handledfirstException = false
repeat { do {
// Request the next mach message from the port
request.Head.msgh_local_port = context.currentExceptionPort
request.Head.msgh_size = UInt32(MemoryLayout.size)
try kernCheck { request.withMsgHeaderPointer { requestPtr in
mach_msg(requestPtr, MACH_RCV_MSG | MACH_RCV_INTERRUPT, 0, request.Head.msgh_size, context.currentExceptionPort, 0, UInt32(MACH_PORT_NULL))
} }
// Prepare the reply structure
reply.Head.msgh_bits = MACH_MSGH_BITS(MACH_MSGH_BITS_REMOTE(request.Head.msgh_bits), 0)
reply.Head.msgh_local_port = UInt32(MACH_PORT_NULL)
reply.Head.msgh_remote_port = request.Head.msgh_remote_port
reply.Head.msgh_size = UInt32(MemoryLayout.size)
reply.NDR = NDR_record
if !handledfirstException {
// Use the MiG generated server to invoke our handler for the request and fill in the rest of the reply structure
guard request.withMsgHeaderPointer(in: { requestPtr in reply.withMsgHeaderPointer { replyPtr in
mach_exc_server(requestPtr, replyPtr)
} }) != 0 else { throw MachExcServer.code(reply.RetCode) }
handledfirstException = true
} else {
// If multiple fatal errors occur, don't handle subsquent errors (let the program crash)
reply.RetCode = KERN_FAILURE
}
// Send the reply
try kernCheck { reply.withMsgHeaderPointer { replyPtr in
mach_msg(replyPtr, MACH_SEND_MSG, reply.Head.msgh_size, 0, UInt32(MACH_PORT_NULL), 0, UInt32(MACH_PORT_NULL))
} }
} catch let error as NSError where (error.domain == NSMachErrorDomain && (error.code == Int(MACH_RCV_PORT_CHANGED) || error.code == Int(MACH_RCV_INVALID_NAME))) {
// Port was already closed before we started or closed while we were listening.
// This means the controlling thread shut down.
return nil
} catch {
// Should never be reached but this is testing code, don't try to recover, just abort
fatalError("Mach message error: \(error)")
} } while true
}
/// Run the provided block. If a mach "BAD_INSTRUCTION" exception is raised, catch it and return a BadInstructionException (which captures stack information about the throw site, if desired). Otherwise return nil.
/// NOTE: This function is only intended for use in test harnesses – use in a distributed build is almost certainly a bad choice. If a "BAD_INSTRUCTION" exception is raised, the block will be exited before completion via Objective-C exception. The risks associated with an Objective-C exception apply here: most Swift/Objective-C functions are *not* exception-safe. Memory may be leaked and the program will not necessarily be left in a safe state.
/// - parameter block: a function without parameters that will be run
/// - returns: if an EXC_BAD_INSTRUCTION is raised during the execution of `block` then a BadInstructionException will be returned, otherwise `nil`.
public func catchBadInstruction(in block: () -> Void) -> BadInstructionException? {
var context = MachContext()
var result: BadInstructionException? = nil
do {
var handlerThread: pthread_t? = nil
defer {
// 8. Wait for the thread to terminate *if* we actually made it to the creation point
// The mach port should be destroyed *before* calling pthread_join to avoid a deadlock.
if handlerThread != nil {
pthread_join(handlerThread!, nil)
}
}
try kernCheck {
// 1. Create the mach port
mach_port_allocate(mach_task_self_, MACH_PORT_RIGHT_RECEIVE, &context.currentExceptionPort)
}
defer {
// 7. Cleanup the mach port
mach_port_destroy(mach_task_self_, context.currentExceptionPort)
}
try kernCheck {
// 2. Configure the mach port
mach_port_insert_right(mach_task_self_, context.currentExceptionPort, context.currentExceptionPort, MACH_MSG_TYPE_MAKE_SEND)
}
try kernCheck { context.withUnsafeMutablePointers { masksPtr, portsPtr, behaviorsPtr, flavorsPtr in
// 3. Apply the mach port as the handler for this thread
thread_swap_exception_ports(mach_thread_self(), EXC_MASK_BAD_INSTRUCTION, context.currentExceptionPort, Int32(bitPattern: UInt32(EXCEPTION_STATE) | MACH_EXCEPTION_CODES), x86_THREAD_STATE64, masksPtr, &context.count, portsPtr, behaviorsPtr, flavorsPtr)
} }
defer { context.withUnsafeMutablePointers { masksPtr, portsPtr, behaviorsPtr, flavorsPtr in
// 6. Unapply the mach port
_ = thread_swap_exception_ports(mach_thread_self(), EXC_MASK_BAD_INSTRUCTION, 0, EXCEPTION_DEFAULT, THREAD_STATE_NONE, masksPtr, &context.count, portsPtr, behaviorsPtr, flavorsPtr)
} }
try withUnsafeMutablePointer(to: &context) { c throws in
// 4. Create the thread
let e = pthread_create(&handlerThread, nil, machMessageHandler, c)
guard e == 0 else { throw PthreadError.code(e) }
// 5. Run the block
result = BadInstructionException.catchException(in: block)
}
} catch {
// Should never be reached but this is testing code, don't try to recover, just abort
fatalError("Mach port error: \(error)")
}
return result
}
#endif
================================================
FILE: Example/Pods/Nimble/Sources/Lib/CwlPreconditionTesting/CwlPreconditionTesting/CwlDarwinDefinitions.swift
================================================
//
// CwlDarwinDefinitions.swift
// CwlPreconditionTesting
//
// Created by Matt Gallagher on 2016/01/10.
// Copyright © 2016 Matt Gallagher ( http://cocoawithlove.com ). All rights reserved.
//
// Permission to use, copy, modify, and/or distribute this software for any
// purpose with or without fee is hereby granted, provided that the above
// copyright notice and this permission notice appear in all copies.
//
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
// ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR
// IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
//
import Darwin
#if arch(x86_64)
// From /usr/include/mach/port.h
// #define MACH_PORT_RIGHT_RECEIVE ((mach_port_right_t) 1)
let MACH_PORT_RIGHT_RECEIVE: mach_port_right_t = 1
// From /usr/include/mach/message.h
// #define MACH_MSG_TYPE_MAKE_SEND 20 /* Must hold receive right */
// #define MACH_MSGH_BITS_REMOTE(bits) \
// ((bits) & MACH_MSGH_BITS_REMOTE_MASK)
// #define MACH_MSGH_BITS(remote, local) /* legacy */ \
// ((remote) | ((local) << 8))
let MACH_MSG_TYPE_MAKE_SEND: UInt32 = 20
func MACH_MSGH_BITS_REMOTE(_ bits: UInt32) -> UInt32 { return bits & UInt32(MACH_MSGH_BITS_REMOTE_MASK) }
func MACH_MSGH_BITS(_ remote: UInt32, _ local: UInt32) -> UInt32 { return ((remote) | ((local) << 8)) }
// From /usr/include/mach/exception_types.h
// #define EXC_BAD_INSTRUCTION 2 /* Instruction failed */
// #define EXC_MASK_BAD_INSTRUCTION (1 << EXC_BAD_INSTRUCTION)
// #define EXCEPTION_DEFAULT 1
let EXC_BAD_INSTRUCTION: UInt32 = 2
let EXC_MASK_BAD_INSTRUCTION: UInt32 = 1 << EXC_BAD_INSTRUCTION
let EXCEPTION_DEFAULT: Int32 = 1
// From /usr/include/mach/i386/thread_status.h
// #define THREAD_STATE_NONE 13
// #define x86_THREAD_STATE64_COUNT ((mach_msg_type_number_t) \
// ( sizeof (x86_thread_state64_t) / sizeof (int) ))
let THREAD_STATE_NONE: Int32 = 13
let x86_THREAD_STATE64_COUNT = UInt32(MemoryLayout.size / MemoryLayout.size)
let EXC_TYPES_COUNT = 14
struct execTypesCountTuple {
// From /usr/include/mach/i386/exception.h
// #define EXC_TYPES_COUNT 14 /* incl. illegal exception 0 */
var value: (T,T,T,T,T,T,T,T,T,T,T,T,T,T) = (0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0)
init() {
}
}
#endif
================================================
FILE: Example/Pods/Nimble/Sources/Lib/CwlPreconditionTesting/CwlPreconditionTesting/mach_excServer.c
================================================
/*
* IDENTIFICATION:
* stub generated Mon Jan 11 00:24:26 2016
* with a MiG generated by bootstrap_cmds-93
* OPTIONS:
*/
/* Module mach_exc */
#if defined(__x86_64__)
#define __MIG_check__Request__mach_exc_subsystem__ 1
#include "mach_excServer.h"
#ifndef mig_internal
#define mig_internal static __inline__
#endif /* mig_internal */
#ifndef mig_external
#define mig_external
#endif /* mig_external */
#if !defined(__MigTypeCheck) && defined(TypeCheck)
#define __MigTypeCheck TypeCheck /* Legacy setting */
#endif /* !defined(__MigTypeCheck) */
#if !defined(__MigKernelSpecificCode) && defined(_MIG_KERNEL_SPECIFIC_CODE_)
#define __MigKernelSpecificCode _MIG_KERNEL_SPECIFIC_CODE_ /* Legacy setting */
#endif /* !defined(__MigKernelSpecificCode) */
#ifndef LimitCheck
#define LimitCheck 0
#endif /* LimitCheck */
#ifndef min
#define min(a,b) ( ((a) < (b))? (a): (b) )
#endif /* min */
#if !defined(_WALIGN_)
#define _WALIGN_(x) (((x) + 3) & ~3)
#endif /* !defined(_WALIGN_) */
#if !defined(_WALIGNSZ_)
#define _WALIGNSZ_(x) _WALIGN_(sizeof(x))
#endif /* !defined(_WALIGNSZ_) */
#ifndef UseStaticTemplates
#define UseStaticTemplates 0
#endif /* UseStaticTemplates */
#ifndef __DeclareRcvRpc
#define __DeclareRcvRpc(_NUM_, _NAME_)
#endif /* __DeclareRcvRpc */
#ifndef __BeforeRcvRpc
#define __BeforeRcvRpc(_NUM_, _NAME_)
#endif /* __BeforeRcvRpc */
#ifndef __AfterRcvRpc
#define __AfterRcvRpc(_NUM_, _NAME_)
#endif /* __AfterRcvRpc */
#ifndef __DeclareRcvSimple
#define __DeclareRcvSimple(_NUM_, _NAME_)
#endif /* __DeclareRcvSimple */
#ifndef __BeforeRcvSimple
#define __BeforeRcvSimple(_NUM_, _NAME_)
#endif /* __BeforeRcvSimple */
#ifndef __AfterRcvSimple
#define __AfterRcvSimple(_NUM_, _NAME_)
#endif /* __AfterRcvSimple */
#define novalue void
#define msgh_request_port msgh_local_port
#define MACH_MSGH_BITS_REQUEST(bits) MACH_MSGH_BITS_LOCAL(bits)
#define msgh_reply_port msgh_remote_port
#define MACH_MSGH_BITS_REPLY(bits) MACH_MSGH_BITS_REMOTE(bits)
#define MIG_RETURN_ERROR(X, code) {\
((mig_reply_error_t *)X)->RetCode = code;\
((mig_reply_error_t *)X)->NDR = NDR_record;\
return;\
}
/* Forward Declarations */
mig_internal novalue _Xmach_exception_raise
(mach_msg_header_t *InHeadP, mach_msg_header_t *OutHeadP);
mig_internal novalue _Xmach_exception_raise_state
(mach_msg_header_t *InHeadP, mach_msg_header_t *OutHeadP);
mig_internal novalue _Xmach_exception_raise_state_identity
(mach_msg_header_t *InHeadP, mach_msg_header_t *OutHeadP);
#if ( __MigTypeCheck )
#if __MIG_check__Request__mach_exc_subsystem__
#if !defined(__MIG_check__Request__mach_exception_raise_t__defined)
#define __MIG_check__Request__mach_exception_raise_t__defined
mig_internal kern_return_t __MIG_check__Request__mach_exception_raise_t(__attribute__((__unused__)) __Request__mach_exception_raise_t *In0P)
{
typedef __Request__mach_exception_raise_t __Request;
#if __MigTypeCheck
unsigned int msgh_size;
#endif /* __MigTypeCheck */
#if __MigTypeCheck
msgh_size = In0P->Head.msgh_size;
if (!(In0P->Head.msgh_bits & MACH_MSGH_BITS_COMPLEX) ||
(In0P->msgh_body.msgh_descriptor_count != 2) ||
(msgh_size < (mach_msg_size_t)(sizeof(__Request) - 16)) || (msgh_size > (mach_msg_size_t)sizeof(__Request)))
return MIG_BAD_ARGUMENTS;
#endif /* __MigTypeCheck */
#if __MigTypeCheck
if (In0P->thread.type != MACH_MSG_PORT_DESCRIPTOR ||
In0P->thread.disposition != 17)
return MIG_TYPE_ERROR;
#endif /* __MigTypeCheck */
#if __MigTypeCheck
if (In0P->task.type != MACH_MSG_PORT_DESCRIPTOR ||
In0P->task.disposition != 17)
return MIG_TYPE_ERROR;
#endif /* __MigTypeCheck */
#if defined(__NDR_convert__int_rep__Request__mach_exception_raise_t__codeCnt__defined)
if (In0P->NDR.int_rep != NDR_record.int_rep)
__NDR_convert__int_rep__Request__mach_exception_raise_t__codeCnt(&In0P->codeCnt, In0P->NDR.int_rep);
#endif /* __NDR_convert__int_rep__Request__mach_exception_raise_t__codeCnt__defined */
#if __MigTypeCheck
if ( In0P->codeCnt > 2 )
return MIG_BAD_ARGUMENTS;
if (((msgh_size - (mach_msg_size_t)(sizeof(__Request) - 16)) / 8 < In0P->codeCnt) ||
(msgh_size != (mach_msg_size_t)(sizeof(__Request) - 16) + (8 * In0P->codeCnt)))
return MIG_BAD_ARGUMENTS;
#endif /* __MigTypeCheck */
return MACH_MSG_SUCCESS;
}
#endif /* !defined(__MIG_check__Request__mach_exception_raise_t__defined) */
#endif /* __MIG_check__Request__mach_exc_subsystem__ */
#endif /* ( __MigTypeCheck ) */
/* Routine mach_exception_raise */
mig_internal novalue _Xmach_exception_raise
(mach_msg_header_t *InHeadP, mach_msg_header_t *OutHeadP)
{
#ifdef __MigPackStructs
#pragma pack(4)
#endif
typedef struct {
mach_msg_header_t Head;
/* start of the kernel processed data */
mach_msg_body_t msgh_body;
mach_msg_port_descriptor_t thread;
mach_msg_port_descriptor_t task;
/* end of the kernel processed data */
NDR_record_t NDR;
exception_type_t exception;
mach_msg_type_number_t codeCnt;
int64_t code[2];
mach_msg_trailer_t trailer;
} Request __attribute__((unused));
#ifdef __MigPackStructs
#pragma pack()
#endif
typedef __Request__mach_exception_raise_t __Request;
typedef __Reply__mach_exception_raise_t Reply __attribute__((unused));
/*
* typedef struct {
* mach_msg_header_t Head;
* NDR_record_t NDR;
* kern_return_t RetCode;
* } mig_reply_error_t;
*/
Request *In0P = (Request *) InHeadP;
Reply *OutP = (Reply *) OutHeadP;
#ifdef __MIG_check__Request__mach_exception_raise_t__defined
kern_return_t check_result;
#endif /* __MIG_check__Request__mach_exception_raise_t__defined */
__DeclareRcvRpc(2405, "mach_exception_raise")
__BeforeRcvRpc(2405, "mach_exception_raise")
#if defined(__MIG_check__Request__mach_exception_raise_t__defined)
check_result = __MIG_check__Request__mach_exception_raise_t((__Request *)In0P);
if (check_result != MACH_MSG_SUCCESS)
{ MIG_RETURN_ERROR(OutP, check_result); }
#endif /* defined(__MIG_check__Request__mach_exception_raise_t__defined) */
OutP->RetCode = catch_mach_exception_raise(In0P->Head.msgh_request_port, In0P->thread.name, In0P->task.name, In0P->exception, In0P->code, In0P->codeCnt);
OutP->NDR = NDR_record;
__AfterRcvRpc(2405, "mach_exception_raise")
}
#if ( __MigTypeCheck )
#if __MIG_check__Request__mach_exc_subsystem__
#if !defined(__MIG_check__Request__mach_exception_raise_state_t__defined)
#define __MIG_check__Request__mach_exception_raise_state_t__defined
mig_internal kern_return_t __MIG_check__Request__mach_exception_raise_state_t(__attribute__((__unused__)) __Request__mach_exception_raise_state_t *In0P, __attribute__((__unused__)) __Request__mach_exception_raise_state_t **In1PP)
{
typedef __Request__mach_exception_raise_state_t __Request;
__Request *In1P;
#if __MigTypeCheck
unsigned int msgh_size;
#endif /* __MigTypeCheck */
unsigned int msgh_size_delta;
#if __MigTypeCheck
msgh_size = In0P->Head.msgh_size;
if ((In0P->Head.msgh_bits & MACH_MSGH_BITS_COMPLEX) ||
(msgh_size < (mach_msg_size_t)(sizeof(__Request) - 912)) || (msgh_size > (mach_msg_size_t)sizeof(__Request)))
return MIG_BAD_ARGUMENTS;
#endif /* __MigTypeCheck */
#if defined(__NDR_convert__int_rep__Request__mach_exception_raise_state_t__codeCnt__defined)
if (In0P->NDR.int_rep != NDR_record.int_rep)
__NDR_convert__int_rep__Request__mach_exception_raise_state_t__codeCnt(&In0P->codeCnt, In0P->NDR.int_rep);
#endif /* __NDR_convert__int_rep__Request__mach_exception_raise_state_t__codeCnt__defined */
msgh_size_delta = (8 * In0P->codeCnt);
#if __MigTypeCheck
if ( In0P->codeCnt > 2 )
return MIG_BAD_ARGUMENTS;
if (((msgh_size - (mach_msg_size_t)(sizeof(__Request) - 912)) / 8 < In0P->codeCnt) ||
(msgh_size < (mach_msg_size_t)(sizeof(__Request) - 912) + (8 * In0P->codeCnt)))
return MIG_BAD_ARGUMENTS;
msgh_size -= msgh_size_delta;
#endif /* __MigTypeCheck */
*In1PP = In1P = (__Request *) ((pointer_t) In0P + msgh_size_delta - 16);
#if defined(__NDR_convert__int_rep__Request__mach_exception_raise_state_t__old_stateCnt__defined)
if (In0P->NDR.int_rep != NDR_record.int_rep)
__NDR_convert__int_rep__Request__mach_exception_raise_state_t__old_stateCnt(&In1P->old_stateCnt, In1P->NDR.int_rep);
#endif /* __NDR_convert__int_rep__Request__mach_exception_raise_state_t__old_stateCnt__defined */
#if __MigTypeCheck
if ( In1P->old_stateCnt > 224 )
return MIG_BAD_ARGUMENTS;
if (((msgh_size - (mach_msg_size_t)(sizeof(__Request) - 912)) / 4 < In1P->old_stateCnt) ||
(msgh_size != (mach_msg_size_t)(sizeof(__Request) - 912) + (4 * In1P->old_stateCnt)))
return MIG_BAD_ARGUMENTS;
#endif /* __MigTypeCheck */
return MACH_MSG_SUCCESS;
}
#endif /* !defined(__MIG_check__Request__mach_exception_raise_state_t__defined) */
#endif /* __MIG_check__Request__mach_exc_subsystem__ */
#endif /* ( __MigTypeCheck ) */
/* Routine mach_exception_raise_state */
mig_internal novalue _Xmach_exception_raise_state
(mach_msg_header_t *InHeadP, mach_msg_header_t *OutHeadP)
{
#ifdef __MigPackStructs
#pragma pack(4)
#endif
typedef struct {
mach_msg_header_t Head;
NDR_record_t NDR;
exception_type_t exception;
mach_msg_type_number_t codeCnt;
int64_t code[2];
int flavor;
mach_msg_type_number_t old_stateCnt;
natural_t old_state[224];
mach_msg_trailer_t trailer;
} Request __attribute__((unused));
#ifdef __MigPackStructs
#pragma pack()
#endif
typedef __Request__mach_exception_raise_state_t __Request;
typedef __Reply__mach_exception_raise_state_t Reply __attribute__((unused));
/*
* typedef struct {
* mach_msg_header_t Head;
* NDR_record_t NDR;
* kern_return_t RetCode;
* } mig_reply_error_t;
*/
Request *In0P = (Request *) InHeadP;
Request *In1P;
Reply *OutP = (Reply *) OutHeadP;
#ifdef __MIG_check__Request__mach_exception_raise_state_t__defined
kern_return_t check_result;
#endif /* __MIG_check__Request__mach_exception_raise_state_t__defined */
__DeclareRcvRpc(2406, "mach_exception_raise_state")
__BeforeRcvRpc(2406, "mach_exception_raise_state")
#if defined(__MIG_check__Request__mach_exception_raise_state_t__defined)
check_result = __MIG_check__Request__mach_exception_raise_state_t((__Request *)In0P, (__Request **)&In1P);
if (check_result != MACH_MSG_SUCCESS)
{ MIG_RETURN_ERROR(OutP, check_result); }
#endif /* defined(__MIG_check__Request__mach_exception_raise_state_t__defined) */
OutP->new_stateCnt = 224;
OutP->RetCode = catch_mach_exception_raise_state(In0P->Head.msgh_request_port, In0P->exception, In0P->code, In0P->codeCnt, &In1P->flavor, In1P->old_state, In1P->old_stateCnt, OutP->new_state, &OutP->new_stateCnt);
if (OutP->RetCode != KERN_SUCCESS) {
MIG_RETURN_ERROR(OutP, OutP->RetCode);
}
OutP->NDR = NDR_record;
OutP->flavor = In1P->flavor;
OutP->Head.msgh_size = (mach_msg_size_t)(sizeof(Reply) - 896) + (((4 * OutP->new_stateCnt)));
__AfterRcvRpc(2406, "mach_exception_raise_state")
}
#if ( __MigTypeCheck )
#if __MIG_check__Request__mach_exc_subsystem__
#if !defined(__MIG_check__Request__mach_exception_raise_state_identity_t__defined)
#define __MIG_check__Request__mach_exception_raise_state_identity_t__defined
mig_internal kern_return_t __MIG_check__Request__mach_exception_raise_state_identity_t(__attribute__((__unused__)) __Request__mach_exception_raise_state_identity_t *In0P, __attribute__((__unused__)) __Request__mach_exception_raise_state_identity_t **In1PP)
{
typedef __Request__mach_exception_raise_state_identity_t __Request;
__Request *In1P;
#if __MigTypeCheck
unsigned int msgh_size;
#endif /* __MigTypeCheck */
unsigned int msgh_size_delta;
#if __MigTypeCheck
msgh_size = In0P->Head.msgh_size;
if (!(In0P->Head.msgh_bits & MACH_MSGH_BITS_COMPLEX) ||
(In0P->msgh_body.msgh_descriptor_count != 2) ||
(msgh_size < (mach_msg_size_t)(sizeof(__Request) - 912)) || (msgh_size > (mach_msg_size_t)sizeof(__Request)))
return MIG_BAD_ARGUMENTS;
#endif /* __MigTypeCheck */
#if __MigTypeCheck
if (In0P->thread.type != MACH_MSG_PORT_DESCRIPTOR ||
In0P->thread.disposition != 17)
return MIG_TYPE_ERROR;
#endif /* __MigTypeCheck */
#if __MigTypeCheck
if (In0P->task.type != MACH_MSG_PORT_DESCRIPTOR ||
In0P->task.disposition != 17)
return MIG_TYPE_ERROR;
#endif /* __MigTypeCheck */
#if defined(__NDR_convert__int_rep__Request__mach_exception_raise_state_identity_t__codeCnt__defined)
if (In0P->NDR.int_rep != NDR_record.int_rep)
__NDR_convert__int_rep__Request__mach_exception_raise_state_identity_t__codeCnt(&In0P->codeCnt, In0P->NDR.int_rep);
#endif /* __NDR_convert__int_rep__Request__mach_exception_raise_state_identity_t__codeCnt__defined */
msgh_size_delta = (8 * In0P->codeCnt);
#if __MigTypeCheck
if ( In0P->codeCnt > 2 )
return MIG_BAD_ARGUMENTS;
if (((msgh_size - (mach_msg_size_t)(sizeof(__Request) - 912)) / 8 < In0P->codeCnt) ||
(msgh_size < (mach_msg_size_t)(sizeof(__Request) - 912) + (8 * In0P->codeCnt)))
return MIG_BAD_ARGUMENTS;
msgh_size -= msgh_size_delta;
#endif /* __MigTypeCheck */
*In1PP = In1P = (__Request *) ((pointer_t) In0P + msgh_size_delta - 16);
#if defined(__NDR_convert__int_rep__Request__mach_exception_raise_state_identity_t__old_stateCnt__defined)
if (In0P->NDR.int_rep != NDR_record.int_rep)
__NDR_convert__int_rep__Request__mach_exception_raise_state_identity_t__old_stateCnt(&In1P->old_stateCnt, In1P->NDR.int_rep);
#endif /* __NDR_convert__int_rep__Request__mach_exception_raise_state_identity_t__old_stateCnt__defined */
#if __MigTypeCheck
if ( In1P->old_stateCnt > 224 )
return MIG_BAD_ARGUMENTS;
if (((msgh_size - (mach_msg_size_t)(sizeof(__Request) - 912)) / 4 < In1P->old_stateCnt) ||
(msgh_size != (mach_msg_size_t)(sizeof(__Request) - 912) + (4 * In1P->old_stateCnt)))
return MIG_BAD_ARGUMENTS;
#endif /* __MigTypeCheck */
return MACH_MSG_SUCCESS;
}
#endif /* !defined(__MIG_check__Request__mach_exception_raise_state_identity_t__defined) */
#endif /* __MIG_check__Request__mach_exc_subsystem__ */
#endif /* ( __MigTypeCheck ) */
/* Routine mach_exception_raise_state_identity */
mig_internal novalue _Xmach_exception_raise_state_identity
(mach_msg_header_t *InHeadP, mach_msg_header_t *OutHeadP)
{
#ifdef __MigPackStructs
#pragma pack(4)
#endif
typedef struct {
mach_msg_header_t Head;
/* start of the kernel processed data */
mach_msg_body_t msgh_body;
mach_msg_port_descriptor_t thread;
mach_msg_port_descriptor_t task;
/* end of the kernel processed data */
NDR_record_t NDR;
exception_type_t exception;
mach_msg_type_number_t codeCnt;
int64_t code[2];
int flavor;
mach_msg_type_number_t old_stateCnt;
natural_t old_state[224];
mach_msg_trailer_t trailer;
} Request __attribute__((unused));
#ifdef __MigPackStructs
#pragma pack()
#endif
typedef __Request__mach_exception_raise_state_identity_t __Request;
typedef __Reply__mach_exception_raise_state_identity_t Reply __attribute__((unused));
/*
* typedef struct {
* mach_msg_header_t Head;
* NDR_record_t NDR;
* kern_return_t RetCode;
* } mig_reply_error_t;
*/
Request *In0P = (Request *) InHeadP;
Request *In1P;
Reply *OutP = (Reply *) OutHeadP;
#ifdef __MIG_check__Request__mach_exception_raise_state_identity_t__defined
kern_return_t check_result;
#endif /* __MIG_check__Request__mach_exception_raise_state_identity_t__defined */
__DeclareRcvRpc(2407, "mach_exception_raise_state_identity")
__BeforeRcvRpc(2407, "mach_exception_raise_state_identity")
#if defined(__MIG_check__Request__mach_exception_raise_state_identity_t__defined)
check_result = __MIG_check__Request__mach_exception_raise_state_identity_t((__Request *)In0P, (__Request **)&In1P);
if (check_result != MACH_MSG_SUCCESS)
{ MIG_RETURN_ERROR(OutP, check_result); }
#endif /* defined(__MIG_check__Request__mach_exception_raise_state_identity_t__defined) */
OutP->new_stateCnt = 224;
OutP->RetCode = catch_mach_exception_raise_state_identity(In0P->Head.msgh_request_port, In0P->thread.name, In0P->task.name, In0P->exception, In0P->code, In0P->codeCnt, &In1P->flavor, In1P->old_state, In1P->old_stateCnt, OutP->new_state, &OutP->new_stateCnt);
if (OutP->RetCode != KERN_SUCCESS) {
MIG_RETURN_ERROR(OutP, OutP->RetCode);
}
OutP->NDR = NDR_record;
OutP->flavor = In1P->flavor;
OutP->Head.msgh_size = (mach_msg_size_t)(sizeof(Reply) - 896) + (((4 * OutP->new_stateCnt)));
__AfterRcvRpc(2407, "mach_exception_raise_state_identity")
}
/* Description of this subsystem, for use in direct RPC */
const struct catch_mach_exc_subsystem catch_mach_exc_subsystem = {
mach_exc_server_routine,
2405,
2408,
(mach_msg_size_t)sizeof(union __ReplyUnion__catch_mach_exc_subsystem),
(vm_address_t)0,
{
{ (mig_impl_routine_t) 0,
(mig_stub_routine_t) _Xmach_exception_raise, 6, 0, (routine_arg_descriptor_t)0, (mach_msg_size_t)sizeof(__Reply__mach_exception_raise_t)},
{ (mig_impl_routine_t) 0,
(mig_stub_routine_t) _Xmach_exception_raise_state, 9, 0, (routine_arg_descriptor_t)0, (mach_msg_size_t)sizeof(__Reply__mach_exception_raise_state_t)},
{ (mig_impl_routine_t) 0,
(mig_stub_routine_t) _Xmach_exception_raise_state_identity, 11, 0, (routine_arg_descriptor_t)0, (mach_msg_size_t)sizeof(__Reply__mach_exception_raise_state_identity_t)},
}
};
mig_external boolean_t mach_exc_server
(mach_msg_header_t *InHeadP, mach_msg_header_t *OutHeadP)
{
/*
* typedef struct {
* mach_msg_header_t Head;
* NDR_record_t NDR;
* kern_return_t RetCode;
* } mig_reply_error_t;
*/
register mig_routine_t routine;
OutHeadP->msgh_bits = MACH_MSGH_BITS(MACH_MSGH_BITS_REPLY(InHeadP->msgh_bits), 0);
OutHeadP->msgh_remote_port = InHeadP->msgh_reply_port;
/* Minimal size: routine() will update it if different */
OutHeadP->msgh_size = (mach_msg_size_t)sizeof(mig_reply_error_t);
OutHeadP->msgh_local_port = MACH_PORT_NULL;
OutHeadP->msgh_id = InHeadP->msgh_id + 100;
if ((InHeadP->msgh_id > 2407) || (InHeadP->msgh_id < 2405) ||
((routine = catch_mach_exc_subsystem.routine[InHeadP->msgh_id - 2405].stub_routine) == 0)) {
((mig_reply_error_t *)OutHeadP)->NDR = NDR_record;
((mig_reply_error_t *)OutHeadP)->RetCode = MIG_BAD_ID;
return FALSE;
}
(*routine) (InHeadP, OutHeadP);
return TRUE;
}
mig_external mig_routine_t mach_exc_server_routine
(mach_msg_header_t *InHeadP)
{
register int msgh_id;
msgh_id = InHeadP->msgh_id - 2405;
if ((msgh_id > 2) || (msgh_id < 0))
return 0;
return catch_mach_exc_subsystem.routine[msgh_id].stub_routine;
}
#endif
================================================
FILE: Example/Pods/Nimble/Sources/Lib/CwlPreconditionTesting/CwlPreconditionTesting/mach_excServer.h
================================================
#ifndef _mach_exc_server_
#define _mach_exc_server_
/* Module mach_exc */
#include
#include
#include
#include
#include
#include
#include
#include
#include
/* BEGIN VOUCHER CODE */
#ifndef KERNEL
#if defined(__has_include)
#if __has_include()
#ifndef USING_VOUCHERS
#define USING_VOUCHERS
#endif
#ifndef __VOUCHER_FORWARD_TYPE_DECLS__
#define __VOUCHER_FORWARD_TYPE_DECLS__
#ifdef __cplusplus
extern "C" {
#endif
extern boolean_t voucher_mach_msg_set(mach_msg_header_t *msg) __attribute__((weak_import));
#ifdef __cplusplus
}
#endif
#endif // __VOUCHER_FORWARD_TYPE_DECLS__
#endif // __has_include()
#endif // __has_include
#endif // !KERNEL
/* END VOUCHER CODE */
#ifdef AUTOTEST
#ifndef FUNCTION_PTR_T
#define FUNCTION_PTR_T
typedef void (*function_ptr_t)(mach_port_t, char *, mach_msg_type_number_t);
typedef struct {
char *name;
function_ptr_t function;
} function_table_entry;
typedef function_table_entry *function_table_t;
#endif /* FUNCTION_PTR_T */
#endif /* AUTOTEST */
#ifndef mach_exc_MSG_COUNT
#define mach_exc_MSG_COUNT 3
#endif /* mach_exc_MSG_COUNT */
#include
#include
#include
#include
#ifdef __BeforeMigServerHeader
__BeforeMigServerHeader
#endif /* __BeforeMigServerHeader */
/* Routine mach_exception_raise */
#ifdef mig_external
mig_external
#else
extern
#endif /* mig_external */
kern_return_t catch_mach_exception_raise
(
mach_port_t exception_port,
mach_port_t thread,
mach_port_t task,
exception_type_t exception,
mach_exception_data_t code,
mach_msg_type_number_t codeCnt
);
/* Routine mach_exception_raise_state */
#ifdef mig_external
mig_external
#else
extern
#endif /* mig_external */
kern_return_t catch_mach_exception_raise_state
(
mach_port_t exception_port,
exception_type_t exception,
const mach_exception_data_t code,
mach_msg_type_number_t codeCnt,
int *flavor,
const thread_state_t old_state,
mach_msg_type_number_t old_stateCnt,
thread_state_t new_state,
mach_msg_type_number_t *new_stateCnt
);
/* Routine mach_exception_raise_state_identity */
#ifdef mig_external
mig_external
#else
extern
#endif /* mig_external */
kern_return_t catch_mach_exception_raise_state_identity
(
mach_port_t exception_port,
mach_port_t thread,
mach_port_t task,
exception_type_t exception,
mach_exception_data_t code,
mach_msg_type_number_t codeCnt,
int *flavor,
thread_state_t old_state,
mach_msg_type_number_t old_stateCnt,
thread_state_t new_state,
mach_msg_type_number_t *new_stateCnt
);
#ifdef mig_external
mig_external
#else
extern
#endif /* mig_external */
boolean_t mach_exc_server(
mach_msg_header_t *InHeadP,
mach_msg_header_t *OutHeadP);
#ifdef mig_external
mig_external
#else
extern
#endif /* mig_external */
mig_routine_t mach_exc_server_routine(
mach_msg_header_t *InHeadP);
/* Description of this subsystem, for use in direct RPC */
extern const struct catch_mach_exc_subsystem {
mig_server_routine_t server; /* Server routine */
mach_msg_id_t start; /* Min routine number */
mach_msg_id_t end; /* Max routine number + 1 */
unsigned int maxsize; /* Max msg size */
vm_address_t reserved; /* Reserved */
struct routine_descriptor /*Array of routine descriptors */
routine[3];
} catch_mach_exc_subsystem;
/* typedefs for all requests */
#ifndef __Request__mach_exc_subsystem__defined
#define __Request__mach_exc_subsystem__defined
#ifdef __MigPackStructs
#pragma pack(4)
#endif
typedef struct {
mach_msg_header_t Head;
/* start of the kernel processed data */
mach_msg_body_t msgh_body;
mach_msg_port_descriptor_t thread;
mach_msg_port_descriptor_t task;
/* end of the kernel processed data */
NDR_record_t NDR;
exception_type_t exception;
mach_msg_type_number_t codeCnt;
int64_t code[2];
} __Request__mach_exception_raise_t __attribute__((unused));
#ifdef __MigPackStructs
#pragma pack()
#endif
#ifdef __MigPackStructs
#pragma pack(4)
#endif
typedef struct {
mach_msg_header_t Head;
NDR_record_t NDR;
exception_type_t exception;
mach_msg_type_number_t codeCnt;
int64_t code[2];
int flavor;
mach_msg_type_number_t old_stateCnt;
natural_t old_state[224];
} __Request__mach_exception_raise_state_t __attribute__((unused));
#ifdef __MigPackStructs
#pragma pack()
#endif
#ifdef __MigPackStructs
#pragma pack(4)
#endif
typedef struct {
mach_msg_header_t Head;
/* start of the kernel processed data */
mach_msg_body_t msgh_body;
mach_msg_port_descriptor_t thread;
mach_msg_port_descriptor_t task;
/* end of the kernel processed data */
NDR_record_t NDR;
exception_type_t exception;
mach_msg_type_number_t codeCnt;
int64_t code[2];
int flavor;
mach_msg_type_number_t old_stateCnt;
natural_t old_state[224];
} __Request__mach_exception_raise_state_identity_t __attribute__((unused));
#ifdef __MigPackStructs
#pragma pack()
#endif
#endif /* !__Request__mach_exc_subsystem__defined */
/* union of all requests */
#ifndef __RequestUnion__catch_mach_exc_subsystem__defined
#define __RequestUnion__catch_mach_exc_subsystem__defined
union __RequestUnion__catch_mach_exc_subsystem {
__Request__mach_exception_raise_t Request_mach_exception_raise;
__Request__mach_exception_raise_state_t Request_mach_exception_raise_state;
__Request__mach_exception_raise_state_identity_t Request_mach_exception_raise_state_identity;
};
#endif /* __RequestUnion__catch_mach_exc_subsystem__defined */
/* typedefs for all replies */
#ifndef __Reply__mach_exc_subsystem__defined
#define __Reply__mach_exc_subsystem__defined
#ifdef __MigPackStructs
#pragma pack(4)
#endif
typedef struct {
mach_msg_header_t Head;
NDR_record_t NDR;
kern_return_t RetCode;
} __Reply__mach_exception_raise_t __attribute__((unused));
#ifdef __MigPackStructs
#pragma pack()
#endif
#ifdef __MigPackStructs
#pragma pack(4)
#endif
typedef struct {
mach_msg_header_t Head;
NDR_record_t NDR;
kern_return_t RetCode;
int flavor;
mach_msg_type_number_t new_stateCnt;
natural_t new_state[224];
} __Reply__mach_exception_raise_state_t __attribute__((unused));
#ifdef __MigPackStructs
#pragma pack()
#endif
#ifdef __MigPackStructs
#pragma pack(4)
#endif
typedef struct {
mach_msg_header_t Head;
NDR_record_t NDR;
kern_return_t RetCode;
int flavor;
mach_msg_type_number_t new_stateCnt;
natural_t new_state[224];
} __Reply__mach_exception_raise_state_identity_t __attribute__((unused));
#ifdef __MigPackStructs
#pragma pack()
#endif
#endif /* !__Reply__mach_exc_subsystem__defined */
/* union of all replies */
#ifndef __ReplyUnion__catch_mach_exc_subsystem__defined
#define __ReplyUnion__catch_mach_exc_subsystem__defined
union __ReplyUnion__catch_mach_exc_subsystem {
__Reply__mach_exception_raise_t Reply_mach_exception_raise;
__Reply__mach_exception_raise_state_t Reply_mach_exception_raise_state;
__Reply__mach_exception_raise_state_identity_t Reply_mach_exception_raise_state_identity;
};
#endif /* __RequestUnion__catch_mach_exc_subsystem__defined */
#ifndef subsystem_to_name_map_mach_exc
#define subsystem_to_name_map_mach_exc \
{ "mach_exception_raise", 2405 },\
{ "mach_exception_raise_state", 2406 },\
{ "mach_exception_raise_state_identity", 2407 }
#endif
#ifdef __AfterMigServerHeader
__AfterMigServerHeader
#endif /* __AfterMigServerHeader */
#endif /* _mach_exc_server_ */
================================================
FILE: Example/Pods/Nimble/Sources/Nimble/Adapters/AdapterProtocols.swift
================================================
import Foundation
/// Protocol for the assertion handler that Nimble uses for all expectations.
public protocol AssertionHandler {
func assert(_ assertion: Bool, message: FailureMessage, location: SourceLocation)
}
/// Global backing interface for assertions that Nimble creates.
/// Defaults to a private test handler that passes through to XCTest.
///
/// If XCTest is not available, you must assign your own assertion handler
/// before using any matchers, otherwise Nimble will abort the program.
///
/// @see AssertionHandler
public var NimbleAssertionHandler: AssertionHandler = { () -> AssertionHandler in
return isXCTestAvailable() ? NimbleXCTestHandler() : NimbleXCTestUnavailableHandler()
}()
================================================
FILE: Example/Pods/Nimble/Sources/Nimble/Adapters/AssertionDispatcher.swift
================================================
/// AssertionDispatcher allows multiple AssertionHandlers to receive
/// assertion messages.
///
/// @warning Does not fully dispatch if one of the handlers raises an exception.
/// This is possible with XCTest-based assertion handlers.
///
public class AssertionDispatcher: AssertionHandler {
let handlers: [AssertionHandler]
public init(handlers: [AssertionHandler]) {
self.handlers = handlers
}
public func assert(_ assertion: Bool, message: FailureMessage, location: SourceLocation) {
for handler in handlers {
handler.assert(assertion, message: message, location: location)
}
}
}
================================================
FILE: Example/Pods/Nimble/Sources/Nimble/Adapters/AssertionRecorder.swift
================================================
import Foundation
/// A data structure that stores information about an assertion when
/// AssertionRecorder is set as the Nimble assertion handler.
///
/// @see AssertionRecorder
/// @see AssertionHandler
public struct AssertionRecord: CustomStringConvertible {
/// Whether the assertion succeeded or failed
public let success: Bool
/// The failure message the assertion would display on failure.
public let message: FailureMessage
/// The source location the expectation occurred on.
public let location: SourceLocation
public var description: String {
return "AssertionRecord { success=\(success), message='\(message.stringValue)', location=\(location) }"
}
}
/// An AssertionHandler that silently records assertions that Nimble makes.
/// This is useful for testing failure messages for matchers.
///
/// @see AssertionHandler
public class AssertionRecorder : AssertionHandler {
/// All the assertions that were captured by this recorder
public var assertions = [AssertionRecord]()
public init() {}
public func assert(_ assertion: Bool, message: FailureMessage, location: SourceLocation) {
assertions.append(
AssertionRecord(
success: assertion,
message: message,
location: location))
}
}
/// Allows you to temporarily replace the current Nimble assertion handler with
/// the one provided for the scope of the closure.
///
/// Once the closure finishes, then the original Nimble assertion handler is restored.
///
/// @see AssertionHandler
public func withAssertionHandler(_ tempAssertionHandler: AssertionHandler, closure: @escaping () throws -> Void) {
let environment = NimbleEnvironment.activeInstance
let oldRecorder = environment.assertionHandler
let capturer = NMBExceptionCapture(handler: nil, finally: ({
environment.assertionHandler = oldRecorder
}))
environment.assertionHandler = tempAssertionHandler
capturer.tryBlock {
try! closure()
}
}
/// Captures expectations that occur in the given closure. Note that all
/// expectations will still go through to the default Nimble handler.
///
/// This can be useful if you want to gather information about expectations
/// that occur within a closure.
///
/// @param silently expectations are no longer send to the default Nimble
/// assertion handler when this is true. Defaults to false.
///
/// @see gatherFailingExpectations
public func gatherExpectations(silently: Bool = false, closure: @escaping () -> Void) -> [AssertionRecord] {
let previousRecorder = NimbleEnvironment.activeInstance.assertionHandler
let recorder = AssertionRecorder()
let handlers: [AssertionHandler]
if silently {
handlers = [recorder]
} else {
handlers = [recorder, previousRecorder]
}
let dispatcher = AssertionDispatcher(handlers: handlers)
withAssertionHandler(dispatcher, closure: closure)
return recorder.assertions
}
/// Captures failed expectations that occur in the given closure. Note that all
/// expectations will still go through to the default Nimble handler.
///
/// This can be useful if you want to gather information about failed
/// expectations that occur within a closure.
///
/// @param silently expectations are no longer send to the default Nimble
/// assertion handler when this is true. Defaults to false.
///
/// @see gatherExpectations
/// @see raiseException source for an example use case.
public func gatherFailingExpectations(silently: Bool = false, closure: @escaping () -> Void) -> [AssertionRecord] {
let assertions = gatherExpectations(silently: silently, closure: closure)
return assertions.filter { assertion in
!assertion.success
}
}
================================================
FILE: Example/Pods/Nimble/Sources/Nimble/Adapters/NMBExpectation.swift
================================================
import Foundation
#if _runtime(_ObjC)
internal struct ObjCMatcherWrapper : Matcher {
let matcher: NMBMatcher
func matches(_ actualExpression: Expression, failureMessage: FailureMessage) -> Bool {
return matcher.matches(
({ try! actualExpression.evaluate() }),
failureMessage: failureMessage,
location: actualExpression.location)
}
func doesNotMatch(_ actualExpression: Expression, failureMessage: FailureMessage) -> Bool {
return matcher.doesNotMatch(
({ try! actualExpression.evaluate() }),
failureMessage: failureMessage,
location: actualExpression.location)
}
}
// Equivalent to Expectation, but for Nimble's Objective-C interface
public class NMBExpectation : NSObject {
internal let _actualBlock: () -> NSObject!
internal var _negative: Bool
internal let _file: FileString
internal let _line: UInt
internal var _timeout: TimeInterval = 1.0
public init(actualBlock: @escaping () -> NSObject!, negative: Bool, file: FileString, line: UInt) {
self._actualBlock = actualBlock
self._negative = negative
self._file = file
self._line = line
}
private var expectValue: Expectation {
return expect(_file, line: _line){
self._actualBlock() as NSObject?
}
}
public var withTimeout: (TimeInterval) -> NMBExpectation {
return ({ timeout in self._timeout = timeout
return self
})
}
public var to: (NMBMatcher) -> Void {
return ({ matcher in
self.expectValue.to(ObjCMatcherWrapper(matcher: matcher))
})
}
public var toWithDescription: (NMBMatcher, String) -> Void {
return ({ matcher, description in
self.expectValue.to(ObjCMatcherWrapper(matcher: matcher), description: description)
})
}
public var toNot: (NMBMatcher) -> Void {
return ({ matcher in
self.expectValue.toNot(
ObjCMatcherWrapper(matcher: matcher)
)
})
}
public var toNotWithDescription: (NMBMatcher, String) -> Void {
return ({ matcher, description in
self.expectValue.toNot(
ObjCMatcherWrapper(matcher: matcher), description: description
)
})
}
public var notTo: (NMBMatcher) -> Void { return toNot }
public var notToWithDescription: (NMBMatcher, String) -> Void { return toNotWithDescription }
public var toEventually: (NMBMatcher) -> Void {
return ({ matcher in
self.expectValue.toEventually(
ObjCMatcherWrapper(matcher: matcher),
timeout: self._timeout,
description: nil
)
})
}
public var toEventuallyWithDescription: (NMBMatcher, String) -> Void {
return ({ matcher, description in
self.expectValue.toEventually(
ObjCMatcherWrapper(matcher: matcher),
timeout: self._timeout,
description: description
)
})
}
public var toEventuallyNot: (NMBMatcher) -> Void {
return ({ matcher in
self.expectValue.toEventuallyNot(
ObjCMatcherWrapper(matcher: matcher),
timeout: self._timeout,
description: nil
)
})
}
public var toEventuallyNotWithDescription: (NMBMatcher, String) -> Void {
return ({ matcher, description in
self.expectValue.toEventuallyNot(
ObjCMatcherWrapper(matcher: matcher),
timeout: self._timeout,
description: description
)
})
}
public var toNotEventually: (NMBMatcher) -> Void { return toEventuallyNot }
public var toNotEventuallyWithDescription: (NMBMatcher, String) -> Void { return toEventuallyNotWithDescription }
public class func failWithMessage(_ message: String, file: FileString, line: UInt) {
fail(message, location: SourceLocation(file: file, line: line))
}
}
#endif
================================================
FILE: Example/Pods/Nimble/Sources/Nimble/Adapters/NMBObjCMatcher.swift
================================================
import Foundation
#if _runtime(_ObjC)
public typealias MatcherBlock = (_ actualExpression: Expression, _ failureMessage: FailureMessage) -> Bool
public typealias FullMatcherBlock = (_ actualExpression: Expression, _ failureMessage: FailureMessage, _ shouldNotMatch: Bool) -> Bool
public class NMBObjCMatcher : NSObject, NMBMatcher {
let _match: MatcherBlock
let _doesNotMatch: MatcherBlock
let canMatchNil: Bool
public init(canMatchNil: Bool, matcher: @escaping MatcherBlock, notMatcher: @escaping MatcherBlock) {
self.canMatchNil = canMatchNil
self._match = matcher
self._doesNotMatch = notMatcher
}
public convenience init(matcher: @escaping MatcherBlock) {
self.init(canMatchNil: true, matcher: matcher)
}
public convenience init(canMatchNil: Bool, matcher: @escaping MatcherBlock) {
self.init(canMatchNil: canMatchNil, matcher: matcher, notMatcher: ({ actualExpression, failureMessage in
return !matcher(actualExpression, failureMessage)
}))
}
public convenience init(matcher: @escaping FullMatcherBlock) {
self.init(canMatchNil: true, matcher: matcher)
}
public convenience init(canMatchNil: Bool, matcher: @escaping FullMatcherBlock) {
self.init(canMatchNil: canMatchNil, matcher: ({ actualExpression, failureMessage in
return matcher(actualExpression, failureMessage, false)
}), notMatcher: ({ actualExpression, failureMessage in
return matcher(actualExpression, failureMessage, true)
}))
}
private func canMatch(_ actualExpression: Expression, failureMessage: FailureMessage) -> Bool {
do {
if !canMatchNil {
if try actualExpression.evaluate() == nil {
failureMessage.postfixActual = " (use beNil() to match nils)"
return false
}
}
} catch let error {
failureMessage.actualValue = "an unexpected error thrown: \(error)"
return false
}
return true
}
public func matches(_ actualBlock: @escaping () -> NSObject!, failureMessage: FailureMessage, location: SourceLocation) -> Bool {
let expr = Expression(expression: actualBlock, location: location)
let result = _match(
expr,
failureMessage)
if self.canMatch(Expression(expression: actualBlock, location: location), failureMessage: failureMessage) {
return result
} else {
return false
}
}
public func doesNotMatch(_ actualBlock: @escaping () -> NSObject!, failureMessage: FailureMessage, location: SourceLocation) -> Bool {
let expr = Expression(expression: actualBlock, location: location)
let result = _doesNotMatch(
expr,
failureMessage)
if self.canMatch(Expression(expression: actualBlock, location: location), failureMessage: failureMessage) {
return result
} else {
return false
}
}
}
#endif
================================================
FILE: Example/Pods/Nimble/Sources/Nimble/Adapters/NimbleEnvironment.swift
================================================
import Dispatch
import Foundation
/// "Global" state of Nimble is stored here. Only DSL functions should access / be aware of this
/// class' existance
internal class NimbleEnvironment {
static var activeInstance: NimbleEnvironment {
get {
let env = Thread.current.threadDictionary["NimbleEnvironment"]
if let env = env as? NimbleEnvironment {
return env
} else {
let newEnv = NimbleEnvironment()
self.activeInstance = newEnv
return newEnv
}
}
set {
Thread.current.threadDictionary["NimbleEnvironment"] = newValue
}
}
// TODO: eventually migrate the global to this environment value
var assertionHandler: AssertionHandler {
get { return NimbleAssertionHandler }
set { NimbleAssertionHandler = newValue }
}
var suppressTVOSAssertionWarning: Bool = false
var awaiter: Awaiter
init() {
let timeoutQueue: DispatchQueue
if #available(OSX 10.10, *) {
timeoutQueue = DispatchQueue.global(qos: .userInitiated)
} else {
timeoutQueue = DispatchQueue.global(priority: .high)
}
awaiter = Awaiter(
waitLock: AssertionWaitLock(),
asyncQueue: .main,
timeoutQueue: timeoutQueue)
}
}
================================================
FILE: Example/Pods/Nimble/Sources/Nimble/Adapters/NimbleXCTestHandler.swift
================================================
import Foundation
import XCTest
/// Default handler for Nimble. This assertion handler passes failures along to
/// XCTest.
public class NimbleXCTestHandler : AssertionHandler {
public func assert(_ assertion: Bool, message: FailureMessage, location: SourceLocation) {
if !assertion {
recordFailure("\(message.stringValue)\n", location: location)
}
}
}
/// Alternative handler for Nimble. This assertion handler passes failures along
/// to XCTest by attempting to reduce the failure message size.
public class NimbleShortXCTestHandler: AssertionHandler {
public func assert(_ assertion: Bool, message: FailureMessage, location: SourceLocation) {
if !assertion {
let msg: String
if let actual = message.actualValue {
msg = "got: \(actual) \(message.postfixActual)"
} else {
msg = "expected \(message.to) \(message.postfixMessage)"
}
recordFailure("\(msg)\n", location: location)
}
}
}
/// Fallback handler in case XCTest is unavailable. This assertion handler will abort
/// the program if it is invoked.
class NimbleXCTestUnavailableHandler : AssertionHandler {
func assert(_ assertion: Bool, message: FailureMessage, location: SourceLocation) {
fatalError("XCTest is not available and no custom assertion handler was configured. Aborting.")
}
}
#if _runtime(_ObjC)
/// Helper class providing access to the currently executing XCTestCase instance, if any
@objc final internal class CurrentTestCaseTracker: NSObject, XCTestObservation {
@objc static let sharedInstance = CurrentTestCaseTracker()
private(set) var currentTestCase: XCTestCase?
@objc func testCaseWillStart(_ testCase: XCTestCase) {
currentTestCase = testCase
}
@objc func testCaseDidFinish(_ testCase: XCTestCase) {
currentTestCase = nil
}
}
#endif
func isXCTestAvailable() -> Bool {
#if _runtime(_ObjC)
// XCTest is weakly linked and so may not be present
return NSClassFromString("XCTestCase") != nil
#else
return true
#endif
}
private func recordFailure(_ message: String, location: SourceLocation) {
#if _runtime(_ObjC)
if let testCase = CurrentTestCaseTracker.sharedInstance.currentTestCase {
testCase.recordFailure(withDescription: message, inFile: location.file, atLine: location.line, expected: true)
} else {
let msg = "Attempted to report a test failure to XCTest while no test case was running. " +
"The failure was:\n\"\(message)\"\nIt occurred at: \(location.file):\(location.line)"
NSException(name: .internalInconsistencyException, reason: msg, userInfo: nil).raise()
}
#else
XCTFail("\(message)\n", file: location.file, line: location.line)
#endif
}
================================================
FILE: Example/Pods/Nimble/Sources/Nimble/DSL+Wait.swift
================================================
import Dispatch
import Foundation
private enum ErrorResult {
case exception(NSException)
case error(Error)
case none
}
/// Only classes, protocols, methods, properties, and subscript declarations can be
/// bridges to Objective-C via the @objc keyword. This class encapsulates callback-style
/// asynchronous waiting logic so that it may be called from Objective-C and Swift.
internal class NMBWait: NSObject {
internal class func until(
timeout: TimeInterval,
file: FileString = #file,
line: UInt = #line,
action: @escaping (@escaping () -> Void) -> Void) -> Void {
return throwableUntil(timeout: timeout, file: file, line: line) { done in
action(done)
}
}
// Using a throwable closure makes this method not objc compatible.
internal class func throwableUntil(
timeout: TimeInterval,
file: FileString = #file,
line: UInt = #line,
action: @escaping (@escaping () -> Void) throws -> Void) -> Void {
let awaiter = NimbleEnvironment.activeInstance.awaiter
let leeway = timeout / 2.0
let result = awaiter.performBlock { (done: @escaping (ErrorResult) -> Void) throws -> Void in
DispatchQueue.main.async {
let capture = NMBExceptionCapture(
handler: ({ exception in
done(.exception(exception))
}),
finally: ({ })
)
capture.tryBlock {
do {
try action() {
done(.none)
}
} catch let e {
done(.error(e))
}
}
}
}.timeout(timeout, forcefullyAbortTimeout: leeway).wait("waitUntil(...)", file: file, line: line)
switch result {
case .incomplete: internalError("Reached .incomplete state for waitUntil(...).")
case .blockedRunLoop:
fail(blockedRunLoopErrorMessageFor("-waitUntil()", leeway: leeway),
file: file, line: line)
case .timedOut:
let pluralize = (timeout == 1 ? "" : "s")
fail("Waited more than \(timeout) second\(pluralize)", file: file, line: line)
case let .raisedException(exception):
fail("Unexpected exception raised: \(exception)")
case let .errorThrown(error):
fail("Unexpected error thrown: \(error)")
case .completed(.exception(let exception)):
fail("Unexpected exception raised: \(exception)")
case .completed(.error(let error)):
fail("Unexpected error thrown: \(error)")
case .completed(.none): // success
break
}
}
#if _runtime(_ObjC)
@objc(untilFile:line:action:)
internal class func until(_ file: FileString = #file, line: UInt = #line, action: @escaping (() -> Void) -> Void) -> Void {
until(timeout: 1, file: file, line: line, action: action)
}
#else
internal class func until(_ file: FileString = #file, line: UInt = #line, action: @escaping (() -> Void) -> Void) -> Void {
until(timeout: 1, file: file, line: line, action: action)
}
#endif
}
internal func blockedRunLoopErrorMessageFor(_ fnName: String, leeway: TimeInterval) -> String {
return "\(fnName) timed out but was unable to run the timeout handler because the main thread is unresponsive (\(leeway) seconds is allow after the wait times out). Conditions that may cause this include processing blocking IO on the main thread, calls to sleep(), deadlocks, and synchronous IPC. Nimble forcefully stopped run loop which may cause future failures in test run."
}
/// Wait asynchronously until the done closure is called or the timeout has been reached.
///
/// @discussion
/// Call the done() closure to indicate the waiting has completed.
///
/// This function manages the main run loop (`NSRunLoop.mainRunLoop()`) while this function
/// is executing. Any attempts to touch the run loop may cause non-deterministic behavior.
public func waitUntil(timeout: TimeInterval = 1, file: FileString = #file, line: UInt = #line, action: @escaping (@escaping () -> Void) -> Void) -> Void {
NMBWait.until(timeout: timeout, file: file, line: line, action: action)
}
================================================
FILE: Example/Pods/Nimble/Sources/Nimble/DSL.swift
================================================
import Foundation
/// Make an expectation on a given actual value. The value given is lazily evaluated.
public func expect(_ expression: @autoclosure @escaping () throws -> T?, file: FileString = #file, line: UInt = #line) -> Expectation {
return Expectation(
expression: Expression(
expression: expression,
location: SourceLocation(file: file, line: line),
isClosure: true))
}
/// Make an expectation on a given actual value. The closure is lazily invoked.
public func expect(_ file: FileString = #file, line: UInt = #line, expression: @escaping () throws -> T?) -> Expectation {
return Expectation(
expression: Expression(
expression: expression,
location: SourceLocation(file: file, line: line),
isClosure: true))
}
/// Always fails the test with a message and a specified location.
public func fail(_ message: String, location: SourceLocation) {
let handler = NimbleEnvironment.activeInstance.assertionHandler
handler.assert(false, message: FailureMessage(stringValue: message), location: location)
}
/// Always fails the test with a message.
public func fail(_ message: String, file: FileString = #file, line: UInt = #line) {
fail(message, location: SourceLocation(file: file, line: line))
}
/// Always fails the test.
public func fail(_ file: FileString = #file, line: UInt = #line) {
fail("fail() always fails", file: file, line: line)
}
/// Like Swift's precondition(), but raises NSExceptions instead of sigaborts
internal func nimblePrecondition(
_ expr: @autoclosure() -> Bool,
_ name: @autoclosure() -> String,
_ message: @autoclosure() -> String,
file: StaticString = #file,
line: UInt = #line) {
let result = expr()
if !result {
#if _runtime(_ObjC)
let e = NSException(
name: NSExceptionName(name()),
reason: message(),
userInfo: nil)
e.raise()
#else
preconditionFailure("\(name()) - \(message())", file: file, line: line)
#endif
}
}
internal func internalError(_ msg: String, file: FileString = #file, line: UInt = #line) -> Never {
fatalError(
"Nimble Bug Found: \(msg) at \(file):\(line).\n" +
"Please file a bug to Nimble: https://github.com/Quick/Nimble/issues with the " +
"code snippet that caused this error."
)
}
================================================
FILE: Example/Pods/Nimble/Sources/Nimble/Expectation.swift
================================================
import Foundation
internal func expressionMatches(_ expression: Expression, matcher: U, to: String, description: String?) -> (Bool, FailureMessage)
where U: Matcher, U.ValueType == T
{
let msg = FailureMessage()
msg.userDescription = description
msg.to = to
do {
let pass = try matcher.matches(expression, failureMessage: msg)
if msg.actualValue == "" {
msg.actualValue = "<\(stringify(try expression.evaluate()))>"
}
return (pass, msg)
} catch let error {
msg.actualValue = "an unexpected error thrown: <\(error)>"
return (false, msg)
}
}
internal func expressionDoesNotMatch(_ expression: Expression, matcher: U, toNot: String, description: String?) -> (Bool, FailureMessage)
where U: Matcher, U.ValueType == T
{
let msg = FailureMessage()
msg.userDescription = description
msg.to = toNot
do {
let pass = try matcher.doesNotMatch(expression, failureMessage: msg)
if msg.actualValue == "" {
msg.actualValue = "<\(stringify(try expression.evaluate()))>"
}
return (pass, msg)
} catch let error {
msg.actualValue = "an unexpected error thrown: <\(error)>"
return (false, msg)
}
}
public struct Expectation {
public let expression: Expression
public func verify(_ pass: Bool, _ message: FailureMessage) {
let handler = NimbleEnvironment.activeInstance.assertionHandler
handler.assert(pass, message: message, location: expression.location)
}
/// Tests the actual value using a matcher to match.
public func to(_ matcher: U, description: String? = nil)
where U: Matcher, U.ValueType == T
{
let (pass, msg) = expressionMatches(expression, matcher: matcher, to: "to", description: description)
verify(pass, msg)
}
/// Tests the actual value using a matcher to not match.
public func toNot(_ matcher: U, description: String? = nil)
where U: Matcher, U.ValueType == T
{
let (pass, msg) = expressionDoesNotMatch(expression, matcher: matcher, toNot: "to not", description: description)
verify(pass, msg)
}
/// Tests the actual value using a matcher to not match.
///
/// Alias to toNot().
public func notTo(_ matcher: U, description: String? = nil)
where U: Matcher, U.ValueType == T
{
toNot(matcher, description: description)
}
// see:
// - AsyncMatcherWrapper for extension
// - NMBExpectation for Objective-C interface
}
================================================
FILE: Example/Pods/Nimble/Sources/Nimble/Expression.swift
================================================
import Foundation
// Memoizes the given closure, only calling the passed
// closure once; even if repeat calls to the returned closure
internal func memoizedClosure(_ closure: @escaping () throws -> T) -> (Bool) throws -> T {
var cache: T?
return ({ withoutCaching in
if (withoutCaching || cache == nil) {
cache = try closure()
}
return cache!
})
}
/// Expression represents the closure of the value inside expect(...).
/// Expressions are memoized by default. This makes them safe to call
/// evaluate() multiple times without causing a re-evaluation of the underlying
/// closure.
///
/// @warning Since the closure can be any code, Objective-C code may choose
/// to raise an exception. Currently, Expression does not memoize
/// exception raising.
///
/// This provides a common consumable API for matchers to utilize to allow
/// Nimble to change internals to how the captured closure is managed.
public struct Expression {
internal let _expression: (Bool) throws -> T?
internal let _withoutCaching: Bool
public let location: SourceLocation
public let isClosure: Bool
/// Creates a new expression struct. Normally, expect(...) will manage this
/// creation process. The expression is memoized.
///
/// @param expression The closure that produces a given value.
/// @param location The source location that this closure originates from.
/// @param isClosure A bool indicating if the captured expression is a
/// closure or internally produced closure. Some matchers
/// may require closures. For example, toEventually()
/// requires an explicit closure. This gives Nimble
/// flexibility if @autoclosure behavior changes between
/// Swift versions. Nimble internals always sets this true.
public init(expression: @escaping () throws -> T?, location: SourceLocation, isClosure: Bool = true) {
self._expression = memoizedClosure(expression)
self.location = location
self._withoutCaching = false
self.isClosure = isClosure
}
/// Creates a new expression struct. Normally, expect(...) will manage this
/// creation process.
///
/// @param expression The closure that produces a given value.
/// @param location The source location that this closure originates from.
/// @param withoutCaching Indicates if the struct should memoize the given
/// closure's result. Subsequent evaluate() calls will
/// not call the given closure if this is true.
/// @param isClosure A bool indicating if the captured expression is a
/// closure or internally produced closure. Some matchers
/// may require closures. For example, toEventually()
/// requires an explicit closure. This gives Nimble
/// flexibility if @autoclosure behavior changes between
/// Swift versions. Nimble internals always sets this true.
public init(memoizedExpression: @escaping (Bool) throws -> T?, location: SourceLocation, withoutCaching: Bool, isClosure: Bool = true) {
self._expression = memoizedExpression
self.location = location
self._withoutCaching = withoutCaching
self.isClosure = isClosure
}
/// Returns a new Expression from the given expression. Identical to a map()
/// on this type. This should be used only to typecast the Expression's
/// closure value.
///
/// The returned expression will preserve location and isClosure.
///
/// @param block The block that can cast the current Expression value to a
/// new type.
public func cast(_ block: @escaping (T?) throws -> U?) -> Expression {
return Expression(expression: ({ try block(self.evaluate()) }), location: self.location, isClosure: self.isClosure)
}
public func evaluate() throws -> T? {
return try self._expression(_withoutCaching)
}
public func withoutCaching() -> Expression {
return Expression(memoizedExpression: self._expression, location: location, withoutCaching: true, isClosure: isClosure)
}
}
================================================
FILE: Example/Pods/Nimble/Sources/Nimble/FailureMessage.swift
================================================
import Foundation
/// Encapsulates the failure message that matchers can report to the end user.
///
/// This is shared state between Nimble and matchers that mutate this value.
public class FailureMessage: NSObject {
public var expected: String = "expected"
public var actualValue: String? = "" // empty string -> use default; nil -> exclude
public var to: String = "to"
public var postfixMessage: String = "match"
public var postfixActual: String = ""
/// An optional message that will be appended as a new line and provides additional details
/// about the failure. This message will only be visible in the issue navigator / in logs but
/// not directly in the source editor since only a single line is presented there.
public var extendedMessage: String? = nil
public var userDescription: String? = nil
public var stringValue: String {
get {
if let value = _stringValueOverride {
return value
} else {
return computeStringValue()
}
}
set {
_stringValueOverride = newValue
}
}
internal var _stringValueOverride: String?
public override init() {
}
public init(stringValue: String) {
_stringValueOverride = stringValue
}
internal func stripNewlines(_ str: String) -> String {
let whitespaces = CharacterSet.whitespacesAndNewlines
return str
.components(separatedBy: "\n")
.map { line in line.trimmingCharacters(in: whitespaces) }
.joined(separator: "")
}
internal func computeStringValue() -> String {
var value = "\(expected) \(to) \(postfixMessage)"
if let actualValue = actualValue {
value = "\(expected) \(to) \(postfixMessage), got \(actualValue)\(postfixActual)"
}
value = stripNewlines(value)
if let extendedMessage = extendedMessage {
value += "\n\(stripNewlines(extendedMessage))"
}
if let userDescription = userDescription {
return "\(userDescription)\n\(value)"
}
return value
}
}
================================================
FILE: Example/Pods/Nimble/Sources/Nimble/Matchers/AllPass.swift
================================================
import Foundation
public func allPass
(_ passFunc: @escaping (T?) -> Bool) -> NonNilMatcherFunc
where U: Sequence, U.Iterator.Element == T
{
return allPass("pass a condition", passFunc)
}
public func allPass
(_ passName: String, _ passFunc: @escaping (T?) -> Bool) -> NonNilMatcherFunc
where U: Sequence, U.Iterator.Element == T
{
return createAllPassMatcher() {
expression, failureMessage in
failureMessage.postfixMessage = passName
return passFunc(try expression.evaluate())
}
}
public func allPass
(_ matcher: V) -> NonNilMatcherFunc
where U: Sequence, V: Matcher, U.Iterator.Element == V.ValueType
{
return createAllPassMatcher() {
try matcher.matches($0, failureMessage: $1)
}
}
private func createAllPassMatcher
(_ elementEvaluator: @escaping (Expression, FailureMessage) throws -> Bool) -> NonNilMatcherFunc
where U: Sequence, U.Iterator.Element == T
{
return NonNilMatcherFunc { actualExpression, failureMessage in
failureMessage.actualValue = nil
if let actualValue = try actualExpression.evaluate() {
for currentElement in actualValue {
let exp = Expression(
expression: {currentElement}, location: actualExpression.location)
if try !elementEvaluator(exp, failureMessage) {
failureMessage.postfixMessage =
"all \(failureMessage.postfixMessage),"
+ " but failed first at element <\(stringify(currentElement))>"
+ " in <\(stringify(actualValue))>"
return false
}
}
failureMessage.postfixMessage = "all \(failureMessage.postfixMessage)"
} else {
failureMessage.postfixMessage = "all pass (use beNil() to match nils)"
return false
}
return true
}
}
#if _runtime(_ObjC)
extension NMBObjCMatcher {
public class func allPassMatcher(_ matcher: NMBObjCMatcher) -> NMBObjCMatcher {
return NMBObjCMatcher(canMatchNil: false) { actualExpression, failureMessage in
let location = actualExpression.location
let actualValue = try! actualExpression.evaluate()
var nsObjects = [NSObject]()
var collectionIsUsable = true
if let value = actualValue as? NSFastEnumeration {
let generator = NSFastEnumerationIterator(value)
while let obj = generator.next() {
if let nsObject = obj as? NSObject {
nsObjects.append(nsObject)
} else {
collectionIsUsable = false
break
}
}
} else {
collectionIsUsable = false
}
if !collectionIsUsable {
failureMessage.postfixMessage =
"allPass only works with NSFastEnumeration (NSArray, NSSet, ...) of NSObjects"
failureMessage.expected = ""
failureMessage.to = ""
return false
}
let expr = Expression(expression: ({ nsObjects }), location: location)
let elementEvaluator: (Expression, FailureMessage) -> Bool = {
expression, failureMessage in
return matcher.matches(
{try! expression.evaluate()}, failureMessage: failureMessage, location: expr.location)
}
return try! createAllPassMatcher(elementEvaluator).matches(
expr, failureMessage: failureMessage)
}
}
}
#endif
================================================
FILE: Example/Pods/Nimble/Sources/Nimble/Matchers/AsyncMatcherWrapper.swift
================================================
import Foundation
/// If you are running on a slower machine, it could be useful to increase the default timeout value
/// or slow down poll interval. Default timeout interval is 1, and poll interval is 0.01.
public struct AsyncDefaults {
public static var Timeout: TimeInterval = 1
public static var PollInterval: TimeInterval = 0.01
}
internal struct AsyncMatcherWrapper: Matcher
where U: Matcher, U.ValueType == T
{
let fullMatcher: U
let timeoutInterval: TimeInterval
let pollInterval: TimeInterval
init(fullMatcher: U, timeoutInterval: TimeInterval = AsyncDefaults.Timeout, pollInterval: TimeInterval = AsyncDefaults.PollInterval) {
self.fullMatcher = fullMatcher
self.timeoutInterval = timeoutInterval
self.pollInterval = pollInterval
}
func matches(_ actualExpression: Expression, failureMessage: FailureMessage) -> Bool {
let uncachedExpression = actualExpression.withoutCaching()
let fnName = "expect(...).toEventually(...)"
let result = pollBlock(
pollInterval: pollInterval,
timeoutInterval: timeoutInterval,
file: actualExpression.location.file,
line: actualExpression.location.line,
fnName: fnName) {
try self.fullMatcher.matches(uncachedExpression, failureMessage: failureMessage)
}
switch (result) {
case let .completed(isSuccessful): return isSuccessful
case .timedOut: return false
case let .errorThrown(error):
failureMessage.actualValue = "an unexpected error thrown: <\(error)>"
return false
case let .raisedException(exception):
failureMessage.actualValue = "an unexpected exception thrown: <\(exception)>"
return false
case .blockedRunLoop:
failureMessage.postfixMessage += " (timed out, but main thread was unresponsive)."
return false
case .incomplete:
internalError("Reached .incomplete state for toEventually(...).")
}
}
func doesNotMatch(_ actualExpression: Expression, failureMessage: FailureMessage) -> Bool {
let uncachedExpression = actualExpression.withoutCaching()
let result = pollBlock(
pollInterval: pollInterval,
timeoutInterval: timeoutInterval,
file: actualExpression.location.file,
line: actualExpression.location.line,
fnName: "expect(...).toEventuallyNot(...)") {
try self.fullMatcher.doesNotMatch(uncachedExpression, failureMessage: failureMessage)
}
switch (result) {
case let .completed(isSuccessful): return isSuccessful
case .timedOut: return false
case let .errorThrown(error):
failureMessage.actualValue = "an unexpected error thrown: <\(error)>"
return false
case let .raisedException(exception):
failureMessage.actualValue = "an unexpected exception thrown: <\(exception)>"
return false
case .blockedRunLoop:
failureMessage.postfixMessage += " (timed out, but main thread was unresponsive)."
return false
case .incomplete:
internalError("Reached .incomplete state for toEventuallyNot(...).")
}
}
}
private let toEventuallyRequiresClosureError = FailureMessage(stringValue: "expect(...).toEventually(...) requires an explicit closure (eg - expect { ... }.toEventually(...) )\nSwift 1.2 @autoclosure behavior has changed in an incompatible way for Nimble to function")
extension Expectation {
/// Tests the actual value using a matcher to match by checking continuously
/// at each pollInterval until the timeout is reached.
///
/// @discussion
/// This function manages the main run loop (`NSRunLoop.mainRunLoop()`) while this function
/// is executing. Any attempts to touch the run loop may cause non-deterministic behavior.
public func toEventually(_ matcher: U, timeout: TimeInterval = AsyncDefaults.Timeout, pollInterval: TimeInterval = AsyncDefaults.PollInterval, description: String? = nil)
where U: Matcher, U.ValueType == T
{
if expression.isClosure {
let (pass, msg) = expressionMatches(
expression,
matcher: AsyncMatcherWrapper(
fullMatcher: matcher,
timeoutInterval: timeout,
pollInterval: pollInterval),
to: "to eventually",
description: description
)
verify(pass, msg)
} else {
verify(false, toEventuallyRequiresClosureError)
}
}
/// Tests the actual value using a matcher to not match by checking
/// continuously at each pollInterval until the timeout is reached.
///
/// @discussion
/// This function manages the main run loop (`NSRunLoop.mainRunLoop()`) while this function
/// is executing. Any attempts to touch the run loop may cause non-deterministic behavior.
public func toEventuallyNot(_ matcher: U, timeout: TimeInterval = AsyncDefaults.Timeout, pollInterval: TimeInterval = AsyncDefaults.PollInterval, description: String? = nil)
where U: Matcher, U.ValueType == T
{
if expression.isClosure {
let (pass, msg) = expressionDoesNotMatch(
expression,
matcher: AsyncMatcherWrapper(
fullMatcher: matcher,
timeoutInterval: timeout,
pollInterval: pollInterval),
toNot: "to eventually not",
description: description
)
verify(pass, msg)
} else {
verify(false, toEventuallyRequiresClosureError)
}
}
/// Tests the actual value using a matcher to not match by checking
/// continuously at each pollInterval until the timeout is reached.
///
/// Alias of toEventuallyNot()
///
/// @discussion
/// This function manages the main run loop (`NSRunLoop.mainRunLoop()`) while this function
/// is executing. Any attempts to touch the run loop may cause non-deterministic behavior.
public func toNotEventually(_ matcher: U, timeout: TimeInterval = AsyncDefaults.Timeout, pollInterval: TimeInterval = AsyncDefaults.PollInterval, description: String? = nil)
where U: Matcher, U.ValueType == T
{
return toEventuallyNot(matcher, timeout: timeout, pollInterval: pollInterval, description: description)
}
}
================================================
FILE: Example/Pods/Nimble/Sources/Nimble/Matchers/BeAKindOf.swift
================================================
import Foundation
#if _runtime(_ObjC)
// A Nimble matcher that catches attempts to use beAKindOf with non Objective-C types
public func beAKindOf(_ expectedClass: Any) -> NonNilMatcherFunc {
return NonNilMatcherFunc {actualExpression, failureMessage in
failureMessage.stringValue = "beAKindOf only works on Objective-C types since"
+ " the Swift compiler will automatically type check Swift-only types."
+ " This expectation is redundant."
return false
}
}
/// A Nimble matcher that succeeds when the actual value is an instance of the given class.
/// @see beAnInstanceOf if you want to match against the exact class
public func beAKindOf(_ expectedClass: AnyClass) -> NonNilMatcherFunc {
return NonNilMatcherFunc { actualExpression, failureMessage in
let instance = try actualExpression.evaluate()
if let validInstance = instance {
failureMessage.actualValue = "<\(String(describing: type(of: validInstance))) instance>"
} else {
failureMessage.actualValue = ""
}
failureMessage.postfixMessage = "be a kind of \(String(describing: expectedClass))"
return instance != nil && instance!.isKind(of: expectedClass)
}
}
extension NMBObjCMatcher {
public class func beAKindOfMatcher(_ expected: AnyClass) -> NMBMatcher {
return NMBObjCMatcher(canMatchNil: false) { actualExpression, failureMessage in
return try! beAKindOf(expected).matches(actualExpression, failureMessage: failureMessage)
}
}
}
#endif
================================================
FILE: Example/Pods/Nimble/Sources/Nimble/Matchers/BeAnInstanceOf.swift
================================================
import Foundation
// A Nimble matcher that catches attempts to use beAnInstanceOf with non Objective-C types
public func beAnInstanceOf(_ expectedClass: Any) -> NonNilMatcherFunc {
return NonNilMatcherFunc {actualExpression, failureMessage in
failureMessage.stringValue = "beAnInstanceOf only works on Objective-C types since"
+ " the Swift compiler will automatically type check Swift-only types."
+ " This expectation is redundant."
return false
}
}
/// A Nimble matcher that succeeds when the actual value is an instance of the given class.
/// @see beAKindOf if you want to match against subclasses
public func beAnInstanceOf(_ expectedClass: AnyClass) -> NonNilMatcherFunc {
return NonNilMatcherFunc { actualExpression, failureMessage in
let instance = try actualExpression.evaluate()
if let validInstance = instance {
failureMessage.actualValue = "<\(String(describing: type(of: validInstance))) instance>"
} else {
failureMessage.actualValue = ""
}
failureMessage.postfixMessage = "be an instance of \(String(describing: expectedClass))"
#if _runtime(_ObjC)
return instance != nil && instance!.isMember(of: expectedClass)
#else
return instance != nil && type(of: instance!) == expectedClass
#endif
}
}
#if _runtime(_ObjC)
extension NMBObjCMatcher {
public class func beAnInstanceOfMatcher(_ expected: AnyClass) -> NMBMatcher {
return NMBObjCMatcher(canMatchNil: false) { actualExpression, failureMessage in
return try! beAnInstanceOf(expected).matches(actualExpression, failureMessage: failureMessage)
}
}
}
#endif
================================================
FILE: Example/Pods/Nimble/Sources/Nimble/Matchers/BeCloseTo.swift
================================================
import Foundation
internal let DefaultDelta = 0.0001
internal func isCloseTo(_ actualValue: NMBDoubleConvertible?, expectedValue: NMBDoubleConvertible, delta: Double, failureMessage: FailureMessage) -> Bool {
failureMessage.postfixMessage = "be close to <\(stringify(expectedValue))> (within \(stringify(delta)))"
failureMessage.actualValue = "<\(stringify(actualValue))>"
return actualValue != nil && abs(actualValue!.doubleValue - expectedValue.doubleValue) < delta
}
/// A Nimble matcher that succeeds when a value is close to another. This is used for floating
/// point values which can have imprecise results when doing arithmetic on them.
///
/// @see equal
public func beCloseTo(_ expectedValue: Double, within delta: Double = DefaultDelta) -> NonNilMatcherFunc {
return NonNilMatcherFunc { actualExpression, failureMessage in
return isCloseTo(try actualExpression.evaluate(), expectedValue: expectedValue, delta: delta, failureMessage: failureMessage)
}
}
/// A Nimble matcher that succeeds when a value is close to another. This is used for floating
/// point values which can have imprecise results when doing arithmetic on them.
///
/// @see equal
public func beCloseTo(_ expectedValue: NMBDoubleConvertible, within delta: Double = DefaultDelta) -> NonNilMatcherFunc {
return NonNilMatcherFunc { actualExpression, failureMessage in
return isCloseTo(try actualExpression.evaluate(), expectedValue: expectedValue, delta: delta, failureMessage: failureMessage)
}
}
#if _runtime(_ObjC)
public class NMBObjCBeCloseToMatcher : NSObject, NMBMatcher {
var _expected: NSNumber
var _delta: CDouble
init(expected: NSNumber, within: CDouble) {
_expected = expected
_delta = within
}
public func matches(_ actualExpression: @escaping () -> NSObject!, failureMessage: FailureMessage, location: SourceLocation) -> Bool {
let actualBlock: () -> NMBDoubleConvertible? = ({
return actualExpression() as? NMBDoubleConvertible
})
let expr = Expression(expression: actualBlock, location: location)
let matcher = beCloseTo(self._expected, within: self._delta)
return try! matcher.matches(expr, failureMessage: failureMessage)
}
public func doesNotMatch(_ actualExpression: @escaping () -> NSObject!, failureMessage: FailureMessage, location: SourceLocation) -> Bool {
let actualBlock: () -> NMBDoubleConvertible? = ({
return actualExpression() as? NMBDoubleConvertible
})
let expr = Expression(expression: actualBlock, location: location)
let matcher = beCloseTo(self._expected, within: self._delta)
return try! matcher.doesNotMatch(expr, failureMessage: failureMessage)
}
public var within: (CDouble) -> NMBObjCBeCloseToMatcher {
return ({ delta in
return NMBObjCBeCloseToMatcher(expected: self._expected, within: delta)
})
}
}
extension NMBObjCMatcher {
public class func beCloseToMatcher(_ expected: NSNumber, within: CDouble) -> NMBObjCBeCloseToMatcher {
return NMBObjCBeCloseToMatcher(expected: expected, within: within)
}
}
#endif
public func beCloseTo(_ expectedValues: [Double], within delta: Double = DefaultDelta) -> NonNilMatcherFunc <[Double]> {
return NonNilMatcherFunc { actualExpression, failureMessage in
failureMessage.postfixMessage = "be close to <\(stringify(expectedValues))> (each within \(stringify(delta)))"
if let actual = try actualExpression.evaluate() {
failureMessage.actualValue = "<\(stringify(actual))>"
if actual.count != expectedValues.count {
return false
} else {
for (index, actualItem) in actual.enumerated() {
if fabs(actualItem - expectedValues[index]) > delta {
return false
}
}
return true
}
}
return false
}
}
// MARK: - Operators
infix operator ≈ : ComparisonPrecedence
public func ≈(lhs: Expectation<[Double]>, rhs: [Double]) {
lhs.to(beCloseTo(rhs))
}
public func ≈(lhs: Expectation, rhs: NMBDoubleConvertible) {
lhs.to(beCloseTo(rhs))
}
public func ≈(lhs: Expectation, rhs: (expected: NMBDoubleConvertible, delta: Double)) {
lhs.to(beCloseTo(rhs.expected, within: rhs.delta))
}
public func ==(lhs: Expectation, rhs: (expected: NMBDoubleConvertible, delta: Double)) {
lhs.to(beCloseTo(rhs.expected, within: rhs.delta))
}
// make this higher precedence than exponents so the Doubles either end aren't pulled in
// unexpectantly
precedencegroup PlusMinusOperatorPrecedence {
higherThan: BitwiseShiftPrecedence
}
infix operator ± : PlusMinusOperatorPrecedence
public func ±(lhs: NMBDoubleConvertible, rhs: Double) -> (expected: NMBDoubleConvertible, delta: Double) {
return (expected: lhs, delta: rhs)
}
================================================
FILE: Example/Pods/Nimble/Sources/Nimble/Matchers/BeEmpty.swift
================================================
import Foundation
/// A Nimble matcher that succeeds when a value is "empty". For collections, this
/// means the are no items in that collection. For strings, it is an empty string.
public func beEmpty() -> NonNilMatcherFunc {
return NonNilMatcherFunc { actualExpression, failureMessage in
failureMessage.postfixMessage = "be empty"
let actualSeq = try actualExpression.evaluate()
if actualSeq == nil {
return true
}
var generator = actualSeq!.makeIterator()
return generator.next() == nil
}
}
/// A Nimble matcher that succeeds when a value is "empty". For collections, this
/// means the are no items in that collection. For strings, it is an empty string.
public func beEmpty() -> NonNilMatcherFunc {
return NonNilMatcherFunc { actualExpression, failureMessage in
failureMessage.postfixMessage = "be empty"
let actualString = try actualExpression.evaluate()
return actualString == nil || NSString(string: actualString!).length == 0
}
}
/// A Nimble matcher that succeeds when a value is "empty". For collections, this
/// means the are no items in that collection. For NSString instances, it is an empty string.
public func beEmpty() -> NonNilMatcherFunc {
return NonNilMatcherFunc { actualExpression, failureMessage in
failureMessage.postfixMessage = "be empty"
let actualString = try actualExpression.evaluate()
return actualString == nil || actualString!.length == 0
}
}
// Without specific overrides, beEmpty() is ambiguous for NSDictionary, NSArray,
// etc, since they conform to Sequence as well as NMBCollection.
/// A Nimble matcher that succeeds when a value is "empty". For collections, this
/// means the are no items in that collection. For strings, it is an empty string.
public func beEmpty() -> NonNilMatcherFunc {
return NonNilMatcherFunc { actualExpression, failureMessage in
failureMessage.postfixMessage = "be empty"
let actualDictionary = try actualExpression.evaluate()
return actualDictionary == nil || actualDictionary!.count == 0
}
}
/// A Nimble matcher that succeeds when a value is "empty". For collections, this
/// means the are no items in that collection. For strings, it is an empty string.
public func beEmpty() -> NonNilMatcherFunc {
return NonNilMatcherFunc { actualExpression, failureMessage in
failureMessage.postfixMessage = "be empty"
let actualArray = try actualExpression.evaluate()
return actualArray == nil || actualArray!.count == 0
}
}
/// A Nimble matcher that succeeds when a value is "empty". For collections, this
/// means the are no items in that collection. For strings, it is an empty string.
public func beEmpty() -> NonNilMatcherFunc {
return NonNilMatcherFunc { actualExpression, failureMessage in
failureMessage.postfixMessage = "be empty"
let actual = try actualExpression.evaluate()
return actual == nil || actual!.count == 0
}
}
#if _runtime(_ObjC)
extension NMBObjCMatcher {
public class func beEmptyMatcher() -> NMBObjCMatcher {
return NMBObjCMatcher(canMatchNil: false) { actualExpression, failureMessage in
let location = actualExpression.location
let actualValue = try! actualExpression.evaluate()
failureMessage.postfixMessage = "be empty"
if let value = actualValue as? NMBCollection {
let expr = Expression(expression: ({ value as NMBCollection }), location: location)
return try! beEmpty().matches(expr, failureMessage: failureMessage)
} else if let value = actualValue as? NSString {
let expr = Expression(expression: ({ value as String }), location: location)
return try! beEmpty().matches(expr, failureMessage: failureMessage)
} else if let actualValue = actualValue {
failureMessage.postfixMessage = "be empty (only works for NSArrays, NSSets, NSIndexSets, NSDictionaries, NSHashTables, and NSStrings)"
failureMessage.actualValue = "\(String(describing: type(of: actualValue))) type"
}
return false
}
}
}
#endif
================================================
FILE: Example/Pods/Nimble/Sources/Nimble/Matchers/BeGreaterThan.swift
================================================
import Foundation
/// A Nimble matcher that succeeds when the actual value is greater than the expected value.
public func beGreaterThan(_ expectedValue: T?) -> NonNilMatcherFunc {
return NonNilMatcherFunc { actualExpression, failureMessage in
failureMessage.postfixMessage = "be greater than <\(stringify(expectedValue))>"
if let actual = try actualExpression.evaluate(), let expected = expectedValue {
return actual > expected
}
return false
}
}
/// A Nimble matcher that succeeds when the actual value is greater than the expected value.
public func beGreaterThan(_ expectedValue: NMBComparable?) -> NonNilMatcherFunc {
return NonNilMatcherFunc { actualExpression, failureMessage in
failureMessage.postfixMessage = "be greater than <\(stringify(expectedValue))>"
let actualValue = try actualExpression.evaluate()
let matches = actualValue != nil && actualValue!.NMB_compare(expectedValue) == ComparisonResult.orderedDescending
return matches
}
}
public func >(lhs: Expectation, rhs: T) {
lhs.to(beGreaterThan(rhs))
}
public func >(lhs: Expectation, rhs: NMBComparable?) {
lhs.to(beGreaterThan(rhs))
}
#if _runtime(_ObjC)
extension NMBObjCMatcher {
public class func beGreaterThanMatcher(_ expected: NMBComparable?) -> NMBObjCMatcher {
return NMBObjCMatcher(canMatchNil: false) { actualExpression, failureMessage in
let expr = actualExpression.cast { $0 as? NMBComparable }
return try! beGreaterThan(expected).matches(expr, failureMessage: failureMessage)
}
}
}
#endif
================================================
FILE: Example/Pods/Nimble/Sources/Nimble/Matchers/BeGreaterThanOrEqualTo.swift
================================================
import Foundation
/// A Nimble matcher that succeeds when the actual value is greater than
/// or equal to the expected value.
public func beGreaterThanOrEqualTo(_ expectedValue: T?) -> NonNilMatcherFunc {
return NonNilMatcherFunc { actualExpression, failureMessage in
failureMessage.postfixMessage = "be greater than or equal to <\(stringify(expectedValue))>"
let actualValue = try actualExpression.evaluate()
if let actual = actualValue, let expected = expectedValue {
return actual >= expected
}
return false
}
}
/// A Nimble matcher that succeeds when the actual value is greater than
/// or equal to the expected value.
public func beGreaterThanOrEqualTo(_ expectedValue: T?) -> NonNilMatcherFunc {
return NonNilMatcherFunc { actualExpression, failureMessage in
failureMessage.postfixMessage = "be greater than or equal to <\(stringify(expectedValue))>"
let actualValue = try actualExpression.evaluate()
let matches = actualValue != nil && actualValue!.NMB_compare(expectedValue) != ComparisonResult.orderedAscending
return matches
}
}
public func >=(lhs: Expectation, rhs: T) {
lhs.to(beGreaterThanOrEqualTo(rhs))
}
public func >=(lhs: Expectation, rhs: T) {
lhs.to(beGreaterThanOrEqualTo(rhs))
}
#if _runtime(_ObjC)
extension NMBObjCMatcher {
public class func beGreaterThanOrEqualToMatcher(_ expected: NMBComparable?) -> NMBObjCMatcher {
return NMBObjCMatcher(canMatchNil: false) { actualExpression, failureMessage in
let expr = actualExpression.cast { $0 as? NMBComparable }
return try! beGreaterThanOrEqualTo(expected).matches(expr, failureMessage: failureMessage)
}
}
}
#endif
================================================
FILE: Example/Pods/Nimble/Sources/Nimble/Matchers/BeIdenticalTo.swift
================================================
import Foundation
/// A Nimble matcher that succeeds when the actual value is the same instance
/// as the expected instance.
public func beIdenticalTo(_ expected: Any?) -> NonNilMatcherFunc {
return NonNilMatcherFunc { actualExpression, failureMessage in
#if os(Linux)
let actual = try actualExpression.evaluate() as? AnyObject
#else
let actual = try actualExpression.evaluate() as AnyObject?
#endif
failureMessage.actualValue = "\(identityAsString(actual))"
failureMessage.postfixMessage = "be identical to \(identityAsString(expected))"
#if os(Linux)
return actual === (expected as? AnyObject) && actual !== nil
#else
return actual === (expected as AnyObject?) && actual !== nil
#endif
}
}
public func ===(lhs: Expectation, rhs: Any?) {
lhs.to(beIdenticalTo(rhs))
}
public func !==(lhs: Expectation, rhs: Any?) {
lhs.toNot(beIdenticalTo(rhs))
}
/// A Nimble matcher that succeeds when the actual value is the same instance
/// as the expected instance.
///
/// Alias for "beIdenticalTo".
public func be(_ expected: Any?) -> NonNilMatcherFunc {
return beIdenticalTo(expected)
}
#if _runtime(_ObjC)
extension NMBObjCMatcher {
public class func beIdenticalToMatcher(_ expected: NSObject?) -> NMBObjCMatcher {
return NMBObjCMatcher(canMatchNil: false) { actualExpression, failureMessage in
let aExpr = actualExpression.cast { $0 as Any? }
return try! beIdenticalTo(expected).matches(aExpr, failureMessage: failureMessage)
}
}
}
#endif
================================================
FILE: Example/Pods/Nimble/Sources/Nimble/Matchers/BeLessThan.swift
================================================
import Foundation
/// A Nimble matcher that succeeds when the actual value is less than the expected value.
public func beLessThan(_ expectedValue: T?) -> NonNilMatcherFunc {
return NonNilMatcherFunc { actualExpression, failureMessage in
failureMessage.postfixMessage = "be less than <\(stringify(expectedValue))>"
if let actual = try actualExpression.evaluate(), let expected = expectedValue {
return actual < expected
}
return false
}
}
/// A Nimble matcher that succeeds when the actual value is less than the expected value.
public func beLessThan(_ expectedValue: NMBComparable?) -> NonNilMatcherFunc {
return NonNilMatcherFunc { actualExpression, failureMessage in
failureMessage.postfixMessage = "be less than <\(stringify(expectedValue))>"
let actualValue = try actualExpression.evaluate()
let matches = actualValue != nil && actualValue!.NMB_compare(expectedValue) == ComparisonResult.orderedAscending
return matches
}
}
public func <(lhs: Expectation, rhs: T) {
lhs.to(beLessThan(rhs))
}
public func <(lhs: Expectation, rhs: NMBComparable?) {
lhs.to(beLessThan(rhs))
}
#if _runtime(_ObjC)
extension NMBObjCMatcher {
public class func beLessThanMatcher(_ expected: NMBComparable?) -> NMBObjCMatcher {
return NMBObjCMatcher(canMatchNil: false) { actualExpression, failureMessage in
let expr = actualExpression.cast { $0 as? NMBComparable }
return try! beLessThan(expected).matches(expr, failureMessage: failureMessage)
}
}
}
#endif
================================================
FILE: Example/Pods/Nimble/Sources/Nimble/Matchers/BeLessThanOrEqual.swift
================================================
import Foundation
/// A Nimble matcher that succeeds when the actual value is less than
/// or equal to the expected value.
public func beLessThanOrEqualTo(_ expectedValue: T?) -> NonNilMatcherFunc {
return NonNilMatcherFunc { actualExpression, failureMessage in
failureMessage.postfixMessage = "be less than or equal to <\(stringify(expectedValue))>"
if let actual = try actualExpression.evaluate(), let expected = expectedValue {
return actual <= expected
}
return false
}
}
/// A Nimble matcher that succeeds when the actual value is less than
/// or equal to the expected value.
public func beLessThanOrEqualTo(_ expectedValue: T?) -> NonNilMatcherFunc {
return NonNilMatcherFunc { actualExpression, failureMessage in
failureMessage.postfixMessage = "be less than or equal to <\(stringify(expectedValue))>"
let actualValue = try actualExpression.evaluate()
return actualValue != nil && actualValue!.NMB_compare(expectedValue) != ComparisonResult.orderedDescending
}
}
public func <=(lhs: Expectation, rhs: T) {
lhs.to(beLessThanOrEqualTo(rhs))
}
public func <=(lhs: Expectation, rhs: T) {
lhs.to(beLessThanOrEqualTo(rhs))
}
#if _runtime(_ObjC)
extension NMBObjCMatcher {
public class func beLessThanOrEqualToMatcher(_ expected: NMBComparable?) -> NMBObjCMatcher {
return NMBObjCMatcher(canMatchNil:false) { actualExpression, failureMessage in
let expr = actualExpression.cast { $0 as? NMBComparable }
return try! beLessThanOrEqualTo(expected).matches(expr, failureMessage: failureMessage)
}
}
}
#endif
================================================
FILE: Example/Pods/Nimble/Sources/Nimble/Matchers/BeLogical.swift
================================================
import Foundation
extension Int8: ExpressibleByBooleanLiteral {
public init(booleanLiteral value: Bool) {
self = NSNumber(value: value).int8Value
}
}
extension UInt8: ExpressibleByBooleanLiteral {
public init(booleanLiteral value: Bool) {
self = NSNumber(value: value).uint8Value
}
}
extension Int16: ExpressibleByBooleanLiteral {
public init(booleanLiteral value: Bool) {
self = NSNumber(value: value).int16Value
}
}
extension UInt16: ExpressibleByBooleanLiteral {
public init(booleanLiteral value: Bool) {
self = NSNumber(value: value).uint16Value
}
}
extension Int32: ExpressibleByBooleanLiteral {
public init(booleanLiteral value: Bool) {
self = NSNumber(value: value).int32Value
}
}
extension UInt32: ExpressibleByBooleanLiteral {
public init(booleanLiteral value: Bool) {
self = NSNumber(value: value).uint32Value
}
}
extension Int64: ExpressibleByBooleanLiteral {
public init(booleanLiteral value: Bool) {
self = NSNumber(value: value).int64Value
}
}
extension UInt64: ExpressibleByBooleanLiteral {
public init(booleanLiteral value: Bool) {
self = NSNumber(value: value).uint64Value
}
}
extension Float: ExpressibleByBooleanLiteral {
public init(booleanLiteral value: Bool) {
self = NSNumber(value: value).floatValue
}
}
extension Double: ExpressibleByBooleanLiteral {
public init(booleanLiteral value: Bool) {
self = NSNumber(value: value).doubleValue
}
}
extension Int: ExpressibleByBooleanLiteral {
public init(booleanLiteral value: Bool) {
self = NSNumber(value: value).intValue
}
}
extension UInt: ExpressibleByBooleanLiteral {
public init(booleanLiteral value: Bool) {
self = NSNumber(value: value).uintValue
}
}
internal func matcherWithFailureMessage(_ matcher: NonNilMatcherFunc, postprocessor: @escaping (FailureMessage) -> Void) -> NonNilMatcherFunc {
return NonNilMatcherFunc { actualExpression, failureMessage in
defer { postprocessor(failureMessage) }
return try matcher.matcher(actualExpression, failureMessage)
}
}
// MARK: beTrue() / beFalse()
/// A Nimble matcher that succeeds when the actual value is exactly true.
/// This matcher will not match against nils.
public func beTrue() -> NonNilMatcherFunc {
return matcherWithFailureMessage(equal(true)) { failureMessage in
failureMessage.postfixMessage = "be true"
}
}
/// A Nimble matcher that succeeds when the actual value is exactly false.
/// This matcher will not match against nils.
public func beFalse() -> NonNilMatcherFunc {
return matcherWithFailureMessage(equal(false)) { failureMessage in
failureMessage.postfixMessage = "be false"
}
}
// MARK: beTruthy() / beFalsy()
/// A Nimble matcher that succeeds when the actual value is not logically false.
public func beTruthy() -> MatcherFunc {
return MatcherFunc { actualExpression, failureMessage in
failureMessage.postfixMessage = "be truthy"
let actualValue = try actualExpression.evaluate()
if let actualValue = actualValue {
// FIXME: This is a workaround to SR-2290.
// See:
// - https://bugs.swift.org/browse/SR-2290
// - https://github.com/norio-nomura/Nimble/pull/5#issuecomment-237835873
if let number = actualValue as? NSNumber {
return number.boolValue == true
}
return actualValue == (true as T)
}
return actualValue != nil
}
}
/// A Nimble matcher that succeeds when the actual value is logically false.
/// This matcher will match against nils.
public func beFalsy() -> MatcherFunc {
return MatcherFunc { actualExpression, failureMessage in
failureMessage.postfixMessage = "be falsy"
let actualValue = try actualExpression.evaluate()
if let actualValue = actualValue {
// FIXME: This is a workaround to SR-2290.
// See:
// - https://bugs.swift.org/browse/SR-2290
// - https://github.com/norio-nomura/Nimble/pull/5#issuecomment-237835873
if let number = actualValue as? NSNumber {
return number.boolValue == false
}
return actualValue == (false as T)
}
return actualValue == nil
}
}
#if _runtime(_ObjC)
extension NMBObjCMatcher {
public class func beTruthyMatcher() -> NMBObjCMatcher {
return NMBObjCMatcher { actualExpression, failureMessage in
let expr = actualExpression.cast { ($0 as? NSNumber)?.boolValue ?? false }
return try! beTruthy().matches(expr, failureMessage: failureMessage)
}
}
public class func beFalsyMatcher() -> NMBObjCMatcher {
return NMBObjCMatcher { actualExpression, failureMessage in
let expr = actualExpression.cast { ($0 as? NSNumber)?.boolValue ?? false }
return try! beFalsy().matches(expr, failureMessage: failureMessage)
}
}
public class func beTrueMatcher() -> NMBObjCMatcher {
return NMBObjCMatcher { actualExpression, failureMessage in
let expr = actualExpression.cast { ($0 as? NSNumber)?.boolValue ?? false }
return try! beTrue().matches(expr, failureMessage: failureMessage)
}
}
public class func beFalseMatcher() -> NMBObjCMatcher {
return NMBObjCMatcher(canMatchNil: false) { actualExpression, failureMessage in
let expr = actualExpression.cast { ($0 as? NSNumber)?.boolValue ?? false }
return try! beFalse().matches(expr, failureMessage: failureMessage)
}
}
}
#endif
================================================
FILE: Example/Pods/Nimble/Sources/Nimble/Matchers/BeNil.swift
================================================
import Foundation
/// A Nimble matcher that succeeds when the actual value is nil.
public func beNil() -> MatcherFunc {
return MatcherFunc { actualExpression, failureMessage in
failureMessage.postfixMessage = "be nil"
let actualValue = try actualExpression.evaluate()
return actualValue == nil
}
}
#if _runtime(_ObjC)
extension NMBObjCMatcher {
public class func beNilMatcher() -> NMBObjCMatcher {
return NMBObjCMatcher { actualExpression, failureMessage in
return try! beNil().matches(actualExpression, failureMessage: failureMessage)
}
}
}
#endif
================================================
FILE: Example/Pods/Nimble/Sources/Nimble/Matchers/BeVoid.swift
================================================
import Foundation
/// A Nimble matcher that succeeds when the actual value is Void.
public func beVoid() -> MatcherFunc<()> {
return MatcherFunc { actualExpression, failureMessage in
failureMessage.postfixMessage = "be void"
let actualValue: ()? = try actualExpression.evaluate()
return actualValue != nil
}
}
public func ==(lhs: Expectation<()>, rhs: ()) {
lhs.to(beVoid())
}
public func !=(lhs: Expectation<()>, rhs: ()) {
lhs.toNot(beVoid())
}
================================================
FILE: Example/Pods/Nimble/Sources/Nimble/Matchers/BeginWith.swift
================================================
import Foundation
/// A Nimble matcher that succeeds when the actual sequence's first element
/// is equal to the expected value.
public func beginWith(_ startingElement: T) -> NonNilMatcherFunc
where S.Iterator.Element == T
{
return NonNilMatcherFunc { actualExpression, failureMessage in
failureMessage.postfixMessage = "begin with <\(startingElement)>"
if let actualValue = try actualExpression.evaluate() {
var actualGenerator = actualValue.makeIterator()
return actualGenerator.next() == startingElement
}
return false
}
}
/// A Nimble matcher that succeeds when the actual collection's first element
/// is equal to the expected object.
public func beginWith(_ startingElement: Any) -> NonNilMatcherFunc {
return NonNilMatcherFunc { actualExpression, failureMessage in
failureMessage.postfixMessage = "begin with <\(startingElement)>"
guard let collection = try actualExpression.evaluate() else { return false }
guard collection.count > 0 else { return false }
#if os(Linux)
guard let collectionValue = collection.object(at: 0) as? NSObject else {
return false
}
#else
let collectionValue = collection.object(at: 0) as AnyObject
#endif
return collectionValue.isEqual(startingElement)
}
}
/// A Nimble matcher that succeeds when the actual string contains expected substring
/// where the expected substring's location is zero.
public func beginWith(_ startingSubstring: String) -> NonNilMatcherFunc {
return NonNilMatcherFunc { actualExpression, failureMessage in
failureMessage.postfixMessage = "begin with <\(startingSubstring)>"
if let actual = try actualExpression.evaluate() {
let range = actual.range(of: startingSubstring)
return range != nil && range!.lowerBound == actual.startIndex
}
return false
}
}
#if _runtime(_ObjC)
extension NMBObjCMatcher {
public class func beginWithMatcher(_ expected: Any) -> NMBObjCMatcher {
return NMBObjCMatcher(canMatchNil: false) { actualExpression, failureMessage in
let actual = try! actualExpression.evaluate()
if let _ = actual as? String {
let expr = actualExpression.cast { $0 as? String }
return try! beginWith(expected as! String).matches(expr, failureMessage: failureMessage)
} else {
let expr = actualExpression.cast { $0 as? NMBOrderedCollection }
return try! beginWith(expected).matches(expr, failureMessage: failureMessage)
}
}
}
}
#endif
================================================
FILE: Example/Pods/Nimble/Sources/Nimble/Matchers/Contain.swift
================================================
import Foundation
/// A Nimble matcher that succeeds when the actual sequence contains the expected value.
public func contain(_ items: T...) -> NonNilMatcherFunc
where S.Iterator.Element == T
{
return contain(items)
}
public func contain(_ items: [T]) -> NonNilMatcherFunc
where S.Iterator.Element == T
{
return NonNilMatcherFunc { actualExpression, failureMessage in
failureMessage.postfixMessage = "contain <\(arrayAsString(items))>"
if let actual = try actualExpression.evaluate() {
return items.all {
return actual.contains($0)
}
}
return false
}
}
/// A Nimble matcher that succeeds when the actual string contains the expected substring.
public func contain(_ substrings: String...) -> NonNilMatcherFunc {
return contain(substrings)
}
public func contain(_ substrings: [String]) -> NonNilMatcherFunc {
return NonNilMatcherFunc { actualExpression, failureMessage in
failureMessage.postfixMessage = "contain <\(arrayAsString(substrings))>"
if let actual = try actualExpression.evaluate() {
return substrings.all {
let range = actual.range(of: $0)
return range != nil && !range!.isEmpty
}
}
return false
}
}
/// A Nimble matcher that succeeds when the actual string contains the expected substring.
public func contain(_ substrings: NSString...) -> NonNilMatcherFunc {
return contain(substrings)
}
public func contain(_ substrings: [NSString]) -> NonNilMatcherFunc {
return NonNilMatcherFunc { actualExpression, failureMessage in
failureMessage.postfixMessage = "contain <\(arrayAsString(substrings))>"
if let actual = try actualExpression.evaluate() {
return substrings.all { actual.range(of: $0.description).length != 0 }
}
return false
}
}
/// A Nimble matcher that succeeds when the actual collection contains the expected object.
public func contain(_ items: Any?...) -> NonNilMatcherFunc {
return contain(items)
}
public func contain(_ items: [Any?]) -> NonNilMatcherFunc {
return NonNilMatcherFunc { actualExpression, failureMessage in
failureMessage.postfixMessage = "contain <\(arrayAsString(items))>"
guard let actual = try actualExpression.evaluate() else { return false }
return items.all { item in
return item != nil && actual.contains(item!)
}
}
}
#if _runtime(_ObjC)
extension NMBObjCMatcher {
public class func containMatcher(_ expected: [NSObject]) -> NMBObjCMatcher {
return NMBObjCMatcher(canMatchNil: false) { actualExpression, failureMessage in
let location = actualExpression.location
let actualValue = try! actualExpression.evaluate()
if let value = actualValue as? NMBContainer {
let expr = Expression(expression: ({ value as NMBContainer }), location: location)
// A straightforward cast on the array causes this to crash, so we have to cast the individual items
let expectedOptionals: [Any?] = expected.map({ $0 as Any? })
return try! contain(expectedOptionals).matches(expr, failureMessage: failureMessage)
} else if let value = actualValue as? NSString {
let expr = Expression(expression: ({ value as String }), location: location)
return try! contain(expected as! [String]).matches(expr, failureMessage: failureMessage)
} else if actualValue != nil {
failureMessage.postfixMessage = "contain <\(arrayAsString(expected))> (only works for NSArrays, NSSets, NSHashTables, and NSStrings)"
} else {
failureMessage.postfixMessage = "contain <\(arrayAsString(expected))>"
}
return false
}
}
}
#endif
================================================
FILE: Example/Pods/Nimble/Sources/Nimble/Matchers/EndWith.swift
================================================
import Foundation
/// A Nimble matcher that succeeds when the actual sequence's last element
/// is equal to the expected value.
public func endWith(_ endingElement: T) -> NonNilMatcherFunc
where S.Iterator.Element == T
{
return NonNilMatcherFunc { actualExpression, failureMessage in
failureMessage.postfixMessage = "end with <\(endingElement)>"
if let actualValue = try actualExpression.evaluate() {
var actualGenerator = actualValue.makeIterator()
var lastItem: T?
var item: T?
repeat {
lastItem = item
item = actualGenerator.next()
} while(item != nil)
return lastItem == endingElement
}
return false
}
}
/// A Nimble matcher that succeeds when the actual collection's last element
/// is equal to the expected object.
public func endWith(_ endingElement: Any) -> NonNilMatcherFunc {
return NonNilMatcherFunc { actualExpression, failureMessage in
failureMessage.postfixMessage = "end with <\(endingElement)>"
guard let collection = try actualExpression.evaluate() else { return false }
guard collection.count > 0 else { return false }
#if os(Linux)
guard let collectionValue = collection.object(at: collection.count - 1) as? NSObject else {
return false
}
#else
let collectionValue = collection.object(at: collection.count - 1) as AnyObject
#endif
return collectionValue.isEqual(endingElement)
}
}
/// A Nimble matcher that succeeds when the actual string contains the expected substring
/// where the expected substring's location is the actual string's length minus the
/// expected substring's length.
public func endWith(_ endingSubstring: String) -> NonNilMatcherFunc {
return NonNilMatcherFunc { actualExpression, failureMessage in
failureMessage.postfixMessage = "end with <\(endingSubstring)>"
if let collection = try actualExpression.evaluate() {
return collection.hasSuffix(endingSubstring)
}
return false
}
}
#if _runtime(_ObjC)
extension NMBObjCMatcher {
public class func endWithMatcher(_ expected: Any) -> NMBObjCMatcher {
return NMBObjCMatcher(canMatchNil: false) { actualExpression, failureMessage in
let actual = try! actualExpression.evaluate()
if let _ = actual as? String {
let expr = actualExpression.cast { $0 as? String }
return try! endWith(expected as! String).matches(expr, failureMessage: failureMessage)
} else {
let expr = actualExpression.cast { $0 as? NMBOrderedCollection }
return try! endWith(expected).matches(expr, failureMessage: failureMessage)
}
}
}
}
#endif
================================================
FILE: Example/Pods/Nimble/Sources/Nimble/Matchers/Equal.swift
================================================
import Foundation
/// A Nimble matcher that succeeds when the actual value is equal to the expected value.
/// Values can support equal by supporting the Equatable protocol.
///
/// @see beCloseTo if you want to match imprecise types (eg - floats, doubles).
public func equal(_ expectedValue: T?) -> NonNilMatcherFunc {
return NonNilMatcherFunc { actualExpression, failureMessage in
failureMessage.postfixMessage = "equal <\(stringify(expectedValue))>"
let actualValue = try actualExpression.evaluate()
let matches = actualValue == expectedValue && expectedValue != nil
if expectedValue == nil || actualValue == nil {
if expectedValue == nil {
failureMessage.postfixActual = " (use beNil() to match nils)"
}
return false
}
return matches
}
}
/// A Nimble matcher that succeeds when the actual value is equal to the expected value.
/// Values can support equal by supporting the Equatable protocol.
///
/// @see beCloseTo if you want to match imprecise types (eg - floats, doubles).
public func equal(_ expectedValue: [T: C]?) -> NonNilMatcherFunc<[T: C]> {
return NonNilMatcherFunc { actualExpression, failureMessage in
failureMessage.postfixMessage = "equal <\(stringify(expectedValue))>"
let actualValue = try actualExpression.evaluate()
if expectedValue == nil || actualValue == nil {
if expectedValue == nil {
failureMessage.postfixActual = " (use beNil() to match nils)"
}
return false
}
return expectedValue! == actualValue!
}
}
/// A Nimble matcher that succeeds when the actual collection is equal to the expected collection.
/// Items must implement the Equatable protocol.
public func equal(_ expectedValue: [T]?) -> NonNilMatcherFunc<[T]> {
return NonNilMatcherFunc { actualExpression, failureMessage in
failureMessage.postfixMessage = "equal <\(stringify(expectedValue))>"
let actualValue = try actualExpression.evaluate()
if expectedValue == nil || actualValue == nil {
if expectedValue == nil {
failureMessage.postfixActual = " (use beNil() to match nils)"
}
return false
}
return expectedValue! == actualValue!
}
}
/// A Nimble matcher allowing comparison of collection with optional type
public func equal(_ expectedValue: [T?]) -> NonNilMatcherFunc<[T?]> {
return NonNilMatcherFunc { actualExpression, failureMessage in
failureMessage.postfixMessage = "equal <\(stringify(expectedValue))>"
if let actualValue = try actualExpression.evaluate() {
if expectedValue.count != actualValue.count {
return false
}
for (index, item) in actualValue.enumerated() {
let otherItem = expectedValue[index]
if item == nil && otherItem == nil {
continue
} else if item == nil && otherItem != nil {
return false
} else if item != nil && otherItem == nil {
return false
} else if item! != otherItem! {
return false
}
}
return true
} else {
failureMessage.postfixActual = " (use beNil() to match nils)"
}
return false
}
}
/// A Nimble matcher that succeeds when the actual set is equal to the expected set.
public func equal(_ expectedValue: Set?) -> NonNilMatcherFunc> {
return equal(expectedValue, stringify: { stringify($0) })
}
/// A Nimble matcher that succeeds when the actual set is equal to the expected set.
public func equal(_ expectedValue: Set?) -> NonNilMatcherFunc> {
return equal(expectedValue, stringify: {
if let set = $0 {
return stringify(Array(set).sorted { $0 < $1 })
} else {
return "nil"
}
})
}
private func equal(_ expectedValue: Set?, stringify: @escaping (Set?) -> String) -> NonNilMatcherFunc> {
return NonNilMatcherFunc { actualExpression, failureMessage in
failureMessage.postfixMessage = "equal <\(stringify(expectedValue))>"
if let expectedValue = expectedValue {
if let actualValue = try actualExpression.evaluate() {
failureMessage.actualValue = "<\(stringify(actualValue))>"
if expectedValue == actualValue {
return true
}
let missing = expectedValue.subtracting(actualValue)
if missing.count > 0 {
failureMessage.postfixActual += ", missing <\(stringify(missing))>"
}
let extra = actualValue.subtracting(expectedValue)
if extra.count > 0 {
failureMessage.postfixActual += ", extra <\(stringify(extra))>"
}
}
} else {
failureMessage.postfixActual = " (use beNil() to match nils)"
}
return false
}
}
public func ==(lhs: Expectation, rhs: T?) {
lhs.to(equal(rhs))
}
public func !=(lhs: Expectation, rhs: T?) {
lhs.toNot(equal(rhs))
}
public func ==(lhs: Expectation<[T]>, rhs: [T]?) {
lhs.to(equal(rhs))
}
public func !=(lhs: Expectation<[T]>, rhs: [T]?) {
lhs.toNot(equal(rhs))
}
public func ==(lhs: Expectation>, rhs: Set?) {
lhs.to(equal(rhs))
}
public func !=(lhs: Expectation>, rhs: Set?) {
lhs.toNot(equal(rhs))
}
public func ==(lhs: Expectation>, rhs: Set?) {
lhs.to(equal(rhs))
}
public func !=(lhs: Expectation>, rhs: Set?) {
lhs.toNot(equal(rhs))
}
public func ==(lhs: Expectation<[T: C]>, rhs: [T: C]?) {
lhs.to(equal(rhs))
}
public func !=(lhs: Expectation<[T: C]>, rhs: [T: C]?) {
lhs.toNot(equal(rhs))
}
#if _runtime(_ObjC)
extension NMBObjCMatcher {
public class func equalMatcher(_ expected: NSObject) -> NMBMatcher {
return NMBObjCMatcher(canMatchNil: false) { actualExpression, failureMessage in
return try! equal(expected).matches(actualExpression, failureMessage: failureMessage)
}
}
}
#endif
================================================
FILE: Example/Pods/Nimble/Sources/Nimble/Matchers/HaveCount.swift
================================================
import Foundation
// The `haveCount` matchers do not print the full string representation of the collection value,
// instead they only print the type name and the expected count. This makes it easier to understand
// the reason for failed expectations. See: https://github.com/Quick/Nimble/issues/308.
// The representation of the collection content is provided in a new line as an `extendedMessage`.
/// A Nimble matcher that succeeds when the actual Collection's count equals
/// the expected value
public func haveCount(_ expectedValue: T.IndexDistance) -> NonNilMatcherFunc {
return NonNilMatcherFunc { actualExpression, failureMessage in
if let actualValue = try actualExpression.evaluate() {
failureMessage.postfixMessage = "have \(prettyCollectionType(actualValue)) with count \(stringify(expectedValue))"
let result = expectedValue == actualValue.count
failureMessage.actualValue = "\(actualValue.count)"
failureMessage.extendedMessage = "Actual Value: \(stringify(actualValue))"
return result
} else {
return false
}
}
}
/// A Nimble matcher that succeeds when the actual collection's count equals
/// the expected value
public func haveCount(_ expectedValue: Int) -> MatcherFunc {
return MatcherFunc { actualExpression, failureMessage in
if let actualValue = try actualExpression.evaluate() {
failureMessage.postfixMessage = "have \(prettyCollectionType(actualValue)) with count \(stringify(expectedValue))"
let result = expectedValue == actualValue.count
failureMessage.actualValue = "\(actualValue.count)"
failureMessage.extendedMessage = "Actual Value: \(stringify(actualValue))"
return result
} else {
return false
}
}
}
#if _runtime(_ObjC)
extension NMBObjCMatcher {
public class func haveCountMatcher(_ expected: NSNumber) -> NMBObjCMatcher {
return NMBObjCMatcher(canMatchNil: false) { actualExpression, failureMessage in
let location = actualExpression.location
let actualValue = try! actualExpression.evaluate()
if let value = actualValue as? NMBCollection {
let expr = Expression(expression: ({ value as NMBCollection}), location: location)
return try! haveCount(expected.intValue).matches(expr, failureMessage: failureMessage)
} else if let actualValue = actualValue {
failureMessage.postfixMessage = "get type of NSArray, NSSet, NSDictionary, or NSHashTable"
failureMessage.actualValue = "\(String(describing: type(of: actualValue)))"
}
return false
}
}
}
#endif
================================================
FILE: Example/Pods/Nimble/Sources/Nimble/Matchers/Match.swift
================================================
import Foundation
/// A Nimble matcher that succeeds when the actual string satisfies the regular expression
/// described by the expected string.
public func match(_ expectedValue: String?) -> NonNilMatcherFunc {
return NonNilMatcherFunc { actualExpression, failureMessage in
failureMessage.postfixMessage = "match <\(stringify(expectedValue))>"
if let actual = try actualExpression.evaluate() {
if let regexp = expectedValue {
return actual.range(of: regexp, options: .regularExpression) != nil
}
}
return false
}
}
#if _runtime(_ObjC)
extension NMBObjCMatcher {
public class func matchMatcher(_ expected: NSString) -> NMBMatcher {
return NMBObjCMatcher(canMatchNil: false) { actualExpression, failureMessage in
let actual = actualExpression.cast { $0 as? String }
return try! match(expected.description).matches(actual, failureMessage: failureMessage)
}
}
}
#endif
================================================
FILE: Example/Pods/Nimble/Sources/Nimble/Matchers/MatchError.swift
================================================
import Foundation
/// A Nimble matcher that succeeds when the actual expression evaluates to an
/// error from the specified case.
///
/// Errors are tried to be compared by their implementation of Equatable,
/// otherwise they fallback to comparision by _domain and _code.
public func matchError(_ error: T) -> NonNilMatcherFunc