mirror of
https://github.com/krzysztofzablocki/Sourcery.git
synced 2026-04-07 19:17:40 +00:00
SPM & 5.4 (#951)
* WIP * Fix path to the resources of test target * Introduce SourceryLib target for testing purpose. It is the same as Sourcery but library, not executable. Reason: linker has problems linking test target against executable. * Import main target as SourceryLib when appropriate * Re-enable specs that cause linker errors previously. JS spec left disabled since it needs additional configuration * Add instruction how to fix error while running tests from Xcode * No need to set ejsPath manually when framework is built with SPM anymore. Re-enable JS spec. * Fix file references and build settings * Use single define `SPM` that is set when the project is built by SPM * Add CodableContextTests * Fix build when building with SPM alone * WIP TemplatesTests * Fix executable name * Update TemplatesTests * Fix compilation of Xcode's project * Add note * Replace SPM flag with SWIFT_PACKAGE * Revert Code signing settings * Use release version of Nimble * Point Quick to 3.0.0 version * Optimize imports * Exclude some files * Fix error message * Update template * Change wording * Add entry to CHANGELOG * Rakefile: fix path to ejs.js * Rakefile: fix path to ejs.js #2 * CircleCI config: fix path to ejs.js * Add location of lib_InternalSwiftSyntaxParser.dylib to the -rpath * Use bundled version of lib_InternalSwiftSyntaxParser.dylib * Fix Nimble dependency * Update -rpath of executable too. Otherwise it won't find the library when launched during TemplatesTests. * Fix imports Add 'import Foundation' * Updated bundled sources * feat: remove xcodeproj and add 5.4 * chore: update rakefile * chore: update docs * chore: cleanup rakefile * chore: disable coverage since it won't work with spm only setup Co-authored-by: HeMet <hemet.mail@gmail.com>
This commit is contained in:
committed by
GitHub
parent
6eb6662a1d
commit
e834936a0c
@@ -27,9 +27,8 @@ jobs:
|
||||
- run: set -o pipefail
|
||||
- run: bundle exec rake build
|
||||
- run: bundle exec rake tests
|
||||
- run: swift build && .build/x86_64-apple-macosx/debug/sourcery --sources SourceryRuntime/Sources --templates Templates/Templates --output SourceryRuntime/Sources --ejsPath SourceryJS/Sources/ejs.js
|
||||
- run: bundle exec slather coverage --scheme "$XCODE_SCHEME" --workspace "$XCODE_WORKSPACE" --output-directory $CIRCLE_ARTIFACTS --binary-basename SourceryRuntime --binary-basename Sourcery --cobertura-xml Sourcery.xcodeproj || true
|
||||
- run: bash <(curl -s https://codecov.io/bash) -f $CIRCLE_ARTIFACTS/cobertura.xml -X coveragepy -X gcov -X xcode
|
||||
# - run: bundle exec slather coverage --scheme "$XCODE_SCHEME" --workspace "$XCODE_WORKSPACE" --output-directory $CIRCLE_ARTIFACTS --binary-basename SourceryRuntime --binary-basename Sourcery --cobertura-xml Sourcery.xcodeproj || true
|
||||
# - run: bash <(curl -s https://codecov.io/bash) -f $CIRCLE_ARTIFACTS/cobertura.xml -X coveragepy -X gcov -X xcode
|
||||
|
||||
workflows:
|
||||
version: 2
|
||||
|
||||
+1
-1
@@ -2,7 +2,6 @@ author: Krzysztof Zabłocki
|
||||
author_url: https://twitter.com/merowing_
|
||||
module: Sourcery
|
||||
sourcekitten_sourcefile: docs.json
|
||||
module_version: 0.6.0
|
||||
github_url: https://github.com/krzysztofzablocki/Sourcery
|
||||
copyright: 'Copyright © 2016-2021 Pixle. All rights reserved.'
|
||||
readme: About.md
|
||||
@@ -37,6 +36,7 @@ custom_categories:
|
||||
- Enum
|
||||
- EnumCase
|
||||
- AssociatedValue
|
||||
- AssociatedType
|
||||
- Variable
|
||||
- Method
|
||||
- MethodParameter
|
||||
|
||||
@@ -31,6 +31,7 @@
|
||||
|
||||
## Internal changes
|
||||
- Removes manual parsing of `TypeName`, only explicit parser / configuration is now used
|
||||
- Add support for testing via `SPM`
|
||||
- Updted SwiftLint, Quick and Nible to latest versions
|
||||
|
||||
## 1.3.4
|
||||
|
||||
@@ -7,4 +7,4 @@ gem 'danger-jazzy'
|
||||
gem 'rake'
|
||||
gem 'slather'
|
||||
gem 'xcpretty'
|
||||
gem 'jazzy', '0.8.2'
|
||||
gem 'jazzy', '0.13.6'
|
||||
|
||||
+33
-33
@@ -62,7 +62,7 @@ GEM
|
||||
concurrent-ruby (1.1.8)
|
||||
cork (0.3.0)
|
||||
colored2 (~> 3.1)
|
||||
danger (8.2.1)
|
||||
danger (8.2.3)
|
||||
claide (~> 1.0)
|
||||
claide-plugins (>= 0.9.2)
|
||||
colored2 (~> 3.1)
|
||||
@@ -74,36 +74,42 @@ GEM
|
||||
kramdown-parser-gfm (~> 1.0)
|
||||
no_proxy_fix
|
||||
octokit (~> 4.7)
|
||||
terminal-table (~> 1)
|
||||
terminal-table (>= 1, < 4)
|
||||
danger-jazzy (1.1.0)
|
||||
danger-plugin-api (~> 1.0)
|
||||
json (~> 2.1.0)
|
||||
danger-plugin-api (1.0.0)
|
||||
danger (> 2.0)
|
||||
escape (0.0.4)
|
||||
ethon (0.13.0)
|
||||
ethon (0.14.0)
|
||||
ffi (>= 1.15.0)
|
||||
faraday (1.1.0)
|
||||
faraday (1.4.1)
|
||||
faraday-excon (~> 1.1)
|
||||
faraday-net_http (~> 1.0)
|
||||
faraday-net_http_persistent (~> 1.1)
|
||||
multipart-post (>= 1.2, < 3)
|
||||
ruby2_keywords
|
||||
ruby2_keywords (>= 0.0.4)
|
||||
faraday-excon (1.1.0)
|
||||
faraday-http-cache (2.2.0)
|
||||
faraday (>= 0.8)
|
||||
faraday-net_http (1.0.1)
|
||||
faraday-net_http_persistent (1.1.0)
|
||||
ffi (1.15.0)
|
||||
fourflusher (2.3.1)
|
||||
fuzzy_match (2.0.4)
|
||||
gh_inspector (1.1.3)
|
||||
git (1.7.0)
|
||||
git (1.8.1)
|
||||
rchardet (~> 1.8)
|
||||
httpclient (2.8.3)
|
||||
i18n (1.8.10)
|
||||
concurrent-ruby (~> 1.0)
|
||||
jazzy (0.8.2)
|
||||
cocoapods (~> 1.0)
|
||||
mustache (~> 0.99)
|
||||
jazzy (0.13.6)
|
||||
cocoapods (~> 1.5)
|
||||
mustache (~> 1.1)
|
||||
open4
|
||||
redcarpet (~> 3.2)
|
||||
rouge (~> 1.5)
|
||||
sass (~> 3.4)
|
||||
redcarpet (~> 3.4)
|
||||
rouge (>= 2.0.6, < 4.0)
|
||||
sassc (~> 2.1)
|
||||
sqlite3 (~> 1.3)
|
||||
xcinvoke (~> 0.3.0)
|
||||
json (2.1.0)
|
||||
@@ -112,50 +118,44 @@ GEM
|
||||
kramdown-parser-gfm (1.1.0)
|
||||
kramdown (~> 2.0)
|
||||
liferaft (0.0.6)
|
||||
mini_portile2 (2.5.0)
|
||||
mini_portile2 (2.5.1)
|
||||
minitest (5.14.4)
|
||||
molinillo (0.6.6)
|
||||
multipart-post (2.1.1)
|
||||
mustache (0.99.8)
|
||||
mustache (1.1.1)
|
||||
nanaimo (0.3.0)
|
||||
nap (1.1.0)
|
||||
netrc (0.11.0)
|
||||
no_proxy_fix (0.1.2)
|
||||
nokogiri (1.11.1)
|
||||
nokogiri (1.11.3)
|
||||
mini_portile2 (~> 2.5.0)
|
||||
racc (~> 1.4)
|
||||
octokit (4.19.0)
|
||||
octokit (4.21.0)
|
||||
faraday (>= 0.9)
|
||||
sawyer (~> 0.8.0, >= 0.5.3)
|
||||
open4 (1.3.4)
|
||||
public_suffix (4.0.6)
|
||||
racc (1.5.2)
|
||||
rake (13.0.1)
|
||||
rb-fsevent (0.10.4)
|
||||
rb-inotify (0.10.1)
|
||||
ffi (~> 1.0)
|
||||
rake (13.0.3)
|
||||
rchardet (1.8.0)
|
||||
redcarpet (3.5.1)
|
||||
rexml (3.2.5)
|
||||
rouge (1.11.1)
|
||||
rouge (2.0.7)
|
||||
ruby-macho (1.4.0)
|
||||
ruby2_keywords (0.0.2)
|
||||
sass (3.7.4)
|
||||
sass-listen (~> 4.0.0)
|
||||
sass-listen (4.0.0)
|
||||
rb-fsevent (~> 0.9, >= 0.9.4)
|
||||
rb-inotify (~> 0.9, >= 0.9.7)
|
||||
ruby2_keywords (0.0.4)
|
||||
sassc (2.4.0)
|
||||
ffi (~> 1.9)
|
||||
sawyer (0.8.2)
|
||||
addressable (>= 2.3.5)
|
||||
faraday (> 0.8, < 2.0)
|
||||
slather (2.5.0)
|
||||
slather (2.7.1)
|
||||
CFPropertyList (>= 2.2, < 4)
|
||||
activesupport
|
||||
clamp (~> 1.3)
|
||||
nokogiri (~> 1.8)
|
||||
nokogiri (~> 1.11)
|
||||
xcodeproj (~> 1.7)
|
||||
sqlite3 (1.4.2)
|
||||
terminal-table (1.8.0)
|
||||
terminal-table (3.0.0)
|
||||
unicode-display_width (~> 1.1, >= 1.1.1)
|
||||
thread_safe (0.3.6)
|
||||
typhoeus (1.4.0)
|
||||
@@ -171,8 +171,8 @@ GEM
|
||||
claide (>= 1.0.2, < 2.0)
|
||||
colored2 (~> 3.1)
|
||||
nanaimo (~> 0.3.0)
|
||||
xcpretty (0.2.6)
|
||||
rouge (~> 1.8)
|
||||
xcpretty (0.3.0)
|
||||
rouge (~> 2.0.7)
|
||||
|
||||
PLATFORMS
|
||||
ruby
|
||||
@@ -182,7 +182,7 @@ DEPENDENCIES
|
||||
cocoapods-update-if-you-dare
|
||||
danger
|
||||
danger-jazzy
|
||||
jazzy (= 0.8.2)
|
||||
jazzy (= 0.13.6)
|
||||
rake
|
||||
slather
|
||||
xcpretty
|
||||
|
||||
+38
-2
@@ -19,6 +19,24 @@
|
||||
"version": "0.9.1"
|
||||
}
|
||||
},
|
||||
{
|
||||
"package": "CwlCatchException",
|
||||
"repositoryURL": "https://github.com/mattgallagher/CwlCatchException.git",
|
||||
"state": {
|
||||
"branch": null,
|
||||
"revision": "f809deb30dc5c9d9b78c872e553261a61177721a",
|
||||
"version": "2.0.0"
|
||||
}
|
||||
},
|
||||
{
|
||||
"package": "CwlPreconditionTesting",
|
||||
"repositoryURL": "https://github.com/mattgallagher/CwlPreconditionTesting.git",
|
||||
"state": {
|
||||
"branch": null,
|
||||
"revision": "02b7a39a99c4da27abe03cab2053a9034379639f",
|
||||
"version": "2.0.0"
|
||||
}
|
||||
},
|
||||
{
|
||||
"package": "Komondor",
|
||||
"repositoryURL": "https://github.com/shibapm/Komondor.git",
|
||||
@@ -28,6 +46,15 @@
|
||||
"version": "1.0.6"
|
||||
}
|
||||
},
|
||||
{
|
||||
"package": "Nimble",
|
||||
"repositoryURL": "https://github.com/Quick/Nimble.git",
|
||||
"state": {
|
||||
"branch": null,
|
||||
"revision": "e491a6731307bb23783bf664d003be9b2fa59ab5",
|
||||
"version": "9.0.0"
|
||||
}
|
||||
},
|
||||
{
|
||||
"package": "PackageConfig",
|
||||
"repositoryURL": "https://github.com/shibapm/PackageConfig.git",
|
||||
@@ -46,6 +73,15 @@
|
||||
"version": "1.0.0"
|
||||
}
|
||||
},
|
||||
{
|
||||
"package": "Quick",
|
||||
"repositoryURL": "https://github.com/Quick/Quick.git",
|
||||
"state": {
|
||||
"branch": null,
|
||||
"revision": "8cce6acd38f965f5baa3167b939f86500314022b",
|
||||
"version": "3.1.2"
|
||||
}
|
||||
},
|
||||
{
|
||||
"package": "ShellOut",
|
||||
"repositoryURL": "https://github.com/JohnSundell/ShellOut.git",
|
||||
@@ -87,8 +123,8 @@
|
||||
"repositoryURL": "https://github.com/apple/swift-syntax.git",
|
||||
"state": {
|
||||
"branch": null,
|
||||
"revision": "844574d683f53d0737a9c6d706c3ef31ed2955eb",
|
||||
"version": "0.50300.0"
|
||||
"revision": "2fff9fc25cdc059379b6bd309377cfab45d8520c",
|
||||
"version": "0.50400.0"
|
||||
}
|
||||
},
|
||||
{
|
||||
|
||||
+160
-19
@@ -1,6 +1,22 @@
|
||||
// swift-tools-version:5.3
|
||||
|
||||
import PackageDescription
|
||||
import Foundation
|
||||
|
||||
let sourceryDependencies: [Target.Dependency] = [
|
||||
"SourceryFramework",
|
||||
"SourceryRuntime",
|
||||
"SourceryStencil",
|
||||
"SourceryJS",
|
||||
"SourcerySwift",
|
||||
"Commander",
|
||||
"PathKit",
|
||||
"Yams",
|
||||
"StencilSwiftKit",
|
||||
"SwiftSyntax",
|
||||
"XcodeProj",
|
||||
"TryCatch"
|
||||
]
|
||||
|
||||
let package = Package(
|
||||
name: "Sourcery",
|
||||
@@ -9,6 +25,8 @@ let package = Package(
|
||||
],
|
||||
products: [
|
||||
.executable(name: "sourcery", targets: ["Sourcery"]),
|
||||
// For testing purpose. The linker has problems linking against executable.
|
||||
.library(name: "SourceryLib", targets: ["SourceryLib"]),
|
||||
.library(name: "SourceryRuntime", targets: ["SourceryRuntime"]),
|
||||
.library(name: "SourceryStencil", targets: ["SourceryStencil"]),
|
||||
.library(name: "SourceryJS", targets: ["SourceryJS"]),
|
||||
@@ -24,23 +42,29 @@ let package = Package(
|
||||
.package(name: "XcodeProj", url: "https://github.com/tuist/xcodeproj", .exact("7.18.0")),
|
||||
.package(name: "SwiftSyntax",
|
||||
url: "https://github.com/apple/swift-syntax.git",
|
||||
.exact("0.50300.0"))
|
||||
.exact("0.50400.0")),
|
||||
.package(url: "https://github.com/Quick/Quick.git", from: "3.0.0"),
|
||||
.package(url: "https://github.com/Quick/Nimble.git", from: "9.0.0")
|
||||
],
|
||||
targets: [
|
||||
.target(name: "Sourcery", dependencies: [
|
||||
"SourceryFramework",
|
||||
"SourceryRuntime",
|
||||
"SourceryStencil",
|
||||
"SourceryJS",
|
||||
"SourcerySwift",
|
||||
"Commander",
|
||||
"PathKit",
|
||||
"Yams",
|
||||
"StencilSwiftKit",
|
||||
"SwiftSyntax",
|
||||
"XcodeProj",
|
||||
"TryCatch",
|
||||
]),
|
||||
.target(
|
||||
name: "Sourcery",
|
||||
dependencies: sourceryDependencies,
|
||||
exclude: [
|
||||
"Templates",
|
||||
"Info.plist"
|
||||
]
|
||||
),
|
||||
.target(
|
||||
name: "SourceryLib",
|
||||
dependencies: sourceryDependencies,
|
||||
path: "Sourcery",
|
||||
exclude: [
|
||||
"main.swift",
|
||||
"Templates",
|
||||
"Info.plist"
|
||||
]
|
||||
),
|
||||
.target(name: "SourceryRuntime"),
|
||||
.target(name: "SourceryUtils", dependencies: [
|
||||
"PathKit"
|
||||
@@ -56,14 +80,131 @@ let package = Package(
|
||||
"SourceryRuntime",
|
||||
"StencilSwiftKit",
|
||||
]),
|
||||
.target(name: "SourceryJS", dependencies: [
|
||||
"PathKit"
|
||||
]),
|
||||
.target(
|
||||
name: "SourceryJS",
|
||||
dependencies: [
|
||||
"PathKit"
|
||||
],
|
||||
exclude: [
|
||||
"Info.plist"
|
||||
],
|
||||
resources: [
|
||||
.copy("Resources/ejs.js")
|
||||
]
|
||||
),
|
||||
.target(name: "SourcerySwift", dependencies: [
|
||||
"PathKit",
|
||||
"SourceryRuntime",
|
||||
"SourceryUtils"
|
||||
]),
|
||||
.target(name: "TryCatch", path: "TryCatch"),
|
||||
.target(
|
||||
name: "CodableContext",
|
||||
path: "Templates/Tests",
|
||||
exclude: [
|
||||
"Context/AutoCases.swift",
|
||||
"Context/AutoEquatable.swift",
|
||||
"Context/AutoHashable.swift",
|
||||
"Context/AutoLenses.swift",
|
||||
"Context/AutoMockable.swift",
|
||||
"Context/LinuxMain.swift",
|
||||
"Generated/AutoCases.generated.swift",
|
||||
"Generated/AutoEquatable.generated.swift",
|
||||
"Generated/AutoHashable.generated.swift",
|
||||
"Generated/AutoLenses.generated.swift",
|
||||
"Generated/AutoMockable.generated.swift",
|
||||
"Generated/LinuxMain.generated.swift",
|
||||
"Expected",
|
||||
"Info.plist",
|
||||
"TemplatesTests.swift"
|
||||
],
|
||||
sources: [
|
||||
"Context/AutoCodable.swift",
|
||||
"Generated/AutoCodable.generated.swift"
|
||||
]
|
||||
),
|
||||
.target(name: "TryCatch", path: "TryCatch", exclude: ["Info.plist"]),
|
||||
.testTarget(
|
||||
name: "SourceryLibTests",
|
||||
dependencies: [
|
||||
"SourceryLib",
|
||||
"Quick",
|
||||
"Nimble"
|
||||
],
|
||||
exclude: [
|
||||
"Info.plist"
|
||||
],
|
||||
resources: [
|
||||
.copy("Stub/Configs"),
|
||||
.copy("Stub/Errors"),
|
||||
.copy("Stub/JavaScriptTemplates"),
|
||||
.copy("Stub/SwiftTemplates"),
|
||||
.copy("Stub/Performance-Code"),
|
||||
.copy("Stub/Result"),
|
||||
.copy("Stub/Templates"),
|
||||
.copy("Stub/Source")
|
||||
]
|
||||
),
|
||||
.testTarget(
|
||||
name: "CodableContextTests",
|
||||
dependencies: [
|
||||
"CodableContext",
|
||||
"Quick",
|
||||
"Nimble"
|
||||
],
|
||||
path: "Templates/CodableContextTests",
|
||||
exclude: [
|
||||
"Info.plist"
|
||||
]
|
||||
),
|
||||
.testTarget(
|
||||
name: "TemplatesTests",
|
||||
dependencies: [
|
||||
"Quick",
|
||||
"Nimble",
|
||||
"PathKit"
|
||||
],
|
||||
path: "Templates",
|
||||
exclude: [
|
||||
"CodableContext",
|
||||
"CodableContextTests",
|
||||
"Tests/Generated",
|
||||
"Tests/Info.plist",
|
||||
"default.profraw"
|
||||
],
|
||||
sources: [
|
||||
// LinuxMain is not compiled as part of the target
|
||||
// since there is no way to run script before compilation begins.
|
||||
"Tests/TemplatesTests.swift"
|
||||
],
|
||||
resources: [
|
||||
.copy("Templates"),
|
||||
.copy("Tests/Context"),
|
||||
.copy("Tests/Expected")
|
||||
]
|
||||
)
|
||||
]
|
||||
)
|
||||
|
||||
hookInternalSwiftSyntaxParser()
|
||||
|
||||
/// We need to manually add an -rpath to the project so the tests can run via Xcode
|
||||
/// If we are running from console (swift build & friend) we don't need to do it
|
||||
func hookInternalSwiftSyntaxParser() {
|
||||
let isFromTerminal = ProcessInfo.processInfo.environment.values.contains("/usr/bin/swift") || ProcessInfo.processInfo.environment.values.contains(where: { $0.contains("sourcekitten") || $0.contains("/bin/rake") || $0.contains("bin/bundle") })
|
||||
if !isFromTerminal {
|
||||
package
|
||||
.targets
|
||||
.filter { $0.isTest || $0.name == "Sourcery" }
|
||||
.forEach { $0.installSwiftSyntaxParser() }
|
||||
}
|
||||
}
|
||||
|
||||
extension PackageDescription.Target {
|
||||
func installSwiftSyntaxParser() {
|
||||
linkerSettings = [.unsafeFlags(["-rpath", packageRoot])]
|
||||
}
|
||||
|
||||
var packageRoot: String {
|
||||
return URL(fileURLWithPath: #file).deletingLastPathComponent().path
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,64 +0,0 @@
|
||||
# Uncomment this line to define a global platform for your project
|
||||
platform :osx, '10.11'
|
||||
|
||||
workspace 'Sourcery.xcworkspace'
|
||||
use_frameworks!
|
||||
inhibit_all_warnings!
|
||||
|
||||
def meta
|
||||
pod 'SwiftLint'
|
||||
end
|
||||
|
||||
def test_pods
|
||||
pod 'Quick'
|
||||
pod 'Nimble'
|
||||
end
|
||||
|
||||
def pathkit
|
||||
pod 'PathKit', '1.0.0'
|
||||
end
|
||||
|
||||
target 'TemplatesTests' do
|
||||
project 'Templates/Templates.xcodeproj'
|
||||
meta
|
||||
test_pods
|
||||
end
|
||||
target 'CodableContextTests' do
|
||||
project 'Templates/Templates.xcodeproj'
|
||||
meta
|
||||
test_pods
|
||||
end
|
||||
|
||||
target 'Sourcery' do
|
||||
pod 'Commander', '0.9.1'
|
||||
pathkit
|
||||
pod "xcodeproj", :git =>'git@github.com:tuist/XcodeProj.git', :tag => '7.18.0'
|
||||
pod 'Yams', '4.0.0'
|
||||
|
||||
target 'SourceryTests' do
|
||||
inherit! :search_paths
|
||||
test_pods
|
||||
end
|
||||
end
|
||||
|
||||
target 'SourceryJS' do
|
||||
pathkit
|
||||
end
|
||||
|
||||
target 'SourcerySwift' do
|
||||
pathkit
|
||||
end
|
||||
|
||||
target 'SourceryStencil' do
|
||||
pod 'Stencil', '0.14.0'
|
||||
pod 'StencilSwiftKit', '2.8.0'
|
||||
pathkit
|
||||
end
|
||||
|
||||
target 'SourceryUtils' do
|
||||
pathkit
|
||||
end
|
||||
|
||||
target 'SourceryFramework' do
|
||||
pathkit
|
||||
end
|
||||
@@ -1,64 +0,0 @@
|
||||
PODS:
|
||||
- AEXML (4.6.0)
|
||||
- Commander (0.9.1)
|
||||
- Nimble (9.0.0)
|
||||
- PathKit (1.0.0)
|
||||
- Quick (3.1.2)
|
||||
- Stencil (0.14.0):
|
||||
- PathKit (~> 1.0.0)
|
||||
- StencilSwiftKit (2.8.0):
|
||||
- Stencil (~> 0.14.0)
|
||||
- SwiftLint (0.43.1)
|
||||
- xcodeproj (7.18.0):
|
||||
- AEXML (~> 4.6.0)
|
||||
- PathKit (~> 1.0.0)
|
||||
- Yams (4.0.0)
|
||||
|
||||
DEPENDENCIES:
|
||||
- Commander (= 0.9.1)
|
||||
- Nimble
|
||||
- PathKit (= 1.0.0)
|
||||
- Quick
|
||||
- Stencil (= 0.14.0)
|
||||
- StencilSwiftKit (= 2.8.0)
|
||||
- SwiftLint
|
||||
- "xcodeproj (from `git@github.com:tuist/XcodeProj.git`, tag `7.18.0`)"
|
||||
- Yams (= 4.0.0)
|
||||
|
||||
SPEC REPOS:
|
||||
trunk:
|
||||
- AEXML
|
||||
- Commander
|
||||
- Nimble
|
||||
- PathKit
|
||||
- Quick
|
||||
- Stencil
|
||||
- StencilSwiftKit
|
||||
- SwiftLint
|
||||
- Yams
|
||||
|
||||
EXTERNAL SOURCES:
|
||||
xcodeproj:
|
||||
:git: "git@github.com:tuist/XcodeProj.git"
|
||||
:tag: 7.18.0
|
||||
|
||||
CHECKOUT OPTIONS:
|
||||
xcodeproj:
|
||||
:git: "git@github.com:tuist/XcodeProj.git"
|
||||
:tag: 7.18.0
|
||||
|
||||
SPEC CHECKSUMS:
|
||||
AEXML: 2fbb73d8724797ed2cde888731e176fa4d44dd83
|
||||
Commander: 723330cf3697b604c00afb9db9576be81a03c501
|
||||
Nimble: 3b4ec3fd40f1dc178058e0981107721c615643d8
|
||||
PathKit: 364e0de7fb5adb142aecab4e112187e5548fc4b6
|
||||
Quick: 60f0ea3b8e0cfc0df3259a5c06a238ad8b3c46e0
|
||||
Stencil: 19487b54873a6ed8d8e4cccc4b45c1a601941f06
|
||||
StencilSwiftKit: 946b0a1ae1067ef195231a135fe6d8f240b46942
|
||||
SwiftLint: 99f82d07b837b942dd563c668de129a03fc3fb52
|
||||
xcodeproj: 760cfd754df4cfac71ec86b1cbdd6075f9fd3102
|
||||
Yams: 9d49b85824751ee13d31e9ec6617c4dfb9a8c3cd
|
||||
|
||||
PODFILE CHECKSUM: 53232264d2ea3889cc7168839639589c41eeb9a0
|
||||
|
||||
COCOAPODS: 1.10.1
|
||||
Generated
-19
@@ -1,19 +0,0 @@
|
||||
Copyright (c) 2014-2020 Marko Tadić <tadija@me.com> http://tadija.net
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
Generated
-194
@@ -1,194 +0,0 @@
|
||||
[](https://swift.org)
|
||||
[](http://www.apple.com)
|
||||
[](https://cocoapods.org/pods/AEXML)
|
||||
[](https://github.com/Carthage/Carthage)
|
||||
[](https://github.com/apple/swift-package-manager)
|
||||
[](https://github.com/tadija/AEXML/blob/master/LICENSE)
|
||||
|
||||
# AEXML
|
||||
|
||||
**Swift minion for simple and lightweight XML parsing**
|
||||
|
||||
> I made this for personal use, but feel free to use it or contribute.
|
||||
> For more examples check out [Sources](Sources) and [Tests](Tests).
|
||||
|
||||
## Index
|
||||
- [Intro](#intro)
|
||||
- [Features](#features)
|
||||
- [Usage](#usage)
|
||||
- [Read XML](#read-xml)
|
||||
- [Write XML](#write-xml)
|
||||
- [Installation](#installation)
|
||||
- [License](#license)
|
||||
|
||||
## Intro
|
||||
|
||||
This is not a robust full featured XML parser, but rather simple, lightweight and easy to use utility for casual XML handling.
|
||||
|
||||
## Features
|
||||
- **Read XML** data
|
||||
- **Write XML** string
|
||||
- Covered with [unit tests](https://github.com/tadija/AEXML/blob/master/Tests/AEXMLTests.swift)
|
||||
- Covered with inline docs
|
||||
|
||||
## Usage
|
||||
|
||||
### Read XML
|
||||
Let's say this is some XML string you picked up somewhere and made a variable `data: Data` from that.
|
||||
|
||||
```xml
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<animals>
|
||||
<cats>
|
||||
<cat breed="Siberian" color="lightgray">Tinna</cat>
|
||||
<cat breed="Domestic" color="darkgray">Rose</cat>
|
||||
<cat breed="Domestic" color="yellow">Caesar</cat>
|
||||
<cat></cat>
|
||||
</cats>
|
||||
<dogs>
|
||||
<dog breed="Bull Terrier" color="white">Villy</dog>
|
||||
<dog breed="Bull Terrier" color="white">Spot</dog>
|
||||
<dog breed="Golden Retriever" color="yellow">Betty</dog>
|
||||
<dog breed="Miniature Schnauzer" color="black">Kika</dog>
|
||||
</dogs>
|
||||
</animals>
|
||||
```
|
||||
|
||||
This is how you can use **AEXML** for working with this data:
|
||||
(for even more examples, look at the unit tests code included in project)
|
||||
|
||||
```swift
|
||||
guard let
|
||||
let xmlPath = Bundle.main.path(forResource: "example", ofType: "xml"),
|
||||
let data = try? Data(contentsOf: URL(fileURLWithPath: xmlPath))
|
||||
else { return }
|
||||
|
||||
do {
|
||||
let xmlDoc = try AEXMLDocument(xml: data, options: options)
|
||||
|
||||
// prints the same XML structure as original
|
||||
print(xmlDoc.xml)
|
||||
|
||||
// prints cats, dogs
|
||||
for child in xmlDoc.root.children {
|
||||
print(child.name)
|
||||
}
|
||||
|
||||
// prints Optional("Tinna") (first element)
|
||||
print(xmlDoc.root["cats"]["cat"].value)
|
||||
|
||||
// prints Tinna (first element)
|
||||
print(xmlDoc.root["cats"]["cat"].string)
|
||||
|
||||
// prints Optional("Kika") (last element)
|
||||
print(xmlDoc.root["dogs"]["dog"].last?.value)
|
||||
|
||||
// prints Betty (3rd element)
|
||||
print(xmlDoc.root["dogs"].children[2].string)
|
||||
|
||||
// prints Tinna, Rose, Caesar
|
||||
if let cats = xmlDoc.root["cats"]["cat"].all {
|
||||
for cat in cats {
|
||||
if let name = cat.value {
|
||||
print(name)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// prints Villy, Spot
|
||||
for dog in xmlDoc.root["dogs"]["dog"].all! {
|
||||
if let color = dog.attributes["color"] {
|
||||
if color == "white" {
|
||||
print(dog.string)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// prints Tinna
|
||||
if let cats = xmlDoc.root["cats"]["cat"].all(withValue: "Tinna") {
|
||||
for cat in cats {
|
||||
print(cat.string)
|
||||
}
|
||||
}
|
||||
|
||||
// prints Caesar
|
||||
if let cats = xmlDoc.root["cats"]["cat"].all(withAttributes: ["breed" : "Domestic", "color" : "yellow"]) {
|
||||
for cat in cats {
|
||||
print(cat.string)
|
||||
}
|
||||
}
|
||||
|
||||
// prints 4
|
||||
print(xmlDoc.root["cats"]["cat"].count)
|
||||
|
||||
// prints Siberian
|
||||
print(xmlDoc.root["cats"]["cat"].attributes["breed"]!)
|
||||
|
||||
// prints <cat breed="Siberian" color="lightgray">Tinna</cat>
|
||||
print(xmlDoc.root["cats"]["cat"].xmlCompact)
|
||||
|
||||
// prints Optional(AEXML.AEXMLError.elementNotFound)
|
||||
print(xmlDoc["NotExistingElement"].error)
|
||||
}
|
||||
catch {
|
||||
print("\(error)")
|
||||
}
|
||||
```
|
||||
|
||||
### Write XML
|
||||
Let's say this is some SOAP XML request you need to generate.
|
||||
Well, you could just build ordinary string for that?
|
||||
|
||||
```xml
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<soap:Envelope xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
|
||||
<soap:Header>
|
||||
<m:Trans xmlns:m="http://www.w3schools.com/transaction/" soap:mustUnderstand="1">234</m:Trans>
|
||||
</soap:Header>
|
||||
<soap:Body>
|
||||
<m:GetStockPrice>
|
||||
<m:StockName>AAPL</m:StockName>
|
||||
</m:GetStockPrice>
|
||||
</soap:Body>
|
||||
</soap:Envelope>
|
||||
```
|
||||
|
||||
Yes, but, you can also do it in a more structured and elegant way with AEXML:
|
||||
|
||||
```swift
|
||||
// create XML Document
|
||||
let soapRequest = AEXMLDocument()
|
||||
let attributes = ["xmlns:xsi" : "http://www.w3.org/2001/XMLSchema-instance", "xmlns:xsd" : "http://www.w3.org/2001/XMLSchema"]
|
||||
let envelope = soapRequest.addChild(name: "soap:Envelope", attributes: attributes)
|
||||
let header = envelope.addChild(name: "soap:Header")
|
||||
let body = envelope.addChild(name: "soap:Body")
|
||||
header.addChild(name: "m:Trans", value: "234", attributes: ["xmlns:m" : "http://www.w3schools.com/transaction/", "soap:mustUnderstand" : "1"])
|
||||
let getStockPrice = body.addChild(name: "m:GetStockPrice")
|
||||
getStockPrice.addChild(name: "m:StockName", value: "AAPL")
|
||||
|
||||
// prints the same XML structure as original
|
||||
print(soapRequest.xml)
|
||||
```
|
||||
|
||||
## Installation
|
||||
|
||||
- [Swift Package Manager](https://swift.org/package-manager/):
|
||||
|
||||
```swift
|
||||
.package(url: "https://github.com/tadija/AEXML.git", from: "4.6.0")
|
||||
```
|
||||
|
||||
- [Carthage](https://github.com/Carthage/Carthage):
|
||||
|
||||
```ogdl
|
||||
github "tadija/AEXML"
|
||||
```
|
||||
|
||||
- [CocoaPods](http://cocoapods.org/):
|
||||
|
||||
```ruby
|
||||
pod 'AEXML'
|
||||
```
|
||||
|
||||
## License
|
||||
AEXML is released under the MIT license. See [LICENSE](LICENSE) for details.
|
||||
Generated
-110
@@ -1,110 +0,0 @@
|
||||
/**
|
||||
* https://github.com/tadija/AEXML
|
||||
* Copyright © Marko Tadić 2014-2020
|
||||
* Licensed under the MIT license
|
||||
*/
|
||||
|
||||
import Foundation
|
||||
#if canImport(FoundationXML)
|
||||
import FoundationXML
|
||||
#endif
|
||||
|
||||
/**
|
||||
This class is inherited from `AEXMLElement` and has a few addons to represent **XML Document**.
|
||||
|
||||
XML Parsing is also done with this object.
|
||||
*/
|
||||
open class AEXMLDocument: AEXMLElement {
|
||||
|
||||
// MARK: - Properties
|
||||
|
||||
/// Root (the first child element) element of XML Document **(Empty element with error if not exists)**.
|
||||
open var root: AEXMLElement {
|
||||
guard let rootElement = children.first else {
|
||||
let errorElement = AEXMLElement(name: "Error")
|
||||
errorElement.error = AEXMLError.rootElementMissing
|
||||
return errorElement
|
||||
}
|
||||
return rootElement
|
||||
}
|
||||
|
||||
public let options: AEXMLOptions
|
||||
|
||||
// MARK: - Lifecycle
|
||||
|
||||
/**
|
||||
Designated initializer - Creates and returns new XML Document object.
|
||||
|
||||
- parameter root: Root XML element for XML Document (defaults to `nil`).
|
||||
- parameter options: Options for XML Document header and parser settings (defaults to `AEXMLOptions()`).
|
||||
|
||||
- returns: Initialized XML Document object.
|
||||
*/
|
||||
public init(root: AEXMLElement? = nil, options: AEXMLOptions = AEXMLOptions()) {
|
||||
self.options = options
|
||||
|
||||
let documentName = String(describing: AEXMLDocument.self)
|
||||
super.init(name: documentName)
|
||||
|
||||
// document has no parent element
|
||||
parent = nil
|
||||
|
||||
// add root element to document (if any)
|
||||
if let rootElement = root {
|
||||
addChild(rootElement)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
Convenience initializer - used for parsing XML data (by calling `loadXMLData:` internally).
|
||||
|
||||
- parameter xmlData: XML data to parse.
|
||||
- parameter options: Options for XML Document header and parser settings (defaults to `AEXMLOptions()`).
|
||||
|
||||
- returns: Initialized XML Document object containing parsed data. Throws error if data could not be parsed.
|
||||
*/
|
||||
public convenience init(xml: Data, options: AEXMLOptions = AEXMLOptions()) throws {
|
||||
self.init(options: options)
|
||||
try loadXML(xml)
|
||||
}
|
||||
|
||||
/**
|
||||
Convenience initializer - used for parsing XML string (by calling `init(xmlData:options:)` internally).
|
||||
|
||||
- parameter xmlString: XML string to parse.
|
||||
- parameter encoding: String encoding for creating `Data` from `xmlString` (defaults to `String.Encoding.utf8`)
|
||||
- parameter options: Options for XML Document header and parser settings (defaults to `AEXMLOptions()`).
|
||||
|
||||
- returns: Initialized XML Document object containing parsed data. Throws error if data could not be parsed.
|
||||
*/
|
||||
public convenience init(xml: String,
|
||||
encoding: String.Encoding = String.Encoding.utf8,
|
||||
options: AEXMLOptions = AEXMLOptions()) throws {
|
||||
guard let data = xml.data(using: encoding) else { throw AEXMLError.parsingFailed }
|
||||
try self.init(xml: data, options: options)
|
||||
}
|
||||
|
||||
// MARK: - Parse XML
|
||||
|
||||
/**
|
||||
Creates instance of `AEXMLParser` (private class which is simple wrapper around `XMLParser`)
|
||||
and starts parsing the given XML data. Throws error if data could not be parsed.
|
||||
|
||||
- parameter data: XML which should be parsed.
|
||||
*/
|
||||
open func loadXML(_ data: Data) throws {
|
||||
children.removeAll(keepingCapacity: false)
|
||||
let xmlParser = AEXMLParser(document: self, data: data)
|
||||
try xmlParser.parse()
|
||||
}
|
||||
|
||||
// MARK: - Override
|
||||
|
||||
/// Override of `xml` property of `AEXMLElement` - it just inserts XML Document header at the beginning.
|
||||
open override var xml: String {
|
||||
var xml = "\(options.documentHeader.xmlString)\n"
|
||||
xml += root.xml
|
||||
return xml
|
||||
}
|
||||
|
||||
}
|
||||
Generated
-351
@@ -1,351 +0,0 @@
|
||||
/**
|
||||
* https://github.com/tadija/AEXML
|
||||
* Copyright © Marko Tadić 2014-2020
|
||||
* Licensed under the MIT license
|
||||
*/
|
||||
|
||||
import Foundation
|
||||
#if canImport(FoundationXML)
|
||||
import FoundationXML
|
||||
#endif
|
||||
|
||||
/**
|
||||
This is base class for holding XML structure.
|
||||
|
||||
You can access its structure by using subscript like this: `element["foo"]["bar"]` which would
|
||||
return `<bar></bar>` element from `<element><foo><bar></bar></foo></element>` XML as an `AEXMLElement` object.
|
||||
*/
|
||||
open class AEXMLElement {
|
||||
|
||||
// MARK: - Properties
|
||||
|
||||
/// Every `AEXMLElement` should have its parent element instead of `AEXMLDocument` which parent is `nil`.
|
||||
open internal(set) weak var parent: AEXMLElement?
|
||||
|
||||
/// Child XML elements.
|
||||
open internal(set) var children = [AEXMLElement]()
|
||||
|
||||
/// XML Element name.
|
||||
open var name: String
|
||||
|
||||
/// XML Element value.
|
||||
open var value: String?
|
||||
|
||||
/// XML Element attributes.
|
||||
open var attributes: [String : String]
|
||||
|
||||
/// Error value (`nil` if there is no error).
|
||||
open var error: AEXMLError?
|
||||
|
||||
/// String representation of `value` property (if `value` is `nil` this is empty String).
|
||||
open var string: String { return value ?? String() }
|
||||
|
||||
/// Boolean representation of `value` property (`nil` if `value` can't be represented as Bool).
|
||||
open var bool: Bool? {
|
||||
switch string.lowercased() {
|
||||
case "true", "1":
|
||||
return true
|
||||
case "false", "0":
|
||||
return false
|
||||
default:
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
/// Integer representation of `value` property (`nil` if `value` can't be represented as Integer).
|
||||
open var int: Int? { return Int(string) }
|
||||
|
||||
/// Double representation of `value` property (`nil` if `value` can't be represented as Double).
|
||||
open var double: Double? { return Double(string) }
|
||||
|
||||
// MARK: - Init
|
||||
|
||||
/**
|
||||
Designated initializer - all parameters are optional.
|
||||
|
||||
- parameter name: XML element name.
|
||||
- parameter value: XML element value (defaults to `nil`).
|
||||
- parameter attributes: XML element attributes (defaults to empty dictionary).
|
||||
|
||||
- returns: An initialized `AEXMLElement` object.
|
||||
*/
|
||||
public init(name: String, value: String? = nil, attributes: [String : String] = [:]) {
|
||||
self.name = name
|
||||
self.value = value
|
||||
self.attributes = attributes
|
||||
}
|
||||
|
||||
// MARK: - XML Read
|
||||
|
||||
/// The first element with given name **(Empty element with error if not exists)**.
|
||||
open subscript(key: String) -> AEXMLElement {
|
||||
guard let
|
||||
first = children.first(where: { $0.name == key })
|
||||
else {
|
||||
let errorElement = AEXMLElement(name: key)
|
||||
errorElement.error = AEXMLError.elementNotFound
|
||||
return errorElement
|
||||
}
|
||||
return first
|
||||
}
|
||||
|
||||
/// Returns all of the elements with equal name as `self` **(nil if not exists)**.
|
||||
open var all: [AEXMLElement]? { return parent?.children.filter { $0.name == self.name } }
|
||||
|
||||
/// Returns the first element with equal name as `self` **(nil if not exists)**.
|
||||
open var first: AEXMLElement? { return all?.first }
|
||||
|
||||
/// Returns the last element with equal name as `self` **(nil if not exists)**.
|
||||
open var last: AEXMLElement? { return all?.last }
|
||||
|
||||
/// Returns number of all elements with equal name as `self`.
|
||||
open var count: Int { return all?.count ?? 0 }
|
||||
|
||||
/**
|
||||
Returns all elements with given value.
|
||||
|
||||
- parameter value: XML element value.
|
||||
|
||||
- returns: Optional Array of found XML elements.
|
||||
*/
|
||||
open func all(withValue value: String) -> [AEXMLElement]? {
|
||||
let found = all?.compactMap {
|
||||
$0.value == value ? $0 : nil
|
||||
}
|
||||
return found
|
||||
}
|
||||
|
||||
/**
|
||||
Returns all elements containing given attributes.
|
||||
|
||||
- parameter attributes: Array of attribute names.
|
||||
|
||||
- returns: Optional Array of found XML elements.
|
||||
*/
|
||||
open func all(containingAttributeKeys keys: [String]) -> [AEXMLElement]? {
|
||||
let found = all?.compactMap { element in
|
||||
keys.reduce(true) { (result, key) in
|
||||
result && Array(element.attributes.keys).contains(key)
|
||||
} ? element : nil
|
||||
}
|
||||
return found
|
||||
}
|
||||
|
||||
/**
|
||||
Returns all elements with given attributes.
|
||||
|
||||
- parameter attributes: Dictionary of Keys and Values of attributes.
|
||||
|
||||
- returns: Optional Array of found XML elements.
|
||||
*/
|
||||
open func all(withAttributes attributes: [String : String]) -> [AEXMLElement]? {
|
||||
let keys = Array(attributes.keys)
|
||||
let found = all(containingAttributeKeys: keys)?.compactMap { element in
|
||||
attributes.reduce(true) { (result, attribute) in
|
||||
result && element.attributes[attribute.key] == attribute.value
|
||||
} ? element : nil
|
||||
}
|
||||
return found
|
||||
}
|
||||
|
||||
/**
|
||||
Returns all descendant elements which satisfy the given predicate.
|
||||
|
||||
Searching is done vertically; children are tested before siblings. Elements appear in the list
|
||||
in the order in which they are found.
|
||||
|
||||
- parameter predicate: Function which returns `true` for a desired element and `false` otherwise.
|
||||
|
||||
- returns: Array of found XML elements.
|
||||
*/
|
||||
open func allDescendants(where predicate: (AEXMLElement) -> Bool) -> [AEXMLElement] {
|
||||
var result: [AEXMLElement] = []
|
||||
|
||||
for child in children {
|
||||
if predicate(child) {
|
||||
result.append(child)
|
||||
}
|
||||
result.append(contentsOf: child.allDescendants(where: predicate))
|
||||
}
|
||||
|
||||
return result
|
||||
}
|
||||
|
||||
/**
|
||||
Returns the first descendant element which satisfies the given predicate, or nil if no such element is found.
|
||||
|
||||
Searching is done vertically; children are tested before siblings.
|
||||
|
||||
- parameter predicate: Function which returns `true` for the desired element and `false` otherwise.
|
||||
|
||||
- returns: Optional AEXMLElement.
|
||||
*/
|
||||
open func firstDescendant(where predicate: (AEXMLElement) -> Bool) -> AEXMLElement? {
|
||||
for child in children {
|
||||
if predicate(child) {
|
||||
return child
|
||||
} else if let descendant = child.firstDescendant(where: predicate) {
|
||||
return descendant
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
/**
|
||||
Indicates whether the element has a descendant satisfying the given predicate.
|
||||
|
||||
- parameter predicate: Function which returns `true` for the desired element and `false` otherwise.
|
||||
|
||||
- returns: Bool.
|
||||
*/
|
||||
open func hasDescendant(where predicate: (AEXMLElement) -> Bool) -> Bool {
|
||||
return firstDescendant(where: predicate) != nil
|
||||
}
|
||||
|
||||
// MARK: - XML Write
|
||||
|
||||
/**
|
||||
Adds child XML element to `self`.
|
||||
|
||||
- parameter child: Child XML element to add.
|
||||
|
||||
- returns: Child XML element with `self` as `parent`.
|
||||
*/
|
||||
@discardableResult
|
||||
open func addChild(_ child: AEXMLElement) -> AEXMLElement {
|
||||
child.parent = self
|
||||
children.append(child)
|
||||
return child
|
||||
}
|
||||
|
||||
/**
|
||||
Adds child XML element to `self`.
|
||||
|
||||
- parameter name: Child XML element name.
|
||||
- parameter value: Child XML element value (defaults to `nil`).
|
||||
- parameter attributes: Child XML element attributes (defaults to empty dictionary).
|
||||
|
||||
- returns: Child XML element with `self` as `parent`.
|
||||
*/
|
||||
@discardableResult
|
||||
open func addChild(name: String,
|
||||
value: String? = nil,
|
||||
attributes: [String : String] = [:]) -> AEXMLElement {
|
||||
let child = AEXMLElement(name: name, value: value, attributes: attributes)
|
||||
return addChild(child)
|
||||
}
|
||||
|
||||
/**
|
||||
Adds an array of XML elements to `self`.
|
||||
|
||||
- parameter children: Child XML element array to add.
|
||||
|
||||
- returns: Child XML elements with `self` as `parent`.
|
||||
*/
|
||||
@discardableResult
|
||||
open func addChildren(_ children: [AEXMLElement]) -> [AEXMLElement] {
|
||||
children.forEach{ addChild($0) }
|
||||
return children
|
||||
}
|
||||
|
||||
/// Removes `self` from `parent` XML element.
|
||||
open func removeFromParent() {
|
||||
if let index = parent?.children.firstIndex(where: { $0 === self }) {
|
||||
parent?.children.remove(at: index)
|
||||
}
|
||||
}
|
||||
|
||||
/// Complete hierarchy of `self` and `children` in **XML** escaped and formatted String
|
||||
open var xml: String {
|
||||
var xml = String()
|
||||
|
||||
// open element
|
||||
xml += indent(withDepth: parentsCount - 1)
|
||||
xml += "<\(name)"
|
||||
|
||||
if attributes.count > 0 {
|
||||
// insert attributes
|
||||
for (key, value) in attributes.sorted(by: { $0.key < $1.key }) {
|
||||
xml += " \(key)=\"\(value.xmlEscaped)\""
|
||||
}
|
||||
}
|
||||
|
||||
if value == nil && children.count == 0 {
|
||||
// close element
|
||||
xml += " />"
|
||||
} else {
|
||||
if children.count > 0 {
|
||||
// add children
|
||||
xml += ">\n"
|
||||
for child in children {
|
||||
xml += "\(child.xml)\n"
|
||||
}
|
||||
// add indentation
|
||||
xml += indent(withDepth: parentsCount - 1)
|
||||
xml += "</\(name)>"
|
||||
} else {
|
||||
// insert string value and close element
|
||||
xml += ">\(string.xmlEscaped)</\(name)>"
|
||||
}
|
||||
}
|
||||
|
||||
return xml
|
||||
}
|
||||
|
||||
/// Same as `xmlString` but without `\n` and `\t` characters
|
||||
open var xmlCompact: String {
|
||||
let chars = CharacterSet(charactersIn: "\n\t")
|
||||
return xml.components(separatedBy: chars).joined(separator: "")
|
||||
}
|
||||
|
||||
/// Same as `xmlString` but with 4 spaces instead '\t' characters
|
||||
open var xmlSpaces: String {
|
||||
let chars = CharacterSet(charactersIn: "\t")
|
||||
return xml.components(separatedBy: chars).joined(separator: " ")
|
||||
}
|
||||
|
||||
// MARK: - Helpers
|
||||
|
||||
private var parentsCount: Int {
|
||||
var count = 0
|
||||
var element = self
|
||||
|
||||
while let parent = element.parent {
|
||||
count += 1
|
||||
element = parent
|
||||
}
|
||||
|
||||
return count
|
||||
}
|
||||
|
||||
private func indent(withDepth depth: Int) -> String {
|
||||
var count = depth
|
||||
var indent = String()
|
||||
|
||||
while count > 0 {
|
||||
indent += "\t"
|
||||
count -= 1
|
||||
}
|
||||
|
||||
return indent
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public extension String {
|
||||
|
||||
/// String representation of self with XML special characters escaped.
|
||||
var xmlEscaped: String {
|
||||
// we need to make sure "&" is escaped first. Not doing this may break escaping the other characters
|
||||
var escaped = replacingOccurrences(of: "&", with: "&", options: .literal)
|
||||
|
||||
// replace the other four special characters
|
||||
let escapeChars = ["<" : "<", ">" : ">", "'" : "'", "\"" : """]
|
||||
for (char, echar) in escapeChars {
|
||||
escaped = escaped.replacingOccurrences(of: char, with: echar, options: .literal)
|
||||
}
|
||||
|
||||
return escaped
|
||||
}
|
||||
|
||||
}
|
||||
Generated
-22
@@ -1,22 +0,0 @@
|
||||
/**
|
||||
* https://github.com/tadija/AEXML
|
||||
* Copyright © Marko Tadić 2014-2020
|
||||
* Licensed under the MIT license
|
||||
*/
|
||||
|
||||
import Foundation
|
||||
#if canImport(FoundationXML)
|
||||
import FoundationXML
|
||||
#endif
|
||||
|
||||
/// A type representing error value that can be thrown or inside `error` property of `AEXMLElement`.
|
||||
public enum AEXMLError: Error {
|
||||
/// This will be inside `error` property of `AEXMLElement` when subscript is used for not-existing element.
|
||||
case elementNotFound
|
||||
|
||||
/// This will be inside `error` property of `AEXMLDocument` when there is no root element.
|
||||
case rootElementMissing
|
||||
|
||||
/// `AEXMLDocument` can throw this error on `init` or `loadXMLData` if parsing with `XMLParser` was not successful.
|
||||
case parsingFailed
|
||||
}
|
||||
Generated
-57
@@ -1,57 +0,0 @@
|
||||
/**
|
||||
* https://github.com/tadija/AEXML
|
||||
* Copyright © Marko Tadić 2014-2020
|
||||
* Licensed under the MIT license
|
||||
*/
|
||||
|
||||
import Foundation
|
||||
#if canImport(FoundationXML)
|
||||
import FoundationXML
|
||||
#endif
|
||||
|
||||
|
||||
/// Options used in `AEXMLDocument`
|
||||
public struct AEXMLOptions {
|
||||
|
||||
/// Values used in XML Document header
|
||||
public struct DocumentHeader {
|
||||
/// Version value for XML Document header (defaults to 1.0).
|
||||
public var version = 1.0
|
||||
|
||||
/// Encoding value for XML Document header (defaults to "utf-8").
|
||||
public var encoding = "utf-8"
|
||||
|
||||
/// Standalone value for XML Document header (defaults to "no").
|
||||
public var standalone = "no"
|
||||
|
||||
/// XML Document header
|
||||
public var xmlString: String {
|
||||
return "<?xml version=\"\(version)\" encoding=\"\(encoding)\" standalone=\"\(standalone)\"?>"
|
||||
}
|
||||
}
|
||||
|
||||
/// Settings used by `Foundation.XMLParser`
|
||||
public struct ParserSettings {
|
||||
/// Parser reports the namespaces and qualified names of elements. (defaults to `false`)
|
||||
public var shouldProcessNamespaces = false
|
||||
|
||||
/// Parser reports the prefixes indicating the scope of namespace declarations. (defaults to `false`)
|
||||
public var shouldReportNamespacePrefixes = false
|
||||
|
||||
/// Parser reports declarations of external entities. (defaults to `false`)
|
||||
public var shouldResolveExternalEntities = false
|
||||
|
||||
/// Parser should trim whitespace from text nodes. (defaults to `true`)
|
||||
public var shouldTrimWhitespace = true
|
||||
}
|
||||
|
||||
/// Values used in XML Document header (defaults to `DocumentHeader()`)
|
||||
public var documentHeader = DocumentHeader()
|
||||
|
||||
/// Settings used by `Foundation.XMLParser` (defaults to `ParserSettings()`)
|
||||
public var parserSettings = ParserSettings()
|
||||
|
||||
/// Designated initializer - Creates and returns default `AEXMLOptions`.
|
||||
public init() {}
|
||||
|
||||
}
|
||||
Generated
-91
@@ -1,91 +0,0 @@
|
||||
/**
|
||||
* https://github.com/tadija/AEXML
|
||||
* Copyright © Marko Tadić 2014-2020
|
||||
* Licensed under the MIT license
|
||||
*/
|
||||
|
||||
import Foundation
|
||||
#if canImport(FoundationXML)
|
||||
import FoundationXML
|
||||
#endif
|
||||
|
||||
/// Simple wrapper around `Foundation.XMLParser`.
|
||||
internal class AEXMLParser: NSObject, XMLParserDelegate {
|
||||
|
||||
// MARK: - Properties
|
||||
|
||||
let document: AEXMLDocument
|
||||
let data: Data
|
||||
|
||||
var currentParent: AEXMLElement?
|
||||
var currentElement: AEXMLElement?
|
||||
var currentValue = String()
|
||||
|
||||
var parseError: Error?
|
||||
|
||||
private lazy var parserSettings: AEXMLOptions.ParserSettings = {
|
||||
return document.options.parserSettings
|
||||
}()
|
||||
|
||||
// MARK: - Lifecycle
|
||||
|
||||
init(document: AEXMLDocument, data: Data) {
|
||||
self.document = document
|
||||
self.data = data
|
||||
currentParent = document
|
||||
|
||||
super.init()
|
||||
}
|
||||
|
||||
// MARK: - API
|
||||
|
||||
func parse() throws {
|
||||
let parser = XMLParser(data: data)
|
||||
parser.delegate = self
|
||||
|
||||
parser.shouldProcessNamespaces = parserSettings.shouldProcessNamespaces
|
||||
parser.shouldReportNamespacePrefixes = parserSettings.shouldReportNamespacePrefixes
|
||||
parser.shouldResolveExternalEntities = parserSettings.shouldResolveExternalEntities
|
||||
|
||||
let success = parser.parse()
|
||||
|
||||
if !success {
|
||||
guard let error = parseError else { throw AEXMLError.parsingFailed }
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - XMLParserDelegate
|
||||
|
||||
func parser(_ parser: XMLParser,
|
||||
didStartElement elementName: String,
|
||||
namespaceURI: String?,
|
||||
qualifiedName qName: String?,
|
||||
attributes attributeDict: [String : String]) {
|
||||
currentValue = String()
|
||||
currentElement = currentParent?.addChild(name: elementName, attributes: attributeDict)
|
||||
currentParent = currentElement
|
||||
}
|
||||
|
||||
func parser(_ parser: XMLParser, foundCharacters string: String) {
|
||||
currentValue.append(string)
|
||||
currentElement?.value = currentValue.isEmpty ? nil : currentValue
|
||||
}
|
||||
|
||||
func parser(_ parser: XMLParser,
|
||||
didEndElement elementName: String,
|
||||
namespaceURI: String?,
|
||||
qualifiedName qName: String?) {
|
||||
if parserSettings.shouldTrimWhitespace {
|
||||
currentElement?.value = currentElement?.value?
|
||||
.trimmingCharacters(in: .whitespacesAndNewlines)
|
||||
}
|
||||
currentParent = currentParent?.parent
|
||||
currentElement = nil
|
||||
}
|
||||
|
||||
func parser(_ parser: XMLParser, parseErrorOccurred parseError: Error) {
|
||||
self.parseError = parseError
|
||||
}
|
||||
|
||||
}
|
||||
Generated
-27
@@ -1,27 +0,0 @@
|
||||
Copyright (c) 2015, Kyle Fuller
|
||||
All rights reserved.
|
||||
|
||||
Redistribution and use in source and binary forms, with or without
|
||||
modification, are permitted provided that the following conditions are met:
|
||||
|
||||
* Redistributions of source code must retain the above copyright notice, this
|
||||
list of conditions and the following disclaimer.
|
||||
|
||||
* Redistributions in binary form must reproduce the above copyright notice,
|
||||
this list of conditions and the following disclaimer in the documentation
|
||||
and/or other materials provided with the distribution.
|
||||
|
||||
* Neither the name of the copyright holder nor the names of its
|
||||
contributors may be used to endorse or promote products derived from
|
||||
this software without specific prior written permission
|
||||
|
||||
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
|
||||
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
|
||||
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
|
||||
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
|
||||
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
|
||||
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
|
||||
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
|
||||
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
|
||||
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
Generated
-244
@@ -1,244 +0,0 @@
|
||||
<img src="Commander.png" width=80 height=83 alt="Commander" />
|
||||
|
||||
# Commander
|
||||
|
||||
[](https://travis-ci.org/kylef/Commander)
|
||||
|
||||
Commander is a small Swift framework allowing you to craft beautiful command
|
||||
line interfaces in a composable way.
|
||||
|
||||
## Usage
|
||||
|
||||
##### Simple Hello World
|
||||
|
||||
```swift
|
||||
import Commander
|
||||
|
||||
let main = command { (filename:String) in
|
||||
print("Reading file \(filename)...")
|
||||
}
|
||||
|
||||
main.run()
|
||||
```
|
||||
|
||||
##### Type-safe argument handling
|
||||
|
||||
The closure passed to the command function takes any arguments that
|
||||
conform to `ArgumentConvertible`, Commander will automatically convert the
|
||||
arguments to these types. If they can't be converted the user will receive a
|
||||
nice error message informing them that their argument doesn't match the
|
||||
expected type.
|
||||
|
||||
`String`, `Int`, `Double`, and `Float` are extended to conform to
|
||||
`ArgumentConvertible`, you can easily extend any other class or structure
|
||||
so you can use it as an argument to your command.
|
||||
|
||||
```swift
|
||||
command { (hostname:String, port:Int) in
|
||||
print("Connecting to \(hostname) on port \(port)...")
|
||||
}
|
||||
```
|
||||
|
||||
##### Grouping commands
|
||||
|
||||
You can group a collection of commands together.
|
||||
|
||||
```swift
|
||||
Group {
|
||||
$0.command("login") { (name:String) in
|
||||
print("Hello \(name)")
|
||||
}
|
||||
|
||||
$0.command("logout") {
|
||||
print("Goodbye.")
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Usage:
|
||||
|
||||
```shell
|
||||
$ auth
|
||||
Usage:
|
||||
|
||||
$ auth COMMAND
|
||||
|
||||
Commands:
|
||||
|
||||
+ login
|
||||
+ logout
|
||||
|
||||
$ auth login Kyle
|
||||
Hello Kyle
|
||||
$ auth logout
|
||||
Goodbye.
|
||||
```
|
||||
|
||||
#### Describing arguments
|
||||
|
||||
You can describe positional arguments and options for a command to auto-generate help.
|
||||
This is done by passing in descriptors of these arguments.
|
||||
|
||||
For example, for fixed positional arguments with descriptions, you can use:
|
||||
|
||||
```swift
|
||||
command(
|
||||
Argument<String>("name", description: "Your name"),
|
||||
Argument<String>("surname", description: "Your surname"),
|
||||
Argument<Int>("count", description: "Number of times to print")
|
||||
) { name, surname, count in
|
||||
for _ in 0..<count {
|
||||
print("Hello \(name) \(surname)")
|
||||
}
|
||||
}.run()
|
||||
```
|
||||
|
||||
Keep in mind you have to pass 3 required arguments.
|
||||
|
||||
Another example, to describe a command which takes two (optional) options, `--name` and
|
||||
`--count` where the default value for name is `world` and the default value for
|
||||
count is `1`.
|
||||
|
||||
```swift
|
||||
command(
|
||||
Option("name", default: "world"),
|
||||
Option("count", default: 1, description: "The number of times to print.")
|
||||
) { name, count in
|
||||
for _ in 0..<count {
|
||||
print("Hello \(name)")
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
```shell
|
||||
$ hello --help
|
||||
Usage:
|
||||
|
||||
$ hello
|
||||
|
||||
Options:
|
||||
--name
|
||||
--count - The number of times to print.
|
||||
|
||||
$ hello
|
||||
Hello world
|
||||
|
||||
$ hello --name Kyle
|
||||
Hello Kyle
|
||||
|
||||
$ hello --name Kyle --count 4
|
||||
Hello Kyle
|
||||
Hello Kyle
|
||||
Hello Kyle
|
||||
Hello Kyle
|
||||
```
|
||||
|
||||
##### Types of descriptors
|
||||
|
||||
- Option - An optional option with a value.
|
||||
- Options - A option with a value which can be used multiple times, your command is passed an array containing all option values. You need to specify ahead of time how many values you expect. Example: `--myOption value1 value2 value3`
|
||||
- VariadicOption - Same as options, but instead of a fixed `count` of values, the user can just repeat the option with additional values. Example: `--myOption value1 --myOption value2`
|
||||
- Flag - A boolean, on/off flag.
|
||||
- Argument - A positional argument.
|
||||
- VariadicArgument - A variadic argument
|
||||
|
||||
**NOTE**: *It's important to describe your arguments after options and flags so the parser can differentiate between `--option value` and `--flag argument`.*
|
||||
|
||||
#### Using the argument parser
|
||||
|
||||
**NOTE**: *`ArgumentParser` itself is `ArgumentConvertible` so you can also
|
||||
get hold of the raw argument parser to perform any custom parsing.*
|
||||
|
||||
```swift
|
||||
command { (name:String, parser:ArgumentParser) in
|
||||
if parser.hasOption("verbose") {
|
||||
print("Verbose mode enabled")
|
||||
}
|
||||
|
||||
print("Hello \(name)")
|
||||
}
|
||||
```
|
||||
|
||||
```shell
|
||||
$ tool Kyle --verbose
|
||||
Verbose mode enabled
|
||||
Hello Kyle
|
||||
```
|
||||
|
||||
### Examples tools using Commander
|
||||
|
||||
- [QueryKit](https://github.com/QueryKit/querykit-cli) via CocoaPods Rome
|
||||
|
||||
## Installation
|
||||
|
||||
You can install Commander in many ways, with SPM (Swift Package Manager), [Conche](https://github.com/Conche/Conche), CocoaPods or [CocoaPods-Rome](https://github.com/neonichu/Rome).
|
||||
|
||||
### Frameworks and `rpath`
|
||||
|
||||
It's important to note that the `.framework` or dynamic library file for
|
||||
Commander (and any other dependency) must be available at run-time for your
|
||||
command line tool. Unless you are using SPM.
|
||||
|
||||
Applications will look in their `rpath` which contains paths of where it expects
|
||||
the `.framework`s to be found at.
|
||||
|
||||
Using a Swift script, you can use the `-F` flag for setting framework search
|
||||
paths, as follows:
|
||||
|
||||
```swift
|
||||
#!/usr/bin/env xcrun swift -F Rome
|
||||
|
||||
import Commander
|
||||
```
|
||||
|
||||
For compiled Swift code, you will need to add an rpath pointing to your
|
||||
dependency frameworks, as follows:
|
||||
|
||||
```shell
|
||||
$ install_name_tool -add_rpath "@executable_path/../Frameworks/" "bin/querykit"
|
||||
```
|
||||
|
||||
Where "../Frameworks" relative to the executable path is used to find the
|
||||
frameworks and `bin/querykit` is the executable.
|
||||
|
||||
When installing your executable on other systems it's important to copy the
|
||||
frameworks and the binary.
|
||||
|
||||
### Architecture
|
||||
|
||||
##### `CommandType`
|
||||
|
||||
`CommandType` is the core protocol behind commands, it's an object or
|
||||
structure that has a `run` method which takes an `ArgumentParser`.
|
||||
|
||||
Both the `command` functions and `Group` return a command that conforms to
|
||||
`CommandType` which can easily be interchanged.
|
||||
|
||||
```swift
|
||||
protocol CommandType {
|
||||
func run(parser:ArgumentParser) throws
|
||||
}
|
||||
```
|
||||
|
||||
##### `ArgumentConvertible`
|
||||
|
||||
The convenience `command` function takes a closure for your command that
|
||||
takes arguments which conform to the `ArgumentConvertible` protocol. This
|
||||
allows Commander to easily convert arguments to the types you would like
|
||||
to use for your command.
|
||||
|
||||
```swift
|
||||
protocol ArgumentConvertible {
|
||||
init(parser: ArgumentParser) throws
|
||||
}
|
||||
```
|
||||
|
||||
##### `ArgumentParser`
|
||||
|
||||
The `ArgumentParser` is an object that allowing you to pull out options,
|
||||
flags and positional arguments.
|
||||
|
||||
## License
|
||||
|
||||
Commander is available under the BSD license. See the [LICENSE file](LICENSE)
|
||||
for more info.
|
||||
@@ -1,149 +0,0 @@
|
||||
public enum ArgumentError : Error, Equatable, CustomStringConvertible {
|
||||
case missingValue(argument: String?)
|
||||
|
||||
/// Value is not convertible to type
|
||||
case invalidType(value:String, type:String, argument:String?)
|
||||
|
||||
/// Unused Argument
|
||||
case unusedArgument(String)
|
||||
|
||||
public var description:String {
|
||||
switch self {
|
||||
case .missingValue(let key):
|
||||
if let key = key {
|
||||
return "Missing value for `\(key)`"
|
||||
}
|
||||
return "Missing argument"
|
||||
case .invalidType(let value, let type, let argument):
|
||||
if let argument = argument {
|
||||
return "`\(value)` is not a valid `\(type)` for `\(argument)`"
|
||||
}
|
||||
return "`\(value)` is not a `\(type)`"
|
||||
case .unusedArgument(let argument):
|
||||
return "Unexpected argument `\(argument)`"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
public func == (lhs: ArgumentError, rhs: ArgumentError) -> Bool {
|
||||
switch (lhs, rhs) {
|
||||
case let (.missingValue(lhsKey), .missingValue(rhsKey)):
|
||||
return lhsKey == rhsKey
|
||||
case let (.invalidType(lhsValue, lhsType, lhsArgument), .invalidType(rhsValue, rhsType, rhsArgument)):
|
||||
return lhsValue == rhsValue && lhsType == rhsType && lhsArgument == rhsArgument
|
||||
case let (.unusedArgument(lhsArgument), .unusedArgument(rhsArgument)):
|
||||
return lhsArgument == rhsArgument
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
public protocol ArgumentConvertible : CustomStringConvertible {
|
||||
/// Initialise the type with an ArgumentParser
|
||||
init(parser: ArgumentParser) throws
|
||||
}
|
||||
|
||||
extension String : ArgumentConvertible {
|
||||
public init(parser: ArgumentParser) throws {
|
||||
if let value = parser.shift() {
|
||||
self.init(value)
|
||||
} else {
|
||||
throw ArgumentError.missingValue(argument: nil)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension Int : ArgumentConvertible {
|
||||
public init(parser: ArgumentParser) throws {
|
||||
if let value = parser.shift() {
|
||||
if let value = Int(value) {
|
||||
self.init(value)
|
||||
} else {
|
||||
throw ArgumentError.invalidType(value: value, type: "number", argument: nil)
|
||||
}
|
||||
} else {
|
||||
throw ArgumentError.missingValue(argument: nil)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
extension Float : ArgumentConvertible {
|
||||
public init(parser: ArgumentParser) throws {
|
||||
if let value = parser.shift() {
|
||||
if let value = Float(value) {
|
||||
self.init(value)
|
||||
} else {
|
||||
throw ArgumentError.invalidType(value: value, type: "number", argument: nil)
|
||||
}
|
||||
} else {
|
||||
throw ArgumentError.missingValue(argument: nil)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
extension Double : ArgumentConvertible {
|
||||
public init(parser: ArgumentParser) throws {
|
||||
if let value = parser.shift() {
|
||||
if let value = Double(value) {
|
||||
self.init(value)
|
||||
} else {
|
||||
throw ArgumentError.invalidType(value: value, type: "number", argument: nil)
|
||||
}
|
||||
} else {
|
||||
throw ArgumentError.missingValue(argument: nil)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
extension Array where Element : ArgumentConvertible {
|
||||
public init(parser: ArgumentParser) throws {
|
||||
var temp = [Element]()
|
||||
|
||||
while true {
|
||||
do {
|
||||
temp.append(try Element(parser: parser))
|
||||
} catch ArgumentError.missingValue {
|
||||
break
|
||||
} catch {
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
self.init(temp)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
extension Optional where Wrapped : ArgumentConvertible {
|
||||
public init(parser: ArgumentParser) throws {
|
||||
do {
|
||||
self = .some(try Wrapped(parser: parser))
|
||||
} catch ArgumentError.missingValue {
|
||||
self = .none
|
||||
} catch {
|
||||
throw error
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
extension Optional where Wrapped : CustomStringConvertible {
|
||||
public var description: String {
|
||||
switch self {
|
||||
case .some(let value):
|
||||
return value.description
|
||||
case .none:
|
||||
return ""
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
extension Array : ArgumentConvertible where Element : ArgumentConvertible {}
|
||||
extension Optional : ArgumentConvertible where Wrapped : ArgumentConvertible {}
|
||||
extension Optional : CustomStringConvertible where Wrapped : CustomStringConvertible {}
|
||||
@@ -1,477 +0,0 @@
|
||||
public enum ArgumentType {
|
||||
case argument
|
||||
case option
|
||||
}
|
||||
|
||||
|
||||
public protocol ArgumentDescriptor {
|
||||
associatedtype ValueType
|
||||
|
||||
/// The arguments name
|
||||
var name: String { get }
|
||||
|
||||
/// The arguments description
|
||||
var description: String? { get }
|
||||
|
||||
var type: ArgumentType { get }
|
||||
|
||||
/// Parse the argument
|
||||
func parse(_ parser: ArgumentParser) throws -> ValueType
|
||||
}
|
||||
|
||||
|
||||
extension ArgumentConvertible {
|
||||
init(string: String) throws {
|
||||
try self.init(parser: ArgumentParser(arguments: [string]))
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@available(*, deprecated, message: "use array as an ArgumentConvertible")
|
||||
public class VariadicArgument<T : ArgumentConvertible> : ArgumentDescriptor {
|
||||
public typealias ValueType = [T]
|
||||
public typealias Validator = (ValueType) throws -> ValueType
|
||||
|
||||
public let name: String
|
||||
public let description: String?
|
||||
public let validator: Validator?
|
||||
public var type: ArgumentType { return .argument }
|
||||
|
||||
public init(_ name: String, description: String? = nil, validator: Validator? = nil) {
|
||||
self.name = name
|
||||
self.description = description
|
||||
self.validator = validator
|
||||
}
|
||||
|
||||
public func parse(_ parser: ArgumentParser) throws -> ValueType {
|
||||
let value = try Array<T>(parser: parser)
|
||||
|
||||
if let validator = validator {
|
||||
return try validator(value)
|
||||
}
|
||||
|
||||
return value
|
||||
}
|
||||
}
|
||||
|
||||
@available(*, deprecated, message: "use VariadicArgument instead")
|
||||
typealias VaradicArgument<T : ArgumentConvertible> = VariadicArgument<T>
|
||||
|
||||
|
||||
public class Argument<T : ArgumentConvertible> : ArgumentDescriptor {
|
||||
public typealias ValueType = T
|
||||
public typealias Validator = (ValueType) throws -> ValueType
|
||||
|
||||
public let name: String
|
||||
public let description: String?
|
||||
public let validator: Validator?
|
||||
public var type: ArgumentType { return .argument }
|
||||
|
||||
public init(_ name: String, description: String? = nil, validator: Validator? = nil) {
|
||||
self.name = name
|
||||
self.description = description
|
||||
self.validator = validator
|
||||
}
|
||||
|
||||
public func parse(_ parser: ArgumentParser) throws -> ValueType {
|
||||
let value: T
|
||||
|
||||
do {
|
||||
value = try T(parser: parser)
|
||||
} catch ArgumentError.missingValue {
|
||||
throw ArgumentError.missingValue(argument: name)
|
||||
} catch {
|
||||
throw error
|
||||
}
|
||||
|
||||
if let validator = validator {
|
||||
return try validator(value)
|
||||
}
|
||||
|
||||
return value
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
public class Option<T : ArgumentConvertible> : ArgumentDescriptor {
|
||||
public typealias ValueType = T
|
||||
public typealias Validator = (ValueType) throws -> ValueType
|
||||
|
||||
public let name: String
|
||||
public let `default`: ValueType
|
||||
public let flag: Character?
|
||||
public let description: String?
|
||||
public let validator: Validator?
|
||||
public var type: ArgumentType { return .option }
|
||||
|
||||
public init(_ name: String, default: ValueType, flag: Character? = nil, description: String? = nil, validator: Validator? = nil) {
|
||||
self.name = name
|
||||
self.`default` = `default`
|
||||
self.flag = flag
|
||||
self.description = description
|
||||
self.validator = validator
|
||||
}
|
||||
|
||||
@available(*, deprecated, message: "use init(_:default:flag:description:validator:) instead")
|
||||
public convenience init(_ name: String, _ default: ValueType, flag: Character? = nil, description: String? = nil, validator: Validator? = nil) {
|
||||
self.init(name, default: `default`, flag: flag, description: description, validator: validator)
|
||||
}
|
||||
|
||||
public func parse(_ parser: ArgumentParser) throws -> ValueType {
|
||||
guard let shifted = try parser.shiftValue(for: name, or: flag) else { return `default` }
|
||||
let value = try T(string: shifted)
|
||||
|
||||
if let validator = validator {
|
||||
return try validator(value)
|
||||
}
|
||||
|
||||
return value
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
public class Options<T : ArgumentConvertible> : ArgumentDescriptor {
|
||||
public typealias ValueType = [T]
|
||||
public typealias Validator = (ValueType) throws -> ValueType
|
||||
|
||||
public let name: String
|
||||
public let `default`: ValueType
|
||||
public let flag: Character?
|
||||
public let count: Int
|
||||
public let description: String?
|
||||
public let validator: Validator?
|
||||
public var type: ArgumentType { return .option }
|
||||
|
||||
public init(_ name: String, default: ValueType, flag: Character? = nil, count: Int, description: String? = nil, validator: Validator? = nil) {
|
||||
self.name = name
|
||||
self.`default` = `default`
|
||||
self.flag = flag
|
||||
self.count = count
|
||||
self.description = description
|
||||
self.validator = validator
|
||||
}
|
||||
|
||||
@available(*, deprecated, message: "use init(_:default:flag:count:description:validator:) instead")
|
||||
public convenience init(_ name: String, _ default: ValueType, flag: Character? = nil, count: Int, description: String? = nil, validator: Validator? = nil) {
|
||||
self.init(name, default: `default`, flag: flag, count: count, description: description, validator: validator)
|
||||
}
|
||||
|
||||
public func parse(_ parser: ArgumentParser) throws -> ValueType {
|
||||
guard let shifted = try parser.shiftValues(for: name, or: flag, count: count) else { return `default` }
|
||||
let values = try shifted.map { try T(string: $0) }
|
||||
|
||||
if let validator = validator {
|
||||
return try validator(values)
|
||||
}
|
||||
|
||||
return values
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
public class VariadicOption<T : ArgumentConvertible> : ArgumentDescriptor {
|
||||
public typealias ValueType = [T]
|
||||
public typealias Validator = (ValueType) throws -> ValueType
|
||||
|
||||
public let name: String
|
||||
public let `default`: ValueType
|
||||
public let flag: Character?
|
||||
public let description: String?
|
||||
public let validator: Validator?
|
||||
public var type: ArgumentType { return .option }
|
||||
|
||||
public init(_ name: String, default: ValueType = [], flag: Character? = nil, description: String? = nil, validator: Validator? = nil) {
|
||||
self.name = name
|
||||
self.`default` = `default`
|
||||
self.flag = flag
|
||||
self.description = description
|
||||
self.validator = validator
|
||||
}
|
||||
|
||||
@available(*, deprecated, message: "use init(_:default:flag:description:validator:) instead")
|
||||
public convenience init(_ name: String, _ default: ValueType, flag: Character? = nil, description: String? = nil, validator: Validator? = nil) {
|
||||
self.init(name, default: `default`, flag: flag, description: description, validator: validator)
|
||||
}
|
||||
|
||||
public func parse(_ parser: ArgumentParser) throws -> ValueType {
|
||||
var values: ValueType? = nil
|
||||
|
||||
while let shifted = try parser.shiftValue(for: name, or: flag) {
|
||||
let argument = try T(string: shifted)
|
||||
|
||||
if values == nil {
|
||||
values = ValueType()
|
||||
}
|
||||
values?.append(argument)
|
||||
}
|
||||
|
||||
if let validator = validator, let values = values {
|
||||
return try validator(values)
|
||||
}
|
||||
|
||||
return values ?? `default`
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
public class Flag : ArgumentDescriptor {
|
||||
public typealias ValueType = Bool
|
||||
|
||||
public let name: String
|
||||
public let `default`: ValueType
|
||||
public let flag: Character?
|
||||
public let disabledName: String
|
||||
public let disabledFlag: Character?
|
||||
public let description: String?
|
||||
public var type: ArgumentType { return .option }
|
||||
|
||||
public init(_ name: String, default: Bool = false, flag: Character? = nil, disabledName: String? = nil, disabledFlag: Character? = nil, description: String? = nil) {
|
||||
self.name = name
|
||||
self.`default` = `default`
|
||||
self.disabledName = disabledName ?? "no-\(name)"
|
||||
self.flag = flag
|
||||
self.disabledFlag = disabledFlag
|
||||
self.description = description
|
||||
}
|
||||
|
||||
@available(*, deprecated, message: "use init(_:default:flag:disabledName:disabledFlag:description:) instead")
|
||||
public convenience init(_ name: String, _ default: ValueType, flag: Character? = nil, disabledName: String? = nil, disabledFlag: Character? = nil, description: String? = nil) {
|
||||
self.init(name, default: `default`, flag: flag, disabledName: disabledName, disabledFlag: disabledFlag, description: description)
|
||||
}
|
||||
|
||||
public func parse(_ parser: ArgumentParser) throws -> ValueType {
|
||||
if parser.hasOption(disabledName) {
|
||||
return false
|
||||
}
|
||||
|
||||
if parser.hasOption(name) {
|
||||
return true
|
||||
}
|
||||
|
||||
if let flag = flag {
|
||||
if parser.hasFlag(flag) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
if let disabledFlag = disabledFlag {
|
||||
if parser.hasFlag(disabledFlag) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
return `default`
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
class BoxedArgumentDescriptor {
|
||||
let name: String
|
||||
let description: String?
|
||||
let `default`: String?
|
||||
let type: ArgumentType
|
||||
let flag: Character?
|
||||
|
||||
var summary: String {
|
||||
var line = ""
|
||||
|
||||
switch type {
|
||||
case .argument:
|
||||
line += "\(name)"
|
||||
case .option:
|
||||
if let flag = flag {
|
||||
line += "-\(flag), "
|
||||
}
|
||||
line += "--\(name)"
|
||||
}
|
||||
|
||||
if let `default` = `default` {
|
||||
line += " [default: \(`default`)]"
|
||||
}
|
||||
|
||||
if let description = description {
|
||||
line += " - \(description)"
|
||||
}
|
||||
|
||||
return line
|
||||
}
|
||||
|
||||
init<T : ArgumentDescriptor>(value: T) {
|
||||
name = value.name
|
||||
description = value.description
|
||||
type = value.type
|
||||
|
||||
if let value = value as? Flag {
|
||||
`default` = value.`default`.description
|
||||
flag = value.flag
|
||||
} else if let value = value as? Option<String> {
|
||||
`default` = value.`default`.description
|
||||
flag = nil
|
||||
} else if let value = value as? Option<Int> {
|
||||
`default` = value.`default`.description
|
||||
flag = nil
|
||||
} else {
|
||||
let mirror = Mirror(reflecting: value)
|
||||
|
||||
if let defaultDescendant = mirror.descendant("default"), let defaultConvertible = defaultDescendant as? CustomStringConvertible {
|
||||
`default` = defaultConvertible.description
|
||||
} else {
|
||||
`default` = nil
|
||||
}
|
||||
|
||||
flag = nil
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
class UsageError : Error, ANSIConvertible, CustomStringConvertible {
|
||||
let message: String
|
||||
let help: Help
|
||||
|
||||
init(_ message: String, _ help: Help) {
|
||||
self.message = message
|
||||
self.help = help
|
||||
}
|
||||
|
||||
var description: String {
|
||||
return [message, help.description].filter { !$0.isEmpty }.joined(separator: "\n\n")
|
||||
}
|
||||
|
||||
var ansiDescription: String {
|
||||
return [message, help.ansiDescription].filter { !$0.isEmpty }.joined(separator: "\n\n")
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
class Help : Error, ANSIConvertible, CustomStringConvertible {
|
||||
let command: String?
|
||||
let group: Group?
|
||||
let descriptors: [BoxedArgumentDescriptor]
|
||||
|
||||
init(_ descriptors: [BoxedArgumentDescriptor], command: String? = nil, group: Group? = nil) {
|
||||
self.command = command
|
||||
self.group = group
|
||||
self.descriptors = descriptors
|
||||
}
|
||||
|
||||
func reraise(_ command: String? = nil) -> Help {
|
||||
if let oldCommand = self.command, let newCommand = command {
|
||||
return Help(descriptors, command: "\(newCommand) \(oldCommand)")
|
||||
}
|
||||
return Help(descriptors, command: command ?? self.command)
|
||||
}
|
||||
|
||||
var description: String {
|
||||
var output = [String]()
|
||||
|
||||
let arguments = descriptors.filter { $0.type == ArgumentType.argument }
|
||||
let options = descriptors.filter { $0.type == ArgumentType.option }
|
||||
|
||||
if let command = command {
|
||||
let args = arguments.map { "<\($0.name)>" }
|
||||
let usage = ([command] + args).joined(separator: " ")
|
||||
|
||||
output.append("Usage:")
|
||||
output.append("")
|
||||
output.append(" \(usage)")
|
||||
output.append("")
|
||||
}
|
||||
|
||||
if let group = group {
|
||||
output.append("Commands:")
|
||||
output.append("")
|
||||
let commands = group.commands.sorted(by: { $0.name < $1.name })
|
||||
for command in commands {
|
||||
if let description = command.description {
|
||||
output.append(" + \(command.name) - \(description)")
|
||||
} else {
|
||||
output.append(" + \(command.name)")
|
||||
}
|
||||
}
|
||||
output.append("")
|
||||
} else if !arguments.isEmpty {
|
||||
output.append("Arguments:")
|
||||
output.append("")
|
||||
output += arguments.map { " \($0.summary)" }
|
||||
output.append("")
|
||||
}
|
||||
|
||||
if !options.isEmpty {
|
||||
output.append("Options:")
|
||||
for option in options {
|
||||
output.append(" \(option.summary)")
|
||||
}
|
||||
}
|
||||
|
||||
return output.joined(separator: "\n")
|
||||
}
|
||||
|
||||
var ansiDescription: String {
|
||||
var output = [String]()
|
||||
|
||||
let arguments = descriptors.filter { $0.type == ArgumentType.argument }
|
||||
let options = descriptors.filter { $0.type == ArgumentType.option }
|
||||
|
||||
if let command = command {
|
||||
let args = arguments.map { "<\($0.name)>" }
|
||||
let usage = ([command] + args).joined(separator: " ")
|
||||
|
||||
output.append("Usage:")
|
||||
output.append("")
|
||||
output.append(" \(usage)")
|
||||
output.append("")
|
||||
}
|
||||
|
||||
if let group = group {
|
||||
output.append("Commands:")
|
||||
output.append("")
|
||||
let commands = group.commands.sorted(by: { $0.name < $1.name })
|
||||
for command in commands {
|
||||
if let description = command.description {
|
||||
output.append(" + \(ANSI.green)\(command.name)\(ANSI.reset) - \(description)")
|
||||
} else {
|
||||
output.append(" + \(ANSI.green)\(command.name)\(ANSI.reset)")
|
||||
}
|
||||
}
|
||||
output.append("")
|
||||
} else if !arguments.isEmpty {
|
||||
output.append("Arguments:")
|
||||
output.append("")
|
||||
|
||||
output += arguments.map { argument in
|
||||
if let description = argument.description {
|
||||
return " \(ANSI.blue)\(argument.name)\(ANSI.reset) - \(description)"
|
||||
} else {
|
||||
return " \(ANSI.blue)\(argument.name)\(ANSI.reset)"
|
||||
}
|
||||
}
|
||||
|
||||
output.append("")
|
||||
}
|
||||
|
||||
if !options.isEmpty {
|
||||
output.append("Options:")
|
||||
for option in options {
|
||||
var line = " "
|
||||
|
||||
if let flag = option.flag {
|
||||
line += "\(ANSI.blue)-\(flag)\(ANSI.reset), "
|
||||
}
|
||||
|
||||
line += "\(ANSI.blue)--\(option.name)\(ANSI.reset)"
|
||||
|
||||
if let `default` = option.default {
|
||||
line += " [default: \(`default`)]"
|
||||
}
|
||||
|
||||
if let description = option.description {
|
||||
line += " - \(description)"
|
||||
}
|
||||
|
||||
output.append(line)
|
||||
}
|
||||
}
|
||||
|
||||
return output.joined(separator: "\n")
|
||||
}
|
||||
}
|
||||
-283
@@ -1,283 +0,0 @@
|
||||
private enum Arg : CustomStringConvertible, Equatable {
|
||||
/// A positional argument
|
||||
case argument(String)
|
||||
|
||||
/// A boolean like option, `--version`, `--help`, `--no-clean`.
|
||||
case option(String)
|
||||
|
||||
/// A flag
|
||||
case flag([Character])
|
||||
|
||||
var description:String {
|
||||
switch self {
|
||||
case .argument(let value):
|
||||
return value
|
||||
case .option(let key):
|
||||
return "--\(key)"
|
||||
case .flag(let flags):
|
||||
return "-\(String(flags))"
|
||||
}
|
||||
}
|
||||
|
||||
var type:String {
|
||||
switch self {
|
||||
case .argument:
|
||||
return "argument"
|
||||
case .option:
|
||||
return "option"
|
||||
case .flag:
|
||||
return "flag"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
private func == (lhs: Arg, rhs: Arg) -> Bool {
|
||||
return lhs.description == rhs.description
|
||||
}
|
||||
|
||||
|
||||
public struct ArgumentParserError : Error, Equatable, CustomStringConvertible {
|
||||
public let description: String
|
||||
|
||||
public init(_ description: String) {
|
||||
self.description = description
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
public func ==(lhs: ArgumentParserError, rhs: ArgumentParserError) -> Bool {
|
||||
return lhs.description == rhs.description
|
||||
}
|
||||
|
||||
public final class ArgumentParser : ArgumentConvertible, CustomStringConvertible {
|
||||
fileprivate var arguments:[Arg]
|
||||
|
||||
public typealias Option = String
|
||||
public typealias Flag = Character
|
||||
|
||||
/// Initialises the ArgumentParser with an array of arguments
|
||||
public init(arguments: [String]) {
|
||||
let splitArguments = arguments.split(maxSplits: 1, omittingEmptySubsequences: false) { $0 == "--" }
|
||||
|
||||
let unfixedArguments: [String]
|
||||
let fixedArguments: [String]
|
||||
if splitArguments.count == 2, let prefix = splitArguments.first, let suffix = splitArguments.last {
|
||||
unfixedArguments = Array(prefix)
|
||||
fixedArguments = Array(suffix)
|
||||
} else {
|
||||
unfixedArguments = arguments
|
||||
fixedArguments = []
|
||||
}
|
||||
|
||||
self.arguments = unfixedArguments.map { argument in
|
||||
if argument.first == "-" {
|
||||
let flags = argument[argument.index(after: argument.startIndex)..<argument.endIndex]
|
||||
|
||||
if flags.first == "-" {
|
||||
let option = flags[flags.index(after: flags.startIndex)..<flags.endIndex]
|
||||
return .option(String(option))
|
||||
}
|
||||
return .flag(Array(String(flags)))
|
||||
}
|
||||
|
||||
return .argument(argument)
|
||||
}
|
||||
self.arguments.append(contentsOf: fixedArguments.map { .argument($0) })
|
||||
}
|
||||
|
||||
public init(parser: ArgumentParser) throws {
|
||||
arguments = parser.arguments
|
||||
}
|
||||
|
||||
public var description:String {
|
||||
return arguments.map { $0.description }.joined(separator: " ")
|
||||
}
|
||||
|
||||
public var isEmpty: Bool {
|
||||
return arguments.first { $0 != .argument("") } == nil
|
||||
}
|
||||
|
||||
public var remainder:[String] {
|
||||
return arguments.map { $0.description }
|
||||
}
|
||||
|
||||
/// Returns the first positional argument in the remaining arguments.
|
||||
/// This will remove the argument from the remaining arguments.
|
||||
public func shift() -> String? {
|
||||
for (index, argument) in arguments.enumerated() {
|
||||
switch argument {
|
||||
case .argument(let value):
|
||||
arguments.remove(at: index)
|
||||
return value
|
||||
default:
|
||||
continue
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
/// Returns the value for an option (--name Kyle, --name=Kyle)
|
||||
public func shiftValue(for name: Option) throws -> String? {
|
||||
return try shiftValues(for: name)?.first
|
||||
}
|
||||
|
||||
/// Returns the value for an option (--name Kyle, --name=Kyle)
|
||||
public func shiftValues(for name: Option, count: Int = 1) throws -> [String]? {
|
||||
var index = 0
|
||||
var hasOption = false
|
||||
|
||||
for argument in arguments {
|
||||
switch argument {
|
||||
case .option(let option):
|
||||
if option == name {
|
||||
hasOption = true
|
||||
break
|
||||
}
|
||||
fallthrough
|
||||
default:
|
||||
index += 1
|
||||
}
|
||||
|
||||
if hasOption {
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
if hasOption {
|
||||
arguments.remove(at: index) // Pop option
|
||||
return try (0..<count).map { i in
|
||||
if arguments.count > index {
|
||||
let argument = arguments.remove(at: index)
|
||||
switch argument {
|
||||
case .argument(let value):
|
||||
return value
|
||||
default:
|
||||
throw ArgumentParserError("Unexpected \(argument.type) `\(argument)` as a value for `--\(name)`")
|
||||
}
|
||||
}
|
||||
|
||||
throw ArgumentError.missingValue(argument: "--\(name)")
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
/// Returns whether an option was specified in the arguments
|
||||
public func hasOption(_ name: Option) -> Bool {
|
||||
var index = 0
|
||||
for argument in arguments {
|
||||
switch argument {
|
||||
case .option(let option):
|
||||
if option == name {
|
||||
arguments.remove(at: index)
|
||||
return true
|
||||
}
|
||||
default:
|
||||
break
|
||||
}
|
||||
|
||||
index += 1
|
||||
}
|
||||
|
||||
return false
|
||||
}
|
||||
|
||||
/// Returns whether a flag was specified in the arguments
|
||||
public func hasFlag(_ flag: Flag) -> Bool {
|
||||
var index = 0
|
||||
for argument in arguments {
|
||||
switch argument {
|
||||
case .flag(let option):
|
||||
var options = option
|
||||
if options.contains(flag) {
|
||||
options.removeAll(where: { $0 == flag })
|
||||
arguments.remove(at: index)
|
||||
|
||||
if !options.isEmpty {
|
||||
arguments.insert(.flag(options), at: index)
|
||||
}
|
||||
return true
|
||||
}
|
||||
default:
|
||||
break
|
||||
}
|
||||
|
||||
index += 1
|
||||
}
|
||||
|
||||
return false
|
||||
}
|
||||
|
||||
/// Returns the value for a flag (-n Kyle)
|
||||
public func shiftValue(for flag: Flag) throws -> String? {
|
||||
return try shiftValues(for: flag)?.first
|
||||
}
|
||||
|
||||
/// Returns the value for a flag (-n Kyle)
|
||||
public func shiftValues(for flag: Flag, count: Int = 1) throws -> [String]? {
|
||||
var index = 0
|
||||
var hasFlag = false
|
||||
|
||||
for argument in arguments {
|
||||
switch argument {
|
||||
case .flag(let flags):
|
||||
if flags.contains(flag) {
|
||||
hasFlag = true
|
||||
break
|
||||
}
|
||||
fallthrough
|
||||
default:
|
||||
index += 1
|
||||
}
|
||||
|
||||
if hasFlag {
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
if hasFlag {
|
||||
arguments.remove(at: index)
|
||||
|
||||
return try (0..<count).map { i in
|
||||
if arguments.count > index {
|
||||
let argument = arguments.remove(at: index)
|
||||
switch argument {
|
||||
case .argument(let value):
|
||||
return value
|
||||
default:
|
||||
throw ArgumentParserError("Unexpected \(argument.type) `\(argument)` as a value for `-\(flag)`")
|
||||
}
|
||||
}
|
||||
|
||||
throw ArgumentError.missingValue(argument: "-\(flag)")
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
/// Returns the value for an option (--name Kyle, --name=Kyle) or flag (-n Kyle)
|
||||
public func shiftValue(for name: Option, or flag: Flag?) throws -> String? {
|
||||
if let value = try shiftValue(for: name) {
|
||||
return value
|
||||
} else if let flag = flag, let value = try shiftValue(for: flag) {
|
||||
return value
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
/// Returns the values for an option (--name Kyle, --name=Kyle) or flag (-n Kyle)
|
||||
public func shiftValues(for name: Option, or flag: Flag?, count: Int = 1) throws -> [String]? {
|
||||
if let value = try shiftValues(for: name, count: count) {
|
||||
return value
|
||||
} else if let flag = flag, let value = try shiftValues(for: flag, count: count) {
|
||||
return value
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
}
|
||||
-23
@@ -1,23 +0,0 @@
|
||||
/// A simple CommandType using a closure
|
||||
struct AnonymousCommand : CommandType {
|
||||
var closure:(ArgumentParser) throws -> ()
|
||||
|
||||
init(_ closure:@escaping ((ArgumentParser) throws -> ())) {
|
||||
self.closure = closure
|
||||
}
|
||||
|
||||
func run(_ parser:ArgumentParser) throws {
|
||||
try closure(parser)
|
||||
}
|
||||
}
|
||||
|
||||
enum CommandError : Error {
|
||||
case invalidArgument
|
||||
}
|
||||
|
||||
/// Create a command using a closure
|
||||
public func command(_ closure: @escaping () throws -> ()) -> CommandType {
|
||||
return AnonymousCommand { parser in
|
||||
try closure()
|
||||
}
|
||||
}
|
||||
@@ -1,50 +0,0 @@
|
||||
#if os(Linux)
|
||||
import Glibc
|
||||
#else
|
||||
import Darwin
|
||||
#endif
|
||||
|
||||
|
||||
/// Extensions to CommandType to provide convinience running methods for CLI tools
|
||||
extension CommandType {
|
||||
/// Run the command using the `Process.argument`, removing the executable name
|
||||
public func run(_ version:String? = nil) -> Never {
|
||||
let parser = ArgumentParser(arguments: CommandLine.arguments)
|
||||
|
||||
if parser.hasOption("version") && !parser.hasOption("help") {
|
||||
if let version = version {
|
||||
print(version)
|
||||
exit(0)
|
||||
}
|
||||
}
|
||||
|
||||
let executableName = parser.shift()! // Executable Name
|
||||
|
||||
do {
|
||||
try run(parser)
|
||||
} catch let error as Help {
|
||||
let help = error.reraise("$ \(executableName)")
|
||||
help.print()
|
||||
exit(1)
|
||||
} catch GroupError.noCommand(let path, let group) {
|
||||
var usage = "$ \(executableName)"
|
||||
if let path = path {
|
||||
usage += " \(path)"
|
||||
}
|
||||
let help = Help([], command: usage, group: group)
|
||||
help.print()
|
||||
exit(1)
|
||||
} catch let error as ANSIConvertible {
|
||||
error.print()
|
||||
exit(1)
|
||||
} catch let error as CustomStringConvertible {
|
||||
ANSI.red.print(error.description, to: stderr)
|
||||
exit(1)
|
||||
} catch {
|
||||
ANSI.red.print("Unknown error occurred.", to: stderr)
|
||||
exit(1)
|
||||
}
|
||||
|
||||
exit(0)
|
||||
}
|
||||
}
|
||||
-14
@@ -1,14 +0,0 @@
|
||||
/// Represents a command that can be run, given an argument parser
|
||||
public protocol CommandType {
|
||||
func run(_ parser:ArgumentParser) throws
|
||||
}
|
||||
|
||||
|
||||
/// Extensions to CommandType to provide convinience running methods
|
||||
extension CommandType {
|
||||
/// Run the command with an array of arguments
|
||||
public func run(_ arguments:[String]) throws {
|
||||
try run(ArgumentParser(arguments: arguments))
|
||||
}
|
||||
}
|
||||
|
||||
-2133
File diff suppressed because it is too large
Load Diff
-58
@@ -1,58 +0,0 @@
|
||||
#if os(Linux)
|
||||
import Glibc
|
||||
#else
|
||||
import Darwin
|
||||
#endif
|
||||
|
||||
|
||||
protocol ANSIConvertible : Error, CustomStringConvertible {
|
||||
var ansiDescription: String { get }
|
||||
}
|
||||
|
||||
|
||||
extension ANSIConvertible {
|
||||
func print() {
|
||||
// Check if we are in any term env and the output is a tty.
|
||||
if ANSI.isTerminalSupported {
|
||||
fputs("\(ansiDescription)\n", stderr)
|
||||
} else {
|
||||
fputs("\(description)\n", stderr)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
enum ANSI: UInt8, CustomStringConvertible {
|
||||
case reset = 0
|
||||
|
||||
case black = 30
|
||||
case red
|
||||
case green
|
||||
case yellow
|
||||
case blue
|
||||
case magenta
|
||||
case cyan
|
||||
case white
|
||||
case `default`
|
||||
|
||||
var description: String {
|
||||
return "\u{001B}[\(self.rawValue)m"
|
||||
}
|
||||
|
||||
static var isTerminalSupported: Bool {
|
||||
if let termType = getenv("TERM"), String(cString: termType).lowercased() != "dumb" &&
|
||||
isatty(fileno(stdout)) != 0 {
|
||||
return true
|
||||
} else {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
func print(_ string: String, to output: UnsafeMutablePointer<FILE> = stdout) {
|
||||
if ANSI.isTerminalSupported {
|
||||
fputs("\(self)\(string)\(ANSI.reset)\n", output)
|
||||
} else {
|
||||
fputs("\(string)\n", output)
|
||||
}
|
||||
}
|
||||
}
|
||||
-120
@@ -1,120 +0,0 @@
|
||||
public enum GroupError : Error, Equatable, CustomStringConvertible {
|
||||
/// No-subcommand was found with the given name
|
||||
case unknownCommand(String)
|
||||
|
||||
/// No command was given
|
||||
/// :param: The current path to the command (i.e, all the group names)
|
||||
/// :param: The group raising the error
|
||||
case noCommand(String?, Group)
|
||||
|
||||
public var description:String {
|
||||
switch self {
|
||||
case .unknownCommand(let name):
|
||||
return "Unknown command: `\(name)`"
|
||||
case .noCommand(let path, let group):
|
||||
let available = group.commands.map { $0.name }.sorted().joined(separator: ", ")
|
||||
if let path = path {
|
||||
return "Usage: \(path) COMMAND\n\nCommands: \(available)"
|
||||
} else {
|
||||
return "Commands: \(available)"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public func == (lhs: GroupError, rhs: GroupError) -> Bool {
|
||||
switch (lhs, rhs) {
|
||||
case let (.unknownCommand(lhsCommand), .unknownCommand(rhsCommand)):
|
||||
return lhsCommand == rhsCommand
|
||||
case let (.noCommand(lhsPath, lhsGroup), .noCommand(rhsPath, rhsGroup)):
|
||||
return lhsPath == rhsPath && lhsGroup === rhsGroup
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
/// Represents a group of commands
|
||||
open class Group : CommandType {
|
||||
struct SubCommand {
|
||||
let name: String
|
||||
let description: String?
|
||||
let command: CommandType
|
||||
|
||||
init(name: String, description: String?, command: CommandType) {
|
||||
self.name = name
|
||||
self.description = description
|
||||
self.command = command
|
||||
}
|
||||
}
|
||||
|
||||
var commands = [SubCommand]()
|
||||
public var commandNames: [String] {
|
||||
return commands.map { $0.name }
|
||||
}
|
||||
|
||||
// When set, allows you to override the default unknown command behaviour
|
||||
public var unknownCommand: ((_ name: String, _ parser: ArgumentParser) throws -> ())?
|
||||
|
||||
// When set, allows you to override the default no command behaviour
|
||||
public var noCommand: ((_ path: String?, _ group: Group, _ parser: ArgumentParser) throws -> ())?
|
||||
|
||||
/// Create a new group
|
||||
public init() {}
|
||||
|
||||
/// Add a named sub-command to the group
|
||||
public func addCommand(_ name: String, _ command: CommandType) {
|
||||
commands.append(SubCommand(name: name, description: nil, command: command))
|
||||
}
|
||||
|
||||
/// Add a named sub-command to the group with a description
|
||||
public func addCommand(_ name: String, _ description: String?, _ command: CommandType) {
|
||||
commands.append(SubCommand(name: name, description: description, command: command))
|
||||
}
|
||||
|
||||
/// Run the group command
|
||||
public func run(_ parser: ArgumentParser) throws {
|
||||
guard let name = parser.shift() else {
|
||||
if let noCommand = noCommand {
|
||||
return try noCommand(nil, self, parser)
|
||||
} else {
|
||||
throw GroupError.noCommand(nil, self)
|
||||
}
|
||||
}
|
||||
|
||||
guard let command = commands.first(where: { $0.name == name }) else {
|
||||
if let unknownCommand = unknownCommand {
|
||||
return try unknownCommand(name, parser)
|
||||
} else {
|
||||
throw GroupError.unknownCommand(name)
|
||||
}
|
||||
}
|
||||
|
||||
do {
|
||||
try command.command.run(parser)
|
||||
} catch GroupError.unknownCommand(let childName) {
|
||||
throw GroupError.unknownCommand("\(name) \(childName)")
|
||||
} catch GroupError.noCommand(let path, let group) {
|
||||
let path = (path == nil) ? name : "\(name) \(path!)"
|
||||
|
||||
if let noCommand = noCommand {
|
||||
try noCommand(path, group, parser)
|
||||
} else {
|
||||
throw GroupError.noCommand(path, group)
|
||||
}
|
||||
} catch let error as Help {
|
||||
throw error.reraise(name)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension Group {
|
||||
public convenience init(closure: (Group) -> ()) {
|
||||
self.init()
|
||||
closure(self)
|
||||
}
|
||||
|
||||
/// Add a sub-group using a closure
|
||||
public func group(_ name: String, _ description: String? = nil, closure: (Group) -> ()) {
|
||||
addCommand(name, description, Group(closure: closure))
|
||||
}
|
||||
}
|
||||
-28
@@ -1,28 +0,0 @@
|
||||
{
|
||||
"name": "xcodeproj",
|
||||
"version": "7.18.0",
|
||||
"summary": "Read/Modify/Write your Xcode projects",
|
||||
"homepage": "https://github.com/tuist/xcodeproj",
|
||||
"license": "MIT",
|
||||
"source": {
|
||||
"git": "https://github.com/tuist/xcodeproj.git",
|
||||
"tag": "7.18.0"
|
||||
},
|
||||
"requires_arc": true,
|
||||
"authors": "Tuist",
|
||||
"swift_versions": "5.1",
|
||||
"platforms": {
|
||||
"osx": "10.10"
|
||||
},
|
||||
"source_files": "Sources/**/*.{swift}",
|
||||
"module_name": "XcodeProj",
|
||||
"dependencies": {
|
||||
"PathKit": [
|
||||
"~> 1.0.0"
|
||||
],
|
||||
"AEXML": [
|
||||
"~> 4.6.0"
|
||||
]
|
||||
},
|
||||
"swift_version": "5.1"
|
||||
}
|
||||
Generated
-64
@@ -1,64 +0,0 @@
|
||||
PODS:
|
||||
- AEXML (4.6.0)
|
||||
- Commander (0.9.1)
|
||||
- Nimble (9.0.0)
|
||||
- PathKit (1.0.0)
|
||||
- Quick (3.1.2)
|
||||
- Stencil (0.14.0):
|
||||
- PathKit (~> 1.0.0)
|
||||
- StencilSwiftKit (2.8.0):
|
||||
- Stencil (~> 0.14.0)
|
||||
- SwiftLint (0.43.1)
|
||||
- xcodeproj (7.18.0):
|
||||
- AEXML (~> 4.6.0)
|
||||
- PathKit (~> 1.0.0)
|
||||
- Yams (4.0.0)
|
||||
|
||||
DEPENDENCIES:
|
||||
- Commander (= 0.9.1)
|
||||
- Nimble
|
||||
- PathKit (= 1.0.0)
|
||||
- Quick
|
||||
- Stencil (= 0.14.0)
|
||||
- StencilSwiftKit (= 2.8.0)
|
||||
- SwiftLint
|
||||
- "xcodeproj (from `git@github.com:tuist/XcodeProj.git`, tag `7.18.0`)"
|
||||
- Yams (= 4.0.0)
|
||||
|
||||
SPEC REPOS:
|
||||
trunk:
|
||||
- AEXML
|
||||
- Commander
|
||||
- Nimble
|
||||
- PathKit
|
||||
- Quick
|
||||
- Stencil
|
||||
- StencilSwiftKit
|
||||
- SwiftLint
|
||||
- Yams
|
||||
|
||||
EXTERNAL SOURCES:
|
||||
xcodeproj:
|
||||
:git: "git@github.com:tuist/XcodeProj.git"
|
||||
:tag: 7.18.0
|
||||
|
||||
CHECKOUT OPTIONS:
|
||||
xcodeproj:
|
||||
:git: "git@github.com:tuist/XcodeProj.git"
|
||||
:tag: 7.18.0
|
||||
|
||||
SPEC CHECKSUMS:
|
||||
AEXML: 2fbb73d8724797ed2cde888731e176fa4d44dd83
|
||||
Commander: 723330cf3697b604c00afb9db9576be81a03c501
|
||||
Nimble: 3b4ec3fd40f1dc178058e0981107721c615643d8
|
||||
PathKit: 364e0de7fb5adb142aecab4e112187e5548fc4b6
|
||||
Quick: 60f0ea3b8e0cfc0df3259a5c06a238ad8b3c46e0
|
||||
Stencil: 19487b54873a6ed8d8e4cccc4b45c1a601941f06
|
||||
StencilSwiftKit: 946b0a1ae1067ef195231a135fe6d8f240b46942
|
||||
SwiftLint: 99f82d07b837b942dd563c668de129a03fc3fb52
|
||||
xcodeproj: 760cfd754df4cfac71ec86b1cbdd6075f9fd3102
|
||||
Yams: 9d49b85824751ee13d31e9ec6617c4dfb9a8c3cd
|
||||
|
||||
PODFILE CHECKSUM: 53232264d2ea3889cc7168839639589c41eeb9a0
|
||||
|
||||
COCOAPODS: 1.10.1
|
||||
Generated
Vendored
-35
@@ -1,35 +0,0 @@
|
||||
//
|
||||
// CwlCatchException.swift
|
||||
// CwlAssertionTesting
|
||||
//
|
||||
// Created by Matt Gallagher on 2016/01/10.
|
||||
// Copyright © 2016 Matt Gallagher ( https://www.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 SWIFT_PACKAGE
|
||||
import CwlCatchExceptionSupport
|
||||
#endif
|
||||
|
||||
private func catchReturnTypeConverter<T: NSException>(_ type: T.Type, block: @escaping () -> Void) -> T? {
|
||||
return catchExceptionOfKind(type, block) as? T
|
||||
}
|
||||
|
||||
extension NSException {
|
||||
public static func catchException(in block: @escaping () -> Void) -> Self? {
|
||||
return catchReturnTypeConverter(self, block: block)
|
||||
}
|
||||
}
|
||||
Generated
Vendored
-34
@@ -1,34 +0,0 @@
|
||||
//
|
||||
// CwlCatchException.m
|
||||
// CwlAssertionTesting
|
||||
//
|
||||
// Created by Matt Gallagher on 2016/01/10.
|
||||
// Copyright © 2016 Matt Gallagher ( https://www.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"
|
||||
|
||||
NSException* __nullable catchExceptionOfKind(Class __nonnull type, void (^ __nonnull inBlock)(void)) {
|
||||
@try {
|
||||
inBlock();
|
||||
} @catch (NSException *exception) {
|
||||
if ([exception isKindOfClass:type]) {
|
||||
return exception;
|
||||
} else {
|
||||
@throw;
|
||||
}
|
||||
}
|
||||
return nil;
|
||||
}
|
||||
Generated
Vendored
-23
@@ -1,23 +0,0 @@
|
||||
//
|
||||
// CwlCatchException.h
|
||||
// CwlCatchException
|
||||
//
|
||||
// Created by Matt Gallagher on 2016/01/10.
|
||||
// Copyright © 2016 Matt Gallagher ( https://www.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/Foundation.h>
|
||||
|
||||
NSException* __nullable catchExceptionOfKind(Class __nonnull type, void (^ __nonnull inBlock)(void));
|
||||
Generated
Vendored
-53
@@ -1,53 +0,0 @@
|
||||
//
|
||||
// CwlMachBadExceptionHandler.m
|
||||
// CwlPreconditionTesting
|
||||
//
|
||||
// Created by Matt Gallagher on 2016/01/10.
|
||||
// Copyright © 2016 Matt Gallagher ( https://www.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.
|
||||
//
|
||||
|
||||
#ifdef __APPLE__
|
||||
#import "TargetConditionals.h"
|
||||
#if TARGET_OS_OSX || TARGET_OS_IOS
|
||||
|
||||
#import "mach_excServer.h"
|
||||
#import "CwlMachBadInstructionHandler.h"
|
||||
|
||||
@protocol BadInstructionReply <NSObject>
|
||||
+(NSNumber *)receiveReply:(NSValue *)value;
|
||||
@end
|
||||
|
||||
/// 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) {
|
||||
bad_instruction_exception_reply_t reply = { exception_port, exception, code, codeCnt, flavor, old_state, old_stateCnt, new_state, new_stateCnt };
|
||||
Class badInstructionClass = NSClassFromString(@"BadInstructionException");
|
||||
NSValue *value = [NSValue valueWithBytes: &reply objCType: @encode(bad_instruction_exception_reply_t)];
|
||||
return [[badInstructionClass performSelector: @selector(receiveReply:) withObject: value] intValue];
|
||||
}
|
||||
|
||||
// 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 /* TARGET_OS_OSX || TARGET_OS_IOS */
|
||||
#endif /* __APPLE__ */
|
||||
Generated
Vendored
-78
@@ -1,78 +0,0 @@
|
||||
//
|
||||
// CwlMachBadInstructionHandler.h
|
||||
// CwlPreconditionTesting
|
||||
//
|
||||
// Created by Matt Gallagher on 2016/01/10.
|
||||
// Copyright © 2016 Matt Gallagher ( https://www.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/Foundation.h>
|
||||
|
||||
#if TARGET_OS_OSX || TARGET_OS_IOS
|
||||
|
||||
#import <mach/mach.h>
|
||||
|
||||
extern bool _swift_disableExclusivityChecking;
|
||||
extern bool _swift_reportFatalErrorsToDebugger;
|
||||
|
||||
NS_ASSUME_NONNULL_BEGIN
|
||||
|
||||
extern boolean_t mach_exc_server(mach_msg_header_t *InHeadP, mach_msg_header_t *OutHeadP);
|
||||
|
||||
// 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;
|
||||
|
||||
typedef struct
|
||||
{
|
||||
mach_port_t exception_port;
|
||||
exception_type_t exception;
|
||||
mach_exception_data_type_t const * _Nullable code;
|
||||
mach_msg_type_number_t codeCnt;
|
||||
int32_t * _Nullable flavor;
|
||||
natural_t const * _Nullable old_state;
|
||||
mach_msg_type_number_t old_stateCnt;
|
||||
thread_state_t _Nullable new_state;
|
||||
mach_msg_type_number_t * _Nullable new_stateCnt;
|
||||
} bad_instruction_exception_reply_t;
|
||||
|
||||
NS_ASSUME_NONNULL_END
|
||||
|
||||
#endif
|
||||
Generated
Vendored
-536
@@ -1,536 +0,0 @@
|
||||
/*
|
||||
* IDENTIFICATION:
|
||||
* stub generated Sun Jan 29 19:05:29 2017
|
||||
* with a MiG generated by bootstrap_cmds-96.20.2
|
||||
* OPTIONS:
|
||||
*/
|
||||
|
||||
/* Module mach_exc */
|
||||
|
||||
#define __MIG_check__Request__mach_exc_subsystem__ 1
|
||||
|
||||
#import "mach_excServer.h"
|
||||
#if TARGET_OS_OSX || TARGET_OS_IOS
|
||||
|
||||
#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;
|
||||
OutHeadP->msgh_reserved = 0;
|
||||
|
||||
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 /* TARGET_OS_OSX || TARGET_OS_IOS */
|
||||
Generated
Vendored
-329
@@ -1,329 +0,0 @@
|
||||
#ifdef __APPLE__
|
||||
#import "TargetConditionals.h"
|
||||
#if TARGET_OS_OSX || TARGET_OS_IOS
|
||||
|
||||
#ifndef _mach_exc_server_
|
||||
#define _mach_exc_server_
|
||||
|
||||
/* Module mach_exc */
|
||||
|
||||
#include <string.h>
|
||||
|
||||
#include <mach/ndr.h>
|
||||
#include <mach/boolean.h>
|
||||
#include <mach/kern_return.h>
|
||||
#include <mach/notify.h>
|
||||
#include <mach/mach_types.h>
|
||||
#include <mach/message.h>
|
||||
#include <mach/mig_errors.h>
|
||||
#include <mach/port.h>
|
||||
|
||||
/* BEGIN VOUCHER CODE */
|
||||
|
||||
#ifndef KERNEL
|
||||
#if defined(__has_include)
|
||||
#if __has_include(<mach/mig_voucher_support.h>)
|
||||
#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(<mach/mach_voucher_types.h>)
|
||||
#endif // __has_include
|
||||
#endif // !KERNEL
|
||||
|
||||
/* END VOUCHER CODE */
|
||||
|
||||
|
||||
/* BEGIN MIG_STRNCPY_ZEROFILL CODE */
|
||||
|
||||
#if defined(__has_include)
|
||||
#if __has_include(<mach/mig_strncpy_zerofill_support.h>)
|
||||
#ifndef USING_MIG_STRNCPY_ZEROFILL
|
||||
#define USING_MIG_STRNCPY_ZEROFILL
|
||||
#endif
|
||||
#ifndef __MIG_STRNCPY_ZEROFILL_FORWARD_TYPE_DECLS__
|
||||
#define __MIG_STRNCPY_ZEROFILL_FORWARD_TYPE_DECLS__
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif
|
||||
extern int mig_strncpy_zerofill(char *dest, const char *src, int len) __attribute__((weak_import));
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif
|
||||
#endif /* __MIG_STRNCPY_ZEROFILL_FORWARD_TYPE_DECLS__ */
|
||||
#endif /* __has_include(<mach/mig_strncpy_zerofill_support.h>) */
|
||||
#endif /* __has_include */
|
||||
|
||||
/* END MIG_STRNCPY_ZEROFILL 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 <mach/std_types.h>
|
||||
#include <mach/mig.h>
|
||||
#include <mach/mig.h>
|
||||
#include <mach/mach_types.h>
|
||||
|
||||
#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_ */
|
||||
|
||||
#endif /* TARGET_OS_OSX || TARGET_OS_IOS */
|
||||
#endif /* __APPLE__ */
|
||||
Generated
Vendored
-89
@@ -1,89 +0,0 @@
|
||||
//
|
||||
// CwlBadInstructionException.swift
|
||||
// CwlPreconditionTesting
|
||||
//
|
||||
// Created by Matt Gallagher on 2016/01/10.
|
||||
// Copyright © 2016 Matt Gallagher ( https://www.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 (os(macOS) || os(iOS)) && arch(x86_64)
|
||||
|
||||
import Foundation
|
||||
|
||||
#if SWIFT_PACKAGE
|
||||
import CwlMachBadInstructionHandler
|
||||
#endif
|
||||
|
||||
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(BadInstructionException)
|
||||
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.
|
||||
@objc(receiveReply:)
|
||||
public class func receiveReply(_ value: NSValue) -> NSNumber {
|
||||
var reply = bad_instruction_exception_reply_t(exception_port: 0, exception: 0, code: nil, codeCnt: 0, flavor: nil, old_state: nil, old_stateCnt: 0, new_state: nil, new_stateCnt: nil)
|
||||
withUnsafeMutablePointer(to: &reply) { value.getValue(UnsafeMutableRawPointer($0)) }
|
||||
|
||||
let old_state: UnsafePointer<natural_t> = reply.old_state!
|
||||
let old_stateCnt: mach_msg_type_number_t = reply.old_stateCnt
|
||||
let new_state: thread_state_t = reply.new_state!
|
||||
let new_stateCnt: UnsafeMutablePointer<mach_msg_type_number_t> = reply.new_stateCnt!
|
||||
|
||||
// Make sure we've been given enough memory
|
||||
if old_stateCnt != x86_THREAD_STATE64_COUNT || new_stateCnt.pointee < x86_THREAD_STATE64_COUNT {
|
||||
return NSNumber(value: 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<Int>.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 NSNumber(value: 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 NSNumber(value: KERN_SUCCESS)
|
||||
}
|
||||
}
|
||||
|
||||
#endif
|
||||
Generated
Vendored
-209
@@ -1,209 +0,0 @@
|
||||
//
|
||||
// CwlCatchBadInstruction.swift
|
||||
// CwlPreconditionTesting
|
||||
//
|
||||
// Created by Matt Gallagher on 2016/01/10.
|
||||
// Copyright © 2016 Matt Gallagher ( https://www.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 (os(macOS) || os(iOS)) && arch(x86_64)
|
||||
|
||||
import Foundation
|
||||
import Swift
|
||||
|
||||
#if SWIFT_PACKAGE
|
||||
import CwlMachBadInstructionHandler
|
||||
#endif
|
||||
|
||||
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 request_mach_exception_raise_t {
|
||||
mutating func withMsgHeaderPointer<R>(in block: (UnsafeMutablePointer<mach_msg_header_t>) -> 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<R>(in block: (UnsafeMutablePointer<mach_msg_header_t>) -> 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<exception_mask_t>()
|
||||
var count: mach_msg_type_number_t = 0
|
||||
var ports = execTypesCountTuple<mach_port_t>()
|
||||
var behaviors = execTypesCountTuple<exception_behavior_t>()
|
||||
var flavors = execTypesCountTuple<thread_state_flavor_t>()
|
||||
var currentExceptionPort: mach_port_t = 0
|
||||
var handlerThread: pthread_t? = nil
|
||||
|
||||
static func internalMutablePointers<R>(_ m: UnsafeMutablePointer<execTypesCountTuple<exception_mask_t>>, _ c: UnsafeMutablePointer<mach_msg_type_number_t>, _ p: UnsafeMutablePointer<execTypesCountTuple<mach_port_t>>, _ b: UnsafeMutablePointer<execTypesCountTuple<exception_behavior_t>>, _ f: UnsafeMutablePointer<execTypesCountTuple<thread_state_flavor_t>>, _ block: (UnsafeMutablePointer<exception_mask_t>, UnsafeMutablePointer<mach_msg_type_number_t>, UnsafeMutablePointer<mach_port_t>, UnsafeMutablePointer<exception_behavior_t>, UnsafeMutablePointer<thread_state_flavor_t>) -> R) -> R {
|
||||
return m.withMemoryRebound(to: exception_mask_t.self, capacity: 1) { masksPtr in
|
||||
return c.withMemoryRebound(to: mach_msg_type_number_t.self, capacity: 1) { countPtr in
|
||||
return p.withMemoryRebound(to: mach_port_t.self, capacity: 1) { portsPtr in
|
||||
return b.withMemoryRebound(to: exception_behavior_t.self, capacity: 1) { behaviorsPtr in
|
||||
return f.withMemoryRebound(to: thread_state_flavor_t.self, capacity: 1) { flavorsPtr in
|
||||
return block(masksPtr, countPtr, portsPtr, behaviorsPtr, flavorsPtr)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
mutating func withUnsafeMutablePointers<R>(in block: @escaping (UnsafeMutablePointer<exception_mask_t>, UnsafeMutablePointer<mach_msg_type_number_t>, UnsafeMutablePointer<mach_port_t>, UnsafeMutablePointer<exception_behavior_t>, UnsafeMutablePointer<thread_state_flavor_t>) -> R) -> R {
|
||||
return MachContext.internalMutablePointers(&masks, &count, &ports, &behaviors, &flavors, block)
|
||||
}
|
||||
}
|
||||
|
||||
/// 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<request_mach_exception_raise_t>.size)
|
||||
let requestSize = request.Head.msgh_size
|
||||
try kernCheck { request.withMsgHeaderPointer { requestPtr in
|
||||
mach_msg(requestPtr, MACH_RCV_MSG | MACH_RCV_INTERRUPT, 0, requestSize, 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<reply_mach_exception_raise_state_t>.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
|
||||
let replySize = reply.Head.msgh_size
|
||||
try kernCheck { reply.withMsgHeaderPointer { replyPtr in
|
||||
mach_msg(replyPtr, MACH_SEND_MSG, replySize, 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: @escaping () -> Void) -> BadInstructionException? {
|
||||
// Suppress Swift runtime's direct triggering of the debugger and exclusivity checking which crashes when we throw past it
|
||||
let previousExclusivity = _swift_disableExclusivityChecking
|
||||
let previousReporting = _swift_reportFatalErrorsToDebugger
|
||||
_swift_disableExclusivityChecking = true
|
||||
_swift_reportFatalErrorsToDebugger = false
|
||||
defer {
|
||||
_swift_reportFatalErrorsToDebugger = previousReporting
|
||||
_swift_disableExclusivityChecking = previousExclusivity
|
||||
}
|
||||
|
||||
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)
|
||||
}
|
||||
|
||||
let currentExceptionPtr = context.currentExceptionPort
|
||||
try kernCheck { context.withUnsafeMutablePointers { masksPtr, countPtr, 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, currentExceptionPtr, Int32(bitPattern: UInt32(EXCEPTION_STATE) | MACH_EXCEPTION_CODES), x86_THREAD_STATE64, masksPtr, countPtr, portsPtr, behaviorsPtr, flavorsPtr)
|
||||
} }
|
||||
|
||||
defer { context.withUnsafeMutablePointers { masksPtr, countPtr, 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, countPtr, 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
|
||||
|
||||
Generated
Vendored
-55
@@ -1,55 +0,0 @@
|
||||
//
|
||||
// CwlDarwinDefinitions.swift
|
||||
// CwlPreconditionTesting
|
||||
//
|
||||
// Created by Matt Gallagher on 2016/01/10.
|
||||
// Copyright © 2016 Matt Gallagher ( https://www.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 (os(macOS) || os(iOS)) && arch(x86_64)
|
||||
|
||||
import Darwin
|
||||
|
||||
// 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))
|
||||
public let MACH_MSG_TYPE_MAKE_SEND: UInt32 = 20
|
||||
public func MACH_MSGH_BITS_REMOTE(_ bits: UInt32) -> UInt32 { return bits & UInt32(MACH_MSGH_BITS_REMOTE_MASK) }
|
||||
public 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)
|
||||
public let EXC_BAD_INSTRUCTION: UInt32 = 2
|
||||
public let EXC_MASK_BAD_INSTRUCTION: UInt32 = 1 << EXC_BAD_INSTRUCTION
|
||||
|
||||
// From /usr/include/mach/i386/thread_status.h
|
||||
// #define x86_THREAD_STATE64_COUNT ((mach_msg_type_number_t) \
|
||||
// ( sizeof (x86_thread_state64_t) / sizeof (int) ))
|
||||
public let x86_THREAD_STATE64_COUNT = UInt32(MemoryLayout<x86_thread_state64_t>.size / MemoryLayout<Int32>.size)
|
||||
|
||||
public let EXC_TYPES_COUNT = 14
|
||||
public struct execTypesCountTuple<T: ExpressibleByIntegerLiteral> {
|
||||
// From /usr/include/mach/i386/exception.h
|
||||
// #define EXC_TYPES_COUNT 14 /* incl. illegal exception 0 */
|
||||
public 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)
|
||||
public init() {
|
||||
}
|
||||
}
|
||||
|
||||
#endif
|
||||
Generated
-201
@@ -1,201 +0,0 @@
|
||||
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 2016 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.
|
||||
Generated
-1776
File diff suppressed because it is too large
Load Diff
@@ -1,16 +0,0 @@
|
||||
/// 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
|
||||
// swiftlint:disable:previous identifier_name
|
||||
return isXCTestAvailable() ? NimbleXCTestHandler() : NimbleXCTestUnavailableHandler()
|
||||
}()
|
||||
@@ -1,19 +0,0 @@
|
||||
/// 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)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,125 +0,0 @@
|
||||
/// 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))
|
||||
}
|
||||
}
|
||||
|
||||
extension NMBExceptionCapture {
|
||||
internal func tryBlockThrows(_ unsafeBlock: () throws -> Void) throws {
|
||||
var catchedError: Error?
|
||||
tryBlock {
|
||||
do {
|
||||
try unsafeBlock()
|
||||
} catch {
|
||||
catchedError = error
|
||||
}
|
||||
}
|
||||
if let error = catchedError {
|
||||
throw error
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 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,
|
||||
file: FileString = #file,
|
||||
line: UInt = #line,
|
||||
closure: () throws -> Void) {
|
||||
let environment = NimbleEnvironment.activeInstance
|
||||
let oldRecorder = environment.assertionHandler
|
||||
let capturer = NMBExceptionCapture(handler: nil, finally: ({
|
||||
environment.assertionHandler = oldRecorder
|
||||
}))
|
||||
environment.assertionHandler = tempAssertionHandler
|
||||
|
||||
do {
|
||||
try capturer.tryBlockThrows {
|
||||
try closure()
|
||||
}
|
||||
} catch {
|
||||
let failureMessage = FailureMessage()
|
||||
failureMessage.stringValue = "unexpected error thrown: <\(error)>"
|
||||
let location = SourceLocation(file: file, line: line)
|
||||
tempAssertionHandler.assert(false, message: failureMessage, location: location)
|
||||
}
|
||||
}
|
||||
|
||||
/// 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: () -> 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: () -> Void) -> [AssertionRecord] {
|
||||
let assertions = gatherExpectations(silently: silently, closure: closure)
|
||||
return assertions.filter { assertion in
|
||||
!assertion.success
|
||||
}
|
||||
}
|
||||
@@ -1,197 +0,0 @@
|
||||
#if canImport(Darwin) && !SWIFT_PACKAGE
|
||||
import class Foundation.NSObject
|
||||
import typealias Foundation.TimeInterval
|
||||
import enum Dispatch.DispatchTimeInterval
|
||||
|
||||
private func from(objcPredicate: NMBPredicate) -> Predicate<NSObject> {
|
||||
return Predicate { actualExpression in
|
||||
let result = objcPredicate.satisfies(({ try actualExpression.evaluate() }),
|
||||
location: actualExpression.location)
|
||||
return result.toSwift()
|
||||
}
|
||||
}
|
||||
|
||||
private func from(matcher: NMBMatcher, style: ExpectationStyle) -> Predicate<NSObject> {
|
||||
// Almost same as `Matcher.toClosure`
|
||||
let closure: (Expression<NSObject>, FailureMessage) throws -> Bool = { expr, msg in
|
||||
switch style {
|
||||
case .toMatch:
|
||||
return matcher.matches(
|
||||
// swiftlint:disable:next force_try
|
||||
({ try! expr.evaluate() }),
|
||||
failureMessage: msg,
|
||||
location: expr.location
|
||||
)
|
||||
case .toNotMatch:
|
||||
return !matcher.doesNotMatch(
|
||||
// swiftlint:disable:next force_try
|
||||
({ try! expr.evaluate() }),
|
||||
failureMessage: msg,
|
||||
location: expr.location
|
||||
)
|
||||
}
|
||||
}
|
||||
return Predicate._fromDeprecatedClosure(closure)
|
||||
}
|
||||
|
||||
// Equivalent to Expectation, but for Nimble's Objective-C interface
|
||||
public class NMBExpectation: NSObject {
|
||||
// swiftlint:disable identifier_name
|
||||
internal let _actualBlock: () -> NSObject?
|
||||
internal var _negative: Bool
|
||||
internal let _file: FileString
|
||||
internal let _line: UInt
|
||||
internal var _timeout: DispatchTimeInterval = .seconds(1)
|
||||
// swiftlint:enable identifier_name
|
||||
|
||||
@objc 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<NSObject> {
|
||||
return expect(file: _file, line: _line, self._actualBlock() as NSObject?)
|
||||
}
|
||||
|
||||
@objc public var withTimeout: (TimeInterval) -> NMBExpectation {
|
||||
return { timeout in self._timeout = timeout.dispatchInterval
|
||||
return self
|
||||
}
|
||||
}
|
||||
|
||||
@objc public var to: (NMBMatcher) -> NMBExpectation {
|
||||
return { matcher in
|
||||
if let pred = matcher as? NMBPredicate {
|
||||
self.expectValue.to(from(objcPredicate: pred))
|
||||
} else {
|
||||
self.expectValue.to(from(matcher: matcher, style: .toMatch))
|
||||
}
|
||||
return self
|
||||
}
|
||||
}
|
||||
|
||||
@objc public var toWithDescription: (NMBMatcher, String) -> NMBExpectation {
|
||||
return { matcher, description in
|
||||
if let pred = matcher as? NMBPredicate {
|
||||
self.expectValue.to(from(objcPredicate: pred), description: description)
|
||||
} else {
|
||||
self.expectValue.to(from(matcher: matcher, style: .toMatch), description: description)
|
||||
}
|
||||
return self
|
||||
}
|
||||
}
|
||||
|
||||
@objc public var toNot: (NMBMatcher) -> NMBExpectation {
|
||||
return { matcher in
|
||||
if let pred = matcher as? NMBPredicate {
|
||||
self.expectValue.toNot(from(objcPredicate: pred))
|
||||
} else {
|
||||
self.expectValue.toNot(from(matcher: matcher, style: .toNotMatch))
|
||||
}
|
||||
return self
|
||||
}
|
||||
}
|
||||
|
||||
@objc public var toNotWithDescription: (NMBMatcher, String) -> NMBExpectation {
|
||||
return { matcher, description in
|
||||
if let pred = matcher as? NMBPredicate {
|
||||
self.expectValue.toNot(from(objcPredicate: pred), description: description)
|
||||
} else {
|
||||
self.expectValue.toNot(from(matcher: matcher, style: .toNotMatch), description: description)
|
||||
}
|
||||
return self
|
||||
}
|
||||
}
|
||||
|
||||
@objc public var notTo: (NMBMatcher) -> NMBExpectation { return toNot }
|
||||
|
||||
@objc public var notToWithDescription: (NMBMatcher, String) -> NMBExpectation { return toNotWithDescription }
|
||||
|
||||
@objc public var toEventually: (NMBMatcher) -> Void {
|
||||
return { matcher in
|
||||
if let pred = matcher as? NMBPredicate {
|
||||
self.expectValue.toEventually(
|
||||
from(objcPredicate: pred),
|
||||
timeout: self._timeout,
|
||||
description: nil
|
||||
)
|
||||
} else {
|
||||
self.expectValue.toEventually(
|
||||
from(matcher: matcher, style: .toMatch),
|
||||
timeout: self._timeout,
|
||||
description: nil
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@objc public var toEventuallyWithDescription: (NMBMatcher, String) -> Void {
|
||||
return { matcher, description in
|
||||
if let pred = matcher as? NMBPredicate {
|
||||
self.expectValue.toEventually(
|
||||
from(objcPredicate: pred),
|
||||
timeout: self._timeout,
|
||||
description: description
|
||||
)
|
||||
} else {
|
||||
self.expectValue.toEventually(
|
||||
from(matcher: matcher, style: .toMatch),
|
||||
timeout: self._timeout,
|
||||
description: description
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@objc public var toEventuallyNot: (NMBMatcher) -> Void {
|
||||
return { matcher in
|
||||
if let pred = matcher as? NMBPredicate {
|
||||
self.expectValue.toEventuallyNot(
|
||||
from(objcPredicate: pred),
|
||||
timeout: self._timeout,
|
||||
description: nil
|
||||
)
|
||||
} else {
|
||||
self.expectValue.toEventuallyNot(
|
||||
from(matcher: matcher, style: .toNotMatch),
|
||||
timeout: self._timeout,
|
||||
description: nil
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@objc public var toEventuallyNotWithDescription: (NMBMatcher, String) -> Void {
|
||||
return { matcher, description in
|
||||
if let pred = matcher as? NMBPredicate {
|
||||
self.expectValue.toEventuallyNot(
|
||||
from(objcPredicate: pred),
|
||||
timeout: self._timeout,
|
||||
description: description
|
||||
)
|
||||
} else {
|
||||
self.expectValue.toEventuallyNot(
|
||||
from(matcher: matcher, style: .toNotMatch),
|
||||
timeout: self._timeout,
|
||||
description: description
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@objc public var toNotEventually: (NMBMatcher) -> Void {
|
||||
return toEventuallyNot
|
||||
}
|
||||
|
||||
@objc public var toNotEventuallyWithDescription: (NMBMatcher, String) -> Void {
|
||||
return toEventuallyNotWithDescription
|
||||
}
|
||||
|
||||
@objc public class func failWithMessage(_ message: String, file: FileString, line: UInt) {
|
||||
fail(message, location: SourceLocation(file: file, line: line))
|
||||
}
|
||||
}
|
||||
|
||||
#endif
|
||||
@@ -1,95 +0,0 @@
|
||||
#if canImport(Darwin)
|
||||
import class Foundation.NSObject
|
||||
|
||||
// swiftlint:disable line_length
|
||||
public typealias MatcherBlock = (_ actualExpression: Expression<NSObject>, _ failureMessage: FailureMessage) throws -> Bool
|
||||
public typealias FullMatcherBlock = (_ actualExpression: Expression<NSObject>, _ failureMessage: FailureMessage, _ shouldNotMatch: Bool) throws -> Bool
|
||||
// swiftlint:enable line_length
|
||||
|
||||
@available(*, deprecated, message: "Use NMBPredicate instead")
|
||||
public class NMBObjCMatcher: NSObject, NMBMatcher {
|
||||
// swiftlint:disable identifier_name
|
||||
let _match: MatcherBlock
|
||||
let _doesNotMatch: MatcherBlock
|
||||
// swiftlint:enable identifier_name
|
||||
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 try !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 try matcher(actualExpression, failureMessage, false)
|
||||
}), notMatcher: ({ actualExpression, failureMessage in
|
||||
return try matcher(actualExpression, failureMessage, true)
|
||||
}))
|
||||
}
|
||||
|
||||
private func canMatch(_ actualExpression: Expression<NSObject>, 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: Bool
|
||||
do {
|
||||
result = try _match(expr, failureMessage)
|
||||
} catch let error {
|
||||
failureMessage.stringValue = "unexpected error thrown: <\(error)>"
|
||||
return false
|
||||
}
|
||||
|
||||
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: Bool
|
||||
do {
|
||||
result = try _doesNotMatch(expr, failureMessage)
|
||||
} catch let error {
|
||||
failureMessage.stringValue = "unexpected error thrown: <\(error)>"
|
||||
return false
|
||||
}
|
||||
|
||||
if self.canMatch(Expression(expression: actualBlock, location: location), failureMessage: failureMessage) {
|
||||
return result
|
||||
} else {
|
||||
return false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#endif
|
||||
@@ -1,44 +0,0 @@
|
||||
import Dispatch
|
||||
import class Foundation.NSObject
|
||||
import class Foundation.Thread
|
||||
|
||||
/// "Global" state of Nimble is stored here. Only DSL functions should access / be aware of this
|
||||
/// class' existence
|
||||
internal class NimbleEnvironment: NSObject {
|
||||
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
|
||||
}
|
||||
}
|
||||
|
||||
// swiftlint:disable:next todo
|
||||
// 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
|
||||
|
||||
override init() {
|
||||
let timeoutQueue = DispatchQueue.global(qos: .userInitiated)
|
||||
awaiter = Awaiter(
|
||||
waitLock: AssertionWaitLock(),
|
||||
asyncQueue: .main,
|
||||
timeoutQueue: timeoutQueue
|
||||
)
|
||||
|
||||
super.init()
|
||||
}
|
||||
}
|
||||
@@ -1,91 +0,0 @@
|
||||
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 !SWIFT_PACKAGE
|
||||
/// 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?
|
||||
|
||||
private var stashed_swift_reportFatalErrorsToDebugger: Bool = false
|
||||
|
||||
@objc func testCaseWillStart(_ testCase: XCTestCase) {
|
||||
#if os(macOS) || os(iOS)
|
||||
stashed_swift_reportFatalErrorsToDebugger = _swift_reportFatalErrorsToDebugger
|
||||
_swift_reportFatalErrorsToDebugger = false
|
||||
#endif
|
||||
|
||||
currentTestCase = testCase
|
||||
}
|
||||
|
||||
@objc func testCaseDidFinish(_ testCase: XCTestCase) {
|
||||
currentTestCase = nil
|
||||
|
||||
#if os(macOS) || os(iOS)
|
||||
_swift_reportFatalErrorsToDebugger = stashed_swift_reportFatalErrorsToDebugger
|
||||
#endif
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
func isXCTestAvailable() -> Bool {
|
||||
#if canImport(Darwin)
|
||||
// XCTest is weakly linked and so may not be present
|
||||
return NSClassFromString("XCTestCase") != nil
|
||||
#else
|
||||
return true
|
||||
#endif
|
||||
}
|
||||
|
||||
public func recordFailure(_ message: String, location: SourceLocation) {
|
||||
#if SWIFT_PACKAGE
|
||||
XCTFail("\(message)", file: location.file, line: location.line)
|
||||
#else
|
||||
if let testCase = CurrentTestCaseTracker.sharedInstance.currentTestCase {
|
||||
let line = Int(location.line)
|
||||
testCase.recordFailure(withDescription: message, inFile: location.file, atLine: line, expected: true)
|
||||
} else {
|
||||
let msg = """
|
||||
Attempted to report a test failure to XCTest while no test case was running. The failure was:
|
||||
\"\(message)\"
|
||||
It occurred at: \(location.file):\(location.line)
|
||||
"""
|
||||
NSException(name: .internalInconsistencyException, reason: msg, userInfo: nil).raise()
|
||||
}
|
||||
#endif
|
||||
}
|
||||
-120
@@ -1,120 +0,0 @@
|
||||
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 {
|
||||
// About these kind of lines, `@objc` attributes are only required for Objective-C
|
||||
// support, so that should be conditional on Darwin platforms and normal Xcode builds
|
||||
// (non-SwiftPM builds).
|
||||
#if canImport(Darwin) && !SWIFT_PACKAGE
|
||||
@objc
|
||||
internal class func until(
|
||||
timeout: TimeInterval,
|
||||
file: FileString = #file,
|
||||
line: UInt = #line,
|
||||
action: @escaping (@escaping () -> Void) -> Void) {
|
||||
// Convert TimeInterval to DispatchTimeInterval
|
||||
until(timeout: timeout.dispatchInterval, file: file, line: line, action: action)
|
||||
}
|
||||
#endif
|
||||
|
||||
internal class func until(
|
||||
timeout: DispatchTimeInterval,
|
||||
file: FileString = #file,
|
||||
line: UInt = #line,
|
||||
action: @escaping (@escaping () -> 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: DispatchTimeInterval,
|
||||
file: FileString = #file,
|
||||
line: UInt = #line,
|
||||
action: @escaping (@escaping () -> Void) throws -> Void) {
|
||||
let awaiter = NimbleEnvironment.activeInstance.awaiter
|
||||
let leeway = timeout.divided
|
||||
// swiftlint:disable:next line_length
|
||||
let result = awaiter.performBlock(file: file, line: line) { (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:
|
||||
fail("Waited more than \(timeout.description)", 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 canImport(Darwin) && !SWIFT_PACKAGE
|
||||
@objc(untilFile:line:action:)
|
||||
internal class func until(
|
||||
_ file: FileString = #file,
|
||||
line: UInt = #line,
|
||||
action: @escaping (@escaping () -> Void) -> Void) {
|
||||
until(timeout: .seconds(1), file: file, line: line, action: action)
|
||||
}
|
||||
#else
|
||||
internal class func until(
|
||||
_ file: FileString = #file,
|
||||
line: UInt = #line,
|
||||
action: @escaping (@escaping () -> Void) -> Void) {
|
||||
until(timeout: .seconds(1), file: file, line: line, action: action)
|
||||
}
|
||||
#endif
|
||||
}
|
||||
|
||||
internal func blockedRunLoopErrorMessageFor(_ fnName: String, leeway: DispatchTimeInterval) -> String {
|
||||
// swiftlint:disable:next line_length
|
||||
return "\(fnName) timed out but was unable to run the timeout handler because the main thread is unresponsive (\(leeway.description) 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: DispatchTimeInterval = AsyncDefaults.timeout, file: FileString = #file, line: UInt = #line, action: @escaping (@escaping () -> Void) -> Void) {
|
||||
NMBWait.until(timeout: timeout, file: file, line: line, action: action)
|
||||
}
|
||||
Generated
-104
@@ -1,104 +0,0 @@
|
||||
/// Make an expectation on a given actual value. The value given is lazily evaluated.
|
||||
public func expect<T>(file: FileString = #file, line: UInt = #line, _ expression: @autoclosure @escaping () throws -> T?) -> Expectation<T> {
|
||||
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<T>(file: FileString = #file, line: UInt = #line, _ expression: @autoclosure () -> (() throws -> T)) -> Expectation<T> {
|
||||
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<T>(file: FileString = #file, line: UInt = #line, _ expression: @autoclosure () -> (() throws -> T?)) -> Expectation<T> {
|
||||
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: @autoclosure () -> (() throws -> Void)) -> Expectation<Void> {
|
||||
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 {
|
||||
_nimblePrecondition(name(), message(), file, line)
|
||||
}
|
||||
}
|
||||
|
||||
internal func internalError(_ msg: String, file: FileString = #file, line: UInt = #line) -> Never {
|
||||
// swiftlint:disable line_length
|
||||
fatalError(
|
||||
"""
|
||||
Nimble Bug Found: \(msg) at \(file):\(line).
|
||||
Please file a bug to Nimble: https://github.com/Quick/Nimble/issues with the code snippet that caused this error.
|
||||
"""
|
||||
)
|
||||
// swiftlint:enable line_length
|
||||
}
|
||||
|
||||
#if canImport(Darwin)
|
||||
import class Foundation.NSException
|
||||
import struct Foundation.NSExceptionName
|
||||
|
||||
private func _nimblePrecondition(
|
||||
_ name: String,
|
||||
_ message: String,
|
||||
_ file: StaticString,
|
||||
_ line: UInt
|
||||
) {
|
||||
let exception = NSException(
|
||||
name: NSExceptionName(name),
|
||||
reason: message,
|
||||
userInfo: nil
|
||||
)
|
||||
exception.raise()
|
||||
}
|
||||
#else
|
||||
private func _nimblePrecondition(
|
||||
_ name: String,
|
||||
_ message: String,
|
||||
_ file: StaticString,
|
||||
_ line: UInt
|
||||
) {
|
||||
preconditionFailure("\(name) - \(message)", file: file, line: line)
|
||||
}
|
||||
#endif
|
||||
-136
@@ -1,136 +0,0 @@
|
||||
@available(*, deprecated)
|
||||
internal func expressionDoesNotMatch<T, U>(_ expression: Expression<T>, 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.stringValue = "unexpected error thrown: <\(error)>"
|
||||
return (false, msg)
|
||||
}
|
||||
}
|
||||
|
||||
internal func execute<T>(_ expression: Expression<T>, _ style: ExpectationStyle, _ predicate: Predicate<T>, to: String, description: String?, captureExceptions: Bool = true) -> (Bool, FailureMessage) {
|
||||
func run() -> (Bool, FailureMessage) {
|
||||
let msg = FailureMessage()
|
||||
msg.userDescription = description
|
||||
msg.to = to
|
||||
do {
|
||||
let result = try predicate.satisfies(expression)
|
||||
result.message.update(failureMessage: msg)
|
||||
if msg.actualValue == "" {
|
||||
msg.actualValue = "<\(stringify(try expression.evaluate()))>"
|
||||
}
|
||||
return (result.toBoolean(expectation: style), msg)
|
||||
} catch let error {
|
||||
msg.stringValue = "unexpected error thrown: <\(error)>"
|
||||
return (false, msg)
|
||||
}
|
||||
}
|
||||
|
||||
var result: (Bool, FailureMessage) = (false, FailureMessage())
|
||||
if captureExceptions {
|
||||
let capture = NMBExceptionCapture(handler: ({ exception -> Void in
|
||||
let msg = FailureMessage()
|
||||
msg.stringValue = "unexpected exception raised: \(exception)"
|
||||
result = (false, msg)
|
||||
}), finally: nil)
|
||||
capture.tryBlock {
|
||||
result = run()
|
||||
}
|
||||
} else {
|
||||
result = run()
|
||||
}
|
||||
|
||||
return result
|
||||
}
|
||||
|
||||
public struct Expectation<T> {
|
||||
|
||||
public let expression: Expression<T>
|
||||
|
||||
public init(expression: Expression<T>) {
|
||||
self.expression = expression
|
||||
}
|
||||
|
||||
public func verify(_ pass: Bool, _ message: FailureMessage) {
|
||||
let handler = NimbleEnvironment.activeInstance.assertionHandler
|
||||
handler.assert(pass, message: message, location: expression.location)
|
||||
}
|
||||
|
||||
////////////////// OLD API /////////////////////
|
||||
|
||||
/// DEPRECATED: Tests the actual value using a matcher to match.
|
||||
@available(*, deprecated, message: "Use Predicate instead")
|
||||
@discardableResult
|
||||
public func to<U>(_ matcher: U, description: String? = nil) -> Self
|
||||
where U: Matcher, U.ValueType == T {
|
||||
let (pass, msg) = execute(
|
||||
expression,
|
||||
.toMatch,
|
||||
matcher.predicate,
|
||||
to: "to",
|
||||
description: description,
|
||||
captureExceptions: false
|
||||
)
|
||||
verify(pass, msg)
|
||||
return self
|
||||
}
|
||||
|
||||
/// DEPRECATED: Tests the actual value using a matcher to not match.
|
||||
@available(*, deprecated, message: "Use Predicate instead")
|
||||
@discardableResult
|
||||
public func toNot<U>(_ matcher: U, description: String? = nil) -> Self
|
||||
where U: Matcher, U.ValueType == T {
|
||||
// swiftlint:disable:next line_length
|
||||
let (pass, msg) = expressionDoesNotMatch(expression, matcher: matcher, toNot: "to not", description: description)
|
||||
verify(pass, msg)
|
||||
return self
|
||||
}
|
||||
|
||||
/// DEPRECATED: Tests the actual value using a matcher to not match.
|
||||
///
|
||||
/// Alias to toNot().
|
||||
@available(*, deprecated, message: "Use Predicate instead")
|
||||
@discardableResult
|
||||
public func notTo<U>(_ matcher: U, description: String? = nil) -> Self
|
||||
where U: Matcher, U.ValueType == T {
|
||||
return toNot(matcher, description: description)
|
||||
}
|
||||
|
||||
////////////////// NEW API /////////////////////
|
||||
|
||||
/// Tests the actual value using a matcher to match.
|
||||
@discardableResult
|
||||
public func to(_ predicate: Predicate<T>, description: String? = nil) -> Self {
|
||||
let (pass, msg) = execute(expression, .toMatch, predicate, to: "to", description: description)
|
||||
verify(pass, msg)
|
||||
return self
|
||||
}
|
||||
|
||||
/// Tests the actual value using a matcher to not match.
|
||||
@discardableResult
|
||||
public func toNot(_ predicate: Predicate<T>, description: String? = nil) -> Self {
|
||||
let (pass, msg) = execute(expression, .toNotMatch, predicate, to: "to not", description: description)
|
||||
verify(pass, msg)
|
||||
return self
|
||||
}
|
||||
|
||||
/// Tests the actual value using a matcher to not match.
|
||||
///
|
||||
/// Alias to toNot().
|
||||
@discardableResult
|
||||
public func notTo(_ predicate: Predicate<T>, description: String? = nil) -> Self {
|
||||
return toNot(predicate, description: description)
|
||||
}
|
||||
|
||||
// see:
|
||||
// - `async` for extension
|
||||
// - NMBExpectation for Objective-C interface
|
||||
}
|
||||
-258
@@ -1,258 +0,0 @@
|
||||
public indirect enum ExpectationMessage {
|
||||
// --- Primary Expectations ---
|
||||
/// includes actual value in output ("expected to <message>, got <actual>")
|
||||
case expectedActualValueTo(/* message: */ String)
|
||||
/// uses a custom actual value string in output ("expected to <message>, got <actual>")
|
||||
case expectedCustomValueTo(/* message: */ String, actual: String)
|
||||
/// excludes actual value in output ("expected to <message>")
|
||||
case expectedTo(/* message: */ String)
|
||||
/// allows any free-form message ("<message>")
|
||||
case fail(/* message: */ String)
|
||||
|
||||
// --- Composite Expectations ---
|
||||
// Generally, you'll want the methods, appended(message:) and appended(details:) instead.
|
||||
|
||||
/// Not Fully Implemented Yet.
|
||||
case prepends(/* Prepended Message */ String, ExpectationMessage)
|
||||
|
||||
/// appends after an existing message ("<expectation> (use beNil() to match nils)")
|
||||
case appends(ExpectationMessage, /* Appended Message */ String)
|
||||
|
||||
/// provides long-form multi-line explainations ("<expectation>\n\n<string>")
|
||||
case details(ExpectationMessage, String)
|
||||
|
||||
/// Returns the smallest message after the "expected to" string that summarizes the error.
|
||||
///
|
||||
/// Returns the message part from ExpectationMessage, ignoring all .appends and .details.
|
||||
public var expectedMessage: String {
|
||||
switch self {
|
||||
case let .fail(msg):
|
||||
return msg
|
||||
case let .expectedTo(msg):
|
||||
return msg
|
||||
case let .expectedActualValueTo(msg):
|
||||
return msg
|
||||
case let .expectedCustomValueTo(msg, _):
|
||||
return msg
|
||||
case let .prepends(_, expectation):
|
||||
return expectation.expectedMessage
|
||||
case let .appends(expectation, msg):
|
||||
return "\(expectation.expectedMessage)\(msg)"
|
||||
case let .details(expectation, _):
|
||||
return expectation.expectedMessage
|
||||
}
|
||||
}
|
||||
|
||||
/// Appends a message after the primary expectation message
|
||||
public func appended(message: String) -> ExpectationMessage {
|
||||
switch self {
|
||||
case .fail, .expectedTo, .expectedActualValueTo, .expectedCustomValueTo, .appends, .prepends:
|
||||
return .appends(self, message)
|
||||
case let .details(expectation, msg):
|
||||
return .details(expectation.appended(message: message), msg)
|
||||
}
|
||||
}
|
||||
|
||||
/// Appends a message hinting to use beNil() for when the actual value given was nil.
|
||||
public func appendedBeNilHint() -> ExpectationMessage {
|
||||
return appended(message: " (use beNil() to match nils)")
|
||||
}
|
||||
|
||||
/// Appends a detailed (aka - multiline) message after the primary expectation message
|
||||
/// Detailed messages will be placed after .appended(message:) calls.
|
||||
public func appended(details: String) -> ExpectationMessage {
|
||||
return .details(self, details)
|
||||
}
|
||||
|
||||
internal func visitLeafs(_ f: (ExpectationMessage) -> ExpectationMessage) -> ExpectationMessage {
|
||||
// swiftlint:disable:previous identifier_name
|
||||
switch self {
|
||||
case .fail, .expectedTo, .expectedActualValueTo, .expectedCustomValueTo:
|
||||
return f(self)
|
||||
case let .prepends(msg, expectation):
|
||||
return .prepends(msg, expectation.visitLeafs(f))
|
||||
case let .appends(expectation, msg):
|
||||
return .appends(expectation.visitLeafs(f), msg)
|
||||
case let .details(expectation, msg):
|
||||
return .details(expectation.visitLeafs(f), msg)
|
||||
}
|
||||
}
|
||||
|
||||
/// Replaces a primary expectation with one returned by f. Preserves all composite expectations
|
||||
/// that were built upon it (aka - all appended(message:) and appended(details:).
|
||||
public func replacedExpectation(_ f: @escaping (ExpectationMessage) -> ExpectationMessage) -> ExpectationMessage {
|
||||
// swiftlint:disable:previous identifier_name
|
||||
func walk(_ msg: ExpectationMessage) -> ExpectationMessage {
|
||||
switch msg {
|
||||
case .fail, .expectedTo, .expectedActualValueTo, .expectedCustomValueTo:
|
||||
return f(msg)
|
||||
default:
|
||||
return msg
|
||||
}
|
||||
}
|
||||
return visitLeafs(walk)
|
||||
}
|
||||
|
||||
/// Wraps a primary expectation with text before and after it.
|
||||
/// Alias to prepended(message: before).appended(message: after)
|
||||
public func wrappedExpectation(before: String, after: String) -> ExpectationMessage {
|
||||
return prepended(expectation: before).appended(message: after)
|
||||
}
|
||||
|
||||
/// Prepends a message by modifying the primary expectation
|
||||
public func prepended(expectation message: String) -> ExpectationMessage {
|
||||
func walk(_ msg: ExpectationMessage) -> ExpectationMessage {
|
||||
switch msg {
|
||||
case let .expectedTo(msg):
|
||||
return .expectedTo(message + msg)
|
||||
case let .expectedActualValueTo(msg):
|
||||
return .expectedActualValueTo(message + msg)
|
||||
case let .expectedCustomValueTo(msg, actual):
|
||||
return .expectedCustomValueTo(message + msg, actual: actual)
|
||||
default:
|
||||
return msg.visitLeafs(walk)
|
||||
}
|
||||
}
|
||||
return visitLeafs(walk)
|
||||
}
|
||||
|
||||
// swiftlint:disable:next todo
|
||||
// TODO: test & verify correct behavior
|
||||
internal func prepended(message: String) -> ExpectationMessage {
|
||||
return .prepends(message, self)
|
||||
}
|
||||
|
||||
/// Converts the tree of ExpectationMessages into a final built string.
|
||||
public func toString(actual: String, expected: String = "expected", to: String = "to") -> String {
|
||||
switch self {
|
||||
case let .fail(msg):
|
||||
return msg
|
||||
case let .expectedTo(msg):
|
||||
return "\(expected) \(to) \(msg)"
|
||||
case let .expectedActualValueTo(msg):
|
||||
return "\(expected) \(to) \(msg), got \(actual)"
|
||||
case let .expectedCustomValueTo(msg, actual):
|
||||
return "\(expected) \(to) \(msg), got \(actual)"
|
||||
case let .prepends(msg, expectation):
|
||||
return "\(msg)\(expectation.toString(actual: actual, expected: expected, to: to))"
|
||||
case let .appends(expectation, msg):
|
||||
return "\(expectation.toString(actual: actual, expected: expected, to: to))\(msg)"
|
||||
case let .details(expectation, msg):
|
||||
return "\(expectation.toString(actual: actual, expected: expected, to: to))\n\n\(msg)"
|
||||
}
|
||||
}
|
||||
|
||||
// Backwards compatibility: converts ExpectationMessage tree to FailureMessage
|
||||
internal func update(failureMessage: FailureMessage) {
|
||||
switch self {
|
||||
case let .fail(msg) where !msg.isEmpty:
|
||||
failureMessage.stringValue = msg
|
||||
case .fail:
|
||||
break
|
||||
case let .expectedTo(msg):
|
||||
failureMessage.actualValue = nil
|
||||
failureMessage.postfixMessage = msg
|
||||
case let .expectedActualValueTo(msg):
|
||||
failureMessage.postfixMessage = msg
|
||||
case let .expectedCustomValueTo(msg, actual):
|
||||
failureMessage.postfixMessage = msg
|
||||
failureMessage.actualValue = actual
|
||||
case let .prepends(msg, expectation):
|
||||
expectation.update(failureMessage: failureMessage)
|
||||
if let desc = failureMessage.userDescription {
|
||||
failureMessage.userDescription = "\(msg)\(desc)"
|
||||
} else {
|
||||
failureMessage.userDescription = msg
|
||||
}
|
||||
case let .appends(expectation, msg):
|
||||
expectation.update(failureMessage: failureMessage)
|
||||
failureMessage.appendMessage(msg)
|
||||
case let .details(expectation, msg):
|
||||
expectation.update(failureMessage: failureMessage)
|
||||
failureMessage.appendDetails(msg)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension FailureMessage {
|
||||
internal func toExpectationMessage() -> ExpectationMessage {
|
||||
let defaultMessage = FailureMessage()
|
||||
if expected != defaultMessage.expected || _stringValueOverride != nil {
|
||||
return .fail(stringValue)
|
||||
}
|
||||
|
||||
var message: ExpectationMessage = .fail(userDescription ?? "")
|
||||
if actualValue != "" && actualValue != nil {
|
||||
message = .expectedCustomValueTo(postfixMessage, actual: actualValue ?? "")
|
||||
} else if postfixMessage != defaultMessage.postfixMessage {
|
||||
if actualValue == nil {
|
||||
message = .expectedTo(postfixMessage)
|
||||
} else {
|
||||
message = .expectedActualValueTo(postfixMessage)
|
||||
}
|
||||
}
|
||||
if postfixActual != defaultMessage.postfixActual {
|
||||
message = .appends(message, postfixActual)
|
||||
}
|
||||
if let extended = extendedMessage {
|
||||
message = .details(message, extended)
|
||||
}
|
||||
return message
|
||||
}
|
||||
}
|
||||
|
||||
#if canImport(Darwin)
|
||||
import class Foundation.NSObject
|
||||
|
||||
public class NMBExpectationMessage: NSObject {
|
||||
private let msg: ExpectationMessage
|
||||
|
||||
internal init(swift msg: ExpectationMessage) {
|
||||
self.msg = msg
|
||||
}
|
||||
|
||||
public init(expectedTo message: String) {
|
||||
self.msg = .expectedTo(message)
|
||||
}
|
||||
public init(expectedActualValueTo message: String) {
|
||||
self.msg = .expectedActualValueTo(message)
|
||||
}
|
||||
|
||||
public init(expectedActualValueTo message: String, customActualValue actual: String) {
|
||||
self.msg = .expectedCustomValueTo(message, actual: actual)
|
||||
}
|
||||
|
||||
public init(fail message: String) {
|
||||
self.msg = .fail(message)
|
||||
}
|
||||
|
||||
public init(prepend message: String, child: NMBExpectationMessage) {
|
||||
self.msg = .prepends(message, child.msg)
|
||||
}
|
||||
|
||||
public init(appendedMessage message: String, child: NMBExpectationMessage) {
|
||||
self.msg = .appends(child.msg, message)
|
||||
}
|
||||
|
||||
public init(prependedMessage message: String, child: NMBExpectationMessage) {
|
||||
self.msg = .prepends(message, child.msg)
|
||||
}
|
||||
|
||||
public init(details message: String, child: NMBExpectationMessage) {
|
||||
self.msg = .details(child.msg, message)
|
||||
}
|
||||
|
||||
public func appendedBeNilHint() -> NMBExpectationMessage {
|
||||
return NMBExpectationMessage(swift: msg.appendedBeNilHint())
|
||||
}
|
||||
|
||||
public func toSwift() -> ExpectationMessage { return self.msg }
|
||||
}
|
||||
|
||||
extension ExpectationMessage {
|
||||
func toObjectiveC() -> NMBExpectationMessage {
|
||||
return NMBExpectationMessage(swift: self)
|
||||
}
|
||||
}
|
||||
|
||||
#endif
|
||||
-99
@@ -1,99 +0,0 @@
|
||||
// Memoizes the given closure, only calling the passed
|
||||
// closure once; even if repeat calls to the returned closure
|
||||
internal func memoizedClosure<T>(_ 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<T> {
|
||||
// swiftlint:disable identifier_name
|
||||
internal let _expression: (Bool) throws -> T?
|
||||
internal let _withoutCaching: Bool
|
||||
// swiftlint:enable identifier_name
|
||||
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<U>(_ block: @escaping (T?) throws -> U?) -> Expression<U> {
|
||||
return Expression<U>(
|
||||
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<T> {
|
||||
return Expression(
|
||||
memoizedExpression: self._expression,
|
||||
location: location,
|
||||
withoutCaching: true,
|
||||
isClosure: isClosure
|
||||
)
|
||||
}
|
||||
}
|
||||
-93
@@ -1,93 +0,0 @@
|
||||
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?
|
||||
public var userDescription: String?
|
||||
|
||||
public var stringValue: String {
|
||||
get {
|
||||
if let value = _stringValueOverride {
|
||||
return value
|
||||
} else {
|
||||
return computeStringValue()
|
||||
}
|
||||
}
|
||||
set {
|
||||
_stringValueOverride = newValue
|
||||
}
|
||||
}
|
||||
|
||||
// swiftlint:disable:next identifier_name
|
||||
internal var _stringValueOverride: String?
|
||||
internal var hasOverriddenStringValue: Bool {
|
||||
return _stringValueOverride != nil
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
|
||||
internal func appendMessage(_ msg: String) {
|
||||
if hasOverriddenStringValue {
|
||||
stringValue += "\(msg)"
|
||||
} else if actualValue != nil {
|
||||
postfixActual += msg
|
||||
} else {
|
||||
postfixMessage += msg
|
||||
}
|
||||
}
|
||||
|
||||
internal func appendDetails(_ msg: String) {
|
||||
if hasOverriddenStringValue {
|
||||
if let desc = userDescription {
|
||||
stringValue = "\(desc)\n\(stringValue)"
|
||||
}
|
||||
stringValue += "\n\(msg)"
|
||||
} else {
|
||||
if let desc = userDescription {
|
||||
userDescription = desc
|
||||
}
|
||||
extendedMessage = msg
|
||||
}
|
||||
}
|
||||
}
|
||||
-123
@@ -1,123 +0,0 @@
|
||||
public func allPass<S: Sequence>(
|
||||
_ passFunc: @escaping (S.Element?) throws -> Bool
|
||||
) -> Predicate<S> {
|
||||
let matcher = Predicate.simpleNilable("pass a condition") { actualExpression in
|
||||
return PredicateStatus(bool: try passFunc(try actualExpression.evaluate()))
|
||||
}
|
||||
return createPredicate(matcher)
|
||||
}
|
||||
|
||||
public func allPass<S: Sequence>(
|
||||
_ passName: String,
|
||||
_ passFunc: @escaping (S.Element?) throws -> Bool
|
||||
) -> Predicate<S> {
|
||||
let matcher = Predicate.simpleNilable(passName) { actualExpression in
|
||||
return PredicateStatus(bool: try passFunc(try actualExpression.evaluate()))
|
||||
}
|
||||
return createPredicate(matcher)
|
||||
}
|
||||
|
||||
@available(*, deprecated, message: "Use Predicate instead")
|
||||
public func allPass<S: Sequence, M: Matcher>(_ elementMatcher: M) -> Predicate<S> where S.Element == M.ValueType {
|
||||
return createPredicate(elementMatcher.predicate)
|
||||
}
|
||||
|
||||
public func allPass<S: Sequence>(_ elementPredicate: Predicate<S.Element>) -> Predicate<S> {
|
||||
return createPredicate(elementPredicate)
|
||||
}
|
||||
|
||||
private func createPredicate<S: Sequence>(_ elementMatcher: Predicate<S.Element>) -> Predicate<S> {
|
||||
return Predicate { actualExpression in
|
||||
guard let actualValue = try actualExpression.evaluate() else {
|
||||
return PredicateResult(
|
||||
status: .fail,
|
||||
message: .appends(.expectedTo("all pass"), " (use beNil() to match nils)")
|
||||
)
|
||||
}
|
||||
|
||||
var failure: ExpectationMessage = .expectedTo("all pass")
|
||||
for currentElement in actualValue {
|
||||
let exp = Expression(
|
||||
expression: {currentElement}, location: actualExpression.location)
|
||||
let predicateResult = try elementMatcher.satisfies(exp)
|
||||
if predicateResult.status == .matches {
|
||||
failure = predicateResult.message.prepended(expectation: "all ")
|
||||
} else {
|
||||
failure = predicateResult.message
|
||||
.replacedExpectation({ .expectedTo($0.expectedMessage) })
|
||||
.wrappedExpectation(
|
||||
before: "all ",
|
||||
after: ", but failed first at element <\(stringify(currentElement))>"
|
||||
+ " in <\(stringify(actualValue))>"
|
||||
)
|
||||
return PredicateResult(status: .doesNotMatch, message: failure)
|
||||
}
|
||||
}
|
||||
failure = failure.replacedExpectation({ expectation in
|
||||
return .expectedTo(expectation.expectedMessage)
|
||||
})
|
||||
return PredicateResult(status: .matches, message: failure)
|
||||
}
|
||||
}
|
||||
|
||||
#if canImport(Darwin)
|
||||
import class Foundation.NSObject
|
||||
import struct Foundation.NSFastEnumerationIterator
|
||||
import protocol Foundation.NSFastEnumeration
|
||||
|
||||
extension NMBPredicate {
|
||||
@objc public class func allPassMatcher(_ matcher: NMBMatcher) -> NMBPredicate {
|
||||
return NMBPredicate { actualExpression in
|
||||
let location = actualExpression.location
|
||||
let actualValue = try actualExpression.evaluate()
|
||||
var nsObjects = [NSObject]()
|
||||
|
||||
var collectionIsUsable = true
|
||||
if let value = actualValue as? NSFastEnumeration {
|
||||
var 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 {
|
||||
return NMBPredicateResult(
|
||||
status: NMBPredicateStatus.fail,
|
||||
message: NMBExpectationMessage(
|
||||
// swiftlint:disable:next line_length
|
||||
fail: "allPass can only be used with types which implement NSFastEnumeration (NSArray, NSSet, ...), and whose elements subclass NSObject, got <\(actualValue?.description ?? "nil")>"
|
||||
)
|
||||
)
|
||||
}
|
||||
|
||||
let expr = Expression(expression: ({ nsObjects }), location: location)
|
||||
let pred: Predicate<[NSObject]> = createPredicate(Predicate { expr in
|
||||
if let predicate = matcher as? NMBPredicate {
|
||||
return predicate.satisfies(({ try expr.evaluate() }), location: expr.location).toSwift()
|
||||
} else {
|
||||
let failureMessage = FailureMessage()
|
||||
let result = matcher.matches(
|
||||
// swiftlint:disable:next force_try
|
||||
({ try! expr.evaluate() }),
|
||||
failureMessage: failureMessage,
|
||||
location: expr.location
|
||||
)
|
||||
let expectationMsg = failureMessage.toExpectationMessage()
|
||||
return PredicateResult(
|
||||
bool: result,
|
||||
message: expectationMsg
|
||||
)
|
||||
}
|
||||
})
|
||||
return try pred.satisfies(expr).toObjectiveC()
|
||||
}
|
||||
}
|
||||
}
|
||||
#endif
|
||||
-189
@@ -1,189 +0,0 @@
|
||||
import Foundation
|
||||
import Dispatch
|
||||
|
||||
/// 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: DispatchTimeInterval = .seconds(1)
|
||||
public static var pollInterval: DispatchTimeInterval = .milliseconds(10)
|
||||
}
|
||||
|
||||
extension AsyncDefaults {
|
||||
@available(*, unavailable, renamed: "timeout")
|
||||
public static var Timeout: TimeInterval = 1
|
||||
@available(*, unavailable, renamed: "pollInterval")
|
||||
public static var PollInterval: TimeInterval = 0.01
|
||||
}
|
||||
|
||||
private func async<T>(style: ExpectationStyle, predicate: Predicate<T>, timeout: DispatchTimeInterval, poll: DispatchTimeInterval, fnName: String) -> Predicate<T> {
|
||||
return Predicate { actualExpression in
|
||||
let uncachedExpression = actualExpression.withoutCaching()
|
||||
let fnName = "expect(...).\(fnName)(...)"
|
||||
var lastPredicateResult: PredicateResult?
|
||||
let result = pollBlock(
|
||||
pollInterval: poll,
|
||||
timeoutInterval: timeout,
|
||||
file: actualExpression.location.file,
|
||||
line: actualExpression.location.line,
|
||||
fnName: fnName) {
|
||||
lastPredicateResult = try predicate.satisfies(uncachedExpression)
|
||||
return lastPredicateResult!.toBoolean(expectation: style)
|
||||
}
|
||||
switch result {
|
||||
case .completed: return lastPredicateResult!
|
||||
case .timedOut:
|
||||
let message = lastPredicateResult?.message ?? .fail("timed out before returning a value")
|
||||
return PredicateResult(status: .fail, message: message)
|
||||
case let .errorThrown(error):
|
||||
return PredicateResult(status: .fail, message: .fail("unexpected error thrown: <\(error)>"))
|
||||
case let .raisedException(exception):
|
||||
return PredicateResult(status: .fail, message: .fail("unexpected exception raised: \(exception)"))
|
||||
case .blockedRunLoop:
|
||||
// swiftlint:disable:next line_length
|
||||
let message = lastPredicateResult?.message.appended(message: " (timed out, but main run loop was unresponsive).") ??
|
||||
.fail("main run loop was unresponsive")
|
||||
return PredicateResult(status: .fail, message: message)
|
||||
case .incomplete:
|
||||
internalError("Reached .incomplete state for \(fnName)(...).")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private let toEventuallyRequiresClosureError = FailureMessage(
|
||||
stringValue: """
|
||||
expect(...).toEventually(...) requires an explicit closure (eg - expect { ... }.toEventually(...) )
|
||||
Swift 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(_ predicate: Predicate<T>, timeout: DispatchTimeInterval = AsyncDefaults.timeout, pollInterval: DispatchTimeInterval = AsyncDefaults.pollInterval, description: String? = nil) {
|
||||
nimblePrecondition(expression.isClosure, "NimbleInternalError", toEventuallyRequiresClosureError.stringValue)
|
||||
|
||||
let (pass, msg) = execute(
|
||||
expression,
|
||||
.toMatch,
|
||||
async(style: .toMatch, predicate: predicate, timeout: timeout, poll: pollInterval, fnName: "toEventually"),
|
||||
to: "to eventually",
|
||||
description: description,
|
||||
captureExceptions: false
|
||||
)
|
||||
verify(pass, msg)
|
||||
}
|
||||
|
||||
/// 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(_ predicate: Predicate<T>, timeout: DispatchTimeInterval = AsyncDefaults.timeout, pollInterval: DispatchTimeInterval = AsyncDefaults.pollInterval, description: String? = nil) {
|
||||
nimblePrecondition(expression.isClosure, "NimbleInternalError", toEventuallyRequiresClosureError.stringValue)
|
||||
|
||||
let (pass, msg) = execute(
|
||||
expression,
|
||||
.toNotMatch,
|
||||
async(
|
||||
style: .toNotMatch,
|
||||
predicate: predicate,
|
||||
timeout: timeout,
|
||||
poll: pollInterval,
|
||||
fnName: "toEventuallyNot"
|
||||
),
|
||||
to: "to eventually not",
|
||||
description: description,
|
||||
captureExceptions: false
|
||||
)
|
||||
verify(pass, msg)
|
||||
}
|
||||
|
||||
/// 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(_ predicate: Predicate<T>, timeout: DispatchTimeInterval = AsyncDefaults.timeout, pollInterval: DispatchTimeInterval = AsyncDefaults.pollInterval, description: String? = nil) {
|
||||
return toEventuallyNot(predicate, timeout: timeout, pollInterval: pollInterval, description: description)
|
||||
}
|
||||
}
|
||||
|
||||
@available(*, deprecated, message: "Use Predicate instead")
|
||||
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<U>(_ matcher: U, timeout: DispatchTimeInterval = AsyncDefaults.timeout, pollInterval: DispatchTimeInterval = AsyncDefaults.pollInterval, description: String? = nil)
|
||||
where U: Matcher, U.ValueType == T {
|
||||
if expression.isClosure {
|
||||
let (pass, msg) = execute(
|
||||
expression,
|
||||
.toMatch,
|
||||
async(
|
||||
style: .toMatch,
|
||||
predicate: matcher.predicate,
|
||||
timeout: timeout,
|
||||
poll: pollInterval,
|
||||
fnName: "toEventually"
|
||||
),
|
||||
to: "to eventually",
|
||||
description: description,
|
||||
captureExceptions: false
|
||||
)
|
||||
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<U>(_ matcher: U, timeout: DispatchTimeInterval = AsyncDefaults.timeout, pollInterval: DispatchTimeInterval = AsyncDefaults.pollInterval, description: String? = nil)
|
||||
where U: Matcher, U.ValueType == T {
|
||||
if expression.isClosure {
|
||||
let (pass, msg) = expressionDoesNotMatch(
|
||||
expression,
|
||||
matcher: async(
|
||||
style: .toNotMatch,
|
||||
predicate: matcher.predicate,
|
||||
timeout: timeout,
|
||||
poll: pollInterval,
|
||||
fnName: "toEventuallyNot"
|
||||
),
|
||||
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<U>(_ matcher: U, timeout: DispatchTimeInterval = AsyncDefaults.timeout, pollInterval: DispatchTimeInterval = AsyncDefaults.pollInterval, description: String? = nil)
|
||||
where U: Matcher, U.ValueType == T {
|
||||
return toEventuallyNot(matcher, timeout: timeout, pollInterval: pollInterval, description: description)
|
||||
}
|
||||
}
|
||||
-67
@@ -1,67 +0,0 @@
|
||||
private func matcherMessage<T>(forType expectedType: T.Type) -> String {
|
||||
return "be a kind of \(String(describing: expectedType))"
|
||||
}
|
||||
private func matcherMessage(forClass expectedClass: AnyClass) -> String {
|
||||
return "be a kind of \(String(describing: expectedClass))"
|
||||
}
|
||||
|
||||
/// A Nimble matcher that succeeds when the actual value is an instance of the given class.
|
||||
public func beAKindOf<T>(_ expectedType: T.Type) -> Predicate<Any> {
|
||||
return Predicate.define { actualExpression in
|
||||
let message: ExpectationMessage
|
||||
|
||||
let instance = try actualExpression.evaluate()
|
||||
guard let validInstance = instance else {
|
||||
message = .expectedCustomValueTo(matcherMessage(forType: expectedType), actual: "<nil>")
|
||||
return PredicateResult(status: .fail, message: message)
|
||||
}
|
||||
message = .expectedCustomValueTo(
|
||||
"be a kind of \(String(describing: expectedType))",
|
||||
actual: "<\(String(describing: type(of: validInstance))) instance>"
|
||||
)
|
||||
|
||||
return PredicateResult(
|
||||
bool: validInstance is T,
|
||||
message: message
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
#if canImport(Darwin)
|
||||
import class Foundation.NSObject
|
||||
|
||||
/// 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) -> Predicate<NSObject> {
|
||||
return Predicate.define { actualExpression in
|
||||
let message: ExpectationMessage
|
||||
let status: PredicateStatus
|
||||
|
||||
let instance = try actualExpression.evaluate()
|
||||
if let validInstance = instance {
|
||||
status = PredicateStatus(bool: instance != nil && instance!.isKind(of: expectedClass))
|
||||
message = .expectedCustomValueTo(
|
||||
matcherMessage(forClass: expectedClass),
|
||||
actual: "<\(String(describing: type(of: validInstance))) instance>"
|
||||
)
|
||||
} else {
|
||||
status = .fail
|
||||
message = .expectedCustomValueTo(
|
||||
matcherMessage(forClass: expectedClass),
|
||||
actual: "<nil>"
|
||||
)
|
||||
}
|
||||
|
||||
return PredicateResult(status: status, message: message)
|
||||
}
|
||||
}
|
||||
|
||||
extension NMBPredicate {
|
||||
@objc public class func beAKindOfMatcher(_ expected: AnyClass) -> NMBPredicate {
|
||||
return NMBPredicate { actualExpression in
|
||||
return try beAKindOf(expected).satisfies(actualExpression).toObjectiveC()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#endif
|
||||
@@ -1,56 +0,0 @@
|
||||
import Foundation
|
||||
|
||||
/// A Nimble matcher that succeeds when the actual value is an _exact_ instance of the given class.
|
||||
public func beAnInstanceOf<T>(_ expectedType: T.Type) -> Predicate<Any> {
|
||||
let errorMessage = "be an instance of \(String(describing: expectedType))"
|
||||
return Predicate.define { actualExpression in
|
||||
let instance = try actualExpression.evaluate()
|
||||
guard let validInstance = instance else {
|
||||
return PredicateResult(
|
||||
status: .doesNotMatch,
|
||||
message: .expectedActualValueTo(errorMessage)
|
||||
)
|
||||
}
|
||||
|
||||
let actualString = "<\(String(describing: type(of: validInstance))) instance>"
|
||||
|
||||
return PredicateResult(
|
||||
status: PredicateStatus(bool: type(of: validInstance) == expectedType),
|
||||
message: .expectedCustomValueTo(errorMessage, actual: actualString)
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/// 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) -> Predicate<NSObject> {
|
||||
let errorMessage = "be an instance of \(String(describing: expectedClass))"
|
||||
return Predicate.define { actualExpression in
|
||||
let instance = try actualExpression.evaluate()
|
||||
let actualString: String
|
||||
if let validInstance = instance {
|
||||
actualString = "<\(String(describing: type(of: validInstance))) instance>"
|
||||
} else {
|
||||
actualString = "<nil>"
|
||||
}
|
||||
#if canImport(Darwin)
|
||||
let matches = instance != nil && instance!.isMember(of: expectedClass)
|
||||
#else
|
||||
let matches = instance != nil && type(of: instance!) == expectedClass
|
||||
#endif
|
||||
return PredicateResult(
|
||||
status: PredicateStatus(bool: matches),
|
||||
message: .expectedCustomValueTo(errorMessage, actual: actualString)
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
#if canImport(Darwin)
|
||||
extension NMBPredicate {
|
||||
@objc public class func beAnInstanceOfMatcher(_ expected: AnyClass) -> NMBPredicate {
|
||||
return NMBPredicate { actualExpression in
|
||||
return try beAnInstanceOf(expected).satisfies(actualExpression).toObjectiveC()
|
||||
}
|
||||
}
|
||||
}
|
||||
#endif
|
||||
-120
@@ -1,120 +0,0 @@
|
||||
import Foundation
|
||||
|
||||
// swiftlint:disable:next identifier_name
|
||||
public let DefaultDelta = 0.0001
|
||||
|
||||
internal func isCloseTo(_ actualValue: NMBDoubleConvertible?,
|
||||
expectedValue: NMBDoubleConvertible,
|
||||
delta: Double)
|
||||
-> PredicateResult {
|
||||
let errorMessage = "be close to <\(stringify(expectedValue))> (within \(stringify(delta)))"
|
||||
return PredicateResult(
|
||||
bool: actualValue != nil &&
|
||||
abs(actualValue!.doubleValue - expectedValue.doubleValue) < delta,
|
||||
message: .expectedCustomValueTo(errorMessage, actual: "<\(stringify(actualValue))>")
|
||||
)
|
||||
}
|
||||
|
||||
/// 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<Value: NMBDoubleConvertible>(_ expectedValue: Value, within delta: Double = DefaultDelta) -> Predicate<Value> {
|
||||
return Predicate.define { actualExpression in
|
||||
return isCloseTo(try actualExpression.evaluate(), expectedValue: expectedValue, delta: delta)
|
||||
}
|
||||
}
|
||||
|
||||
private func beCloseTo(_ expectedValue: NMBDoubleConvertible, within delta: Double = DefaultDelta) -> Predicate<NMBDoubleConvertible> {
|
||||
return Predicate.define { actualExpression in
|
||||
return isCloseTo(try actualExpression.evaluate(), expectedValue: expectedValue, delta: delta)
|
||||
}
|
||||
}
|
||||
|
||||
#if canImport(Darwin)
|
||||
public class NMBObjCBeCloseToPredicate: NMBPredicate {
|
||||
private let _expected: NSNumber
|
||||
|
||||
fileprivate init(expected: NSNumber, within: CDouble) {
|
||||
_expected = expected
|
||||
|
||||
let predicate = beCloseTo(expected, within: within)
|
||||
let predicateBlock: PredicateBlock = { actualExpression in
|
||||
let expr = actualExpression.cast { $0 as? NMBDoubleConvertible }
|
||||
return try predicate.satisfies(expr).toObjectiveC()
|
||||
}
|
||||
super.init(predicate: predicateBlock)
|
||||
}
|
||||
|
||||
@objc public var within: (CDouble) -> NMBObjCBeCloseToPredicate {
|
||||
let expected = _expected
|
||||
return { delta in
|
||||
return NMBObjCBeCloseToPredicate(expected: expected, within: delta)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension NMBPredicate {
|
||||
@objc public class func beCloseToMatcher(_ expected: NSNumber, within: CDouble) -> NMBObjCBeCloseToPredicate {
|
||||
return NMBObjCBeCloseToPredicate(expected: expected, within: within)
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
public func beCloseTo(_ expectedValues: [Double], within delta: Double = DefaultDelta) -> Predicate<[Double]> {
|
||||
let errorMessage = "be close to <\(stringify(expectedValues))> (each within \(stringify(delta)))"
|
||||
return Predicate.simple(errorMessage) { actualExpression in
|
||||
if let actual = try actualExpression.evaluate() {
|
||||
if actual.count != expectedValues.count {
|
||||
return .doesNotMatch
|
||||
} else {
|
||||
for (index, actualItem) in actual.enumerated() {
|
||||
if fabs(actualItem - expectedValues[index]) > delta {
|
||||
return .doesNotMatch
|
||||
}
|
||||
}
|
||||
return .matches
|
||||
}
|
||||
}
|
||||
return .doesNotMatch
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Operators
|
||||
|
||||
infix operator ≈ : ComparisonPrecedence
|
||||
|
||||
extension Expectation where T == [Double] {
|
||||
// swiftlint:disable:next identifier_name
|
||||
public static func ≈(lhs: Expectation, rhs: [Double]) {
|
||||
lhs.to(beCloseTo(rhs))
|
||||
}
|
||||
}
|
||||
|
||||
extension Expectation where T == NMBDoubleConvertible {
|
||||
// swiftlint:disable:next identifier_name
|
||||
public static func ≈(lhs: Expectation, rhs: NMBDoubleConvertible) {
|
||||
lhs.to(beCloseTo(rhs))
|
||||
}
|
||||
|
||||
// swiftlint:disable:next identifier_name
|
||||
public static func ≈(lhs: Expectation, rhs: (expected: NMBDoubleConvertible, delta: Double)) {
|
||||
lhs.to(beCloseTo(rhs.expected, within: rhs.delta))
|
||||
}
|
||||
|
||||
public static 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
|
||||
// swiftlint:disable:next identifier_name
|
||||
public func ±(lhs: NMBDoubleConvertible, rhs: Double) -> (expected: NMBDoubleConvertible, delta: Double) {
|
||||
return (expected: lhs, delta: rhs)
|
||||
}
|
||||
-111
@@ -1,111 +0,0 @@
|
||||
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<S: Sequence>() -> Predicate<S> {
|
||||
return Predicate.simple("be empty") { actualExpression in
|
||||
guard let actual = try actualExpression.evaluate() else { return .fail }
|
||||
|
||||
var generator = actual.makeIterator()
|
||||
return PredicateStatus(bool: 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<S: SetAlgebra>() -> Predicate<S> {
|
||||
return Predicate.simple("be empty") { actualExpression in
|
||||
guard let actual = try actualExpression.evaluate() else { return .fail }
|
||||
return PredicateStatus(bool: actual.isEmpty)
|
||||
}
|
||||
}
|
||||
|
||||
/// 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<S: Sequence & SetAlgebra>() -> Predicate<S> {
|
||||
return Predicate.simple("be empty") { actualExpression in
|
||||
guard let actual = try actualExpression.evaluate() else { return .fail }
|
||||
return PredicateStatus(bool: actual.isEmpty)
|
||||
}
|
||||
}
|
||||
|
||||
/// 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() -> Predicate<String> {
|
||||
return Predicate.simple("be empty") { actualExpression in
|
||||
guard let actual = try actualExpression.evaluate() else { return .fail }
|
||||
return PredicateStatus(bool: actual.isEmpty)
|
||||
}
|
||||
}
|
||||
|
||||
/// 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() -> Predicate<NSString> {
|
||||
return Predicate.simple("be empty") { actualExpression in
|
||||
guard let actual = try actualExpression.evaluate() else { return .fail }
|
||||
return PredicateStatus(bool: actual.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() -> Predicate<NSDictionary> {
|
||||
return Predicate.simple("be empty") { actualExpression in
|
||||
guard let actual = try actualExpression.evaluate() else { return .fail }
|
||||
return PredicateStatus(bool: actual.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() -> Predicate<NSArray> {
|
||||
return Predicate.simple("be empty") { actualExpression in
|
||||
guard let actual = try actualExpression.evaluate() else { return .fail }
|
||||
return PredicateStatus(bool: actual.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() -> Predicate<NMBCollection> {
|
||||
return Predicate.simple("be empty") { actualExpression in
|
||||
guard let actual = try actualExpression.evaluate() else { return .fail }
|
||||
return PredicateStatus(bool: actual.count == 0)
|
||||
}
|
||||
}
|
||||
|
||||
#if canImport(Darwin)
|
||||
extension NMBPredicate {
|
||||
@objc public class func beEmptyMatcher() -> NMBPredicate {
|
||||
return NMBPredicate { actualExpression in
|
||||
let location = actualExpression.location
|
||||
let actualValue = try actualExpression.evaluate()
|
||||
|
||||
if let value = actualValue as? NMBCollection {
|
||||
let expr = Expression(expression: ({ value }), location: location)
|
||||
return try beEmpty().satisfies(expr).toObjectiveC()
|
||||
} else if let value = actualValue as? NSString {
|
||||
let expr = Expression(expression: ({ value }), location: location)
|
||||
return try beEmpty().satisfies(expr).toObjectiveC()
|
||||
} else if let actualValue = actualValue {
|
||||
// swiftlint:disable:next line_length
|
||||
let badTypeErrorMsg = "be empty (only works for NSArrays, NSSets, NSIndexSets, NSDictionaries, NSHashTables, and NSStrings)"
|
||||
return NMBPredicateResult(
|
||||
status: NMBPredicateStatus.fail,
|
||||
message: NMBExpectationMessage(
|
||||
expectedActualValueTo: badTypeErrorMsg,
|
||||
customActualValue: "\(String(describing: type(of: actualValue))) type"
|
||||
)
|
||||
)
|
||||
}
|
||||
return NMBPredicateResult(
|
||||
status: NMBPredicateStatus.fail,
|
||||
message: NMBExpectationMessage(expectedActualValueTo: "be empty").appendedBeNilHint()
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
#endif
|
||||
@@ -1,41 +0,0 @@
|
||||
/// A Nimble matcher that succeeds when the actual value is greater than the expected value.
|
||||
public func beGreaterThan<T: Comparable>(_ expectedValue: T?) -> Predicate<T> {
|
||||
let errorMessage = "be greater than <\(stringify(expectedValue))>"
|
||||
return Predicate.simple(errorMessage) { actualExpression in
|
||||
guard let actual = try actualExpression.evaluate(), let expected = expectedValue else { return .fail }
|
||||
|
||||
return PredicateStatus(bool: actual > expected)
|
||||
}
|
||||
}
|
||||
|
||||
public func ><T: Comparable>(lhs: Expectation<T>, rhs: T) {
|
||||
lhs.to(beGreaterThan(rhs))
|
||||
}
|
||||
|
||||
#if canImport(Darwin)
|
||||
import enum Foundation.ComparisonResult
|
||||
|
||||
/// A Nimble matcher that succeeds when the actual value is greater than the expected value.
|
||||
public func beGreaterThan(_ expectedValue: NMBComparable?) -> Predicate<NMBComparable> {
|
||||
let errorMessage = "be greater than <\(stringify(expectedValue))>"
|
||||
return Predicate.simple(errorMessage) { actualExpression in
|
||||
let actualValue = try actualExpression.evaluate()
|
||||
let matches = actualValue != nil
|
||||
&& actualValue!.NMB_compare(expectedValue) == ComparisonResult.orderedDescending
|
||||
return PredicateStatus(bool: matches)
|
||||
}
|
||||
}
|
||||
|
||||
public func > (lhs: Expectation<NMBComparable>, rhs: NMBComparable?) {
|
||||
lhs.to(beGreaterThan(rhs))
|
||||
}
|
||||
|
||||
extension NMBPredicate {
|
||||
@objc public class func beGreaterThanMatcher(_ expected: NMBComparable?) -> NMBPredicate {
|
||||
return NMBPredicate { actualExpression in
|
||||
let expr = actualExpression.cast { $0 as? NMBComparable }
|
||||
return try beGreaterThan(expected).satisfies(expr).toObjectiveC()
|
||||
}
|
||||
}
|
||||
}
|
||||
#endif
|
||||
@@ -1,42 +0,0 @@
|
||||
/// A Nimble matcher that succeeds when the actual value is greater than
|
||||
/// or equal to the expected value.
|
||||
public func beGreaterThanOrEqualTo<T: Comparable>(_ expectedValue: T?) -> Predicate<T> {
|
||||
let message = "be greater than or equal to <\(stringify(expectedValue))>"
|
||||
return Predicate.simple(message) { actualExpression in
|
||||
guard let actual = try actualExpression.evaluate(), let expected = expectedValue else { return .fail }
|
||||
|
||||
return PredicateStatus(bool: actual >= expected)
|
||||
}
|
||||
}
|
||||
|
||||
public func >=<T: Comparable>(lhs: Expectation<T>, rhs: T) {
|
||||
lhs.to(beGreaterThanOrEqualTo(rhs))
|
||||
}
|
||||
|
||||
#if canImport(Darwin)
|
||||
import enum Foundation.ComparisonResult
|
||||
|
||||
/// A Nimble matcher that succeeds when the actual value is greater than
|
||||
/// or equal to the expected value.
|
||||
public func beGreaterThanOrEqualTo<T: NMBComparable>(_ expectedValue: T?) -> Predicate<T> {
|
||||
let message = "be greater than or equal to <\(stringify(expectedValue))>"
|
||||
return Predicate.simple(message) { actualExpression in
|
||||
let actualValue = try actualExpression.evaluate()
|
||||
let matches = actualValue != nil && actualValue!.NMB_compare(expectedValue) != ComparisonResult.orderedAscending
|
||||
return PredicateStatus(bool: matches)
|
||||
}
|
||||
}
|
||||
|
||||
public func >=<T: NMBComparable>(lhs: Expectation<T>, rhs: T) {
|
||||
lhs.to(beGreaterThanOrEqualTo(rhs))
|
||||
}
|
||||
|
||||
extension NMBPredicate {
|
||||
@objc public class func beGreaterThanOrEqualToMatcher(_ expected: NMBComparable?) -> NMBPredicate {
|
||||
return NMBPredicate { actualExpression in
|
||||
let expr = actualExpression.cast { $0 as? NMBComparable }
|
||||
return try beGreaterThanOrEqualTo(expected).satisfies(expr).toObjectiveC()
|
||||
}
|
||||
}
|
||||
}
|
||||
#endif
|
||||
@@ -1,47 +0,0 @@
|
||||
/// A Nimble matcher that succeeds when the actual value is the same instance
|
||||
/// as the expected instance.
|
||||
public func beIdenticalTo(_ expected: Any?) -> Predicate<Any> {
|
||||
return Predicate.define { actualExpression in
|
||||
let actual = try actualExpression.evaluate() as AnyObject?
|
||||
|
||||
let bool = actual === (expected as AnyObject?) && actual !== nil
|
||||
return PredicateResult(
|
||||
bool: bool,
|
||||
message: .expectedCustomValueTo(
|
||||
"be identical to \(identityAsString(expected))",
|
||||
actual: "\(identityAsString(actual))"
|
||||
)
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
extension Expectation where T == Any {
|
||||
public static func === (lhs: Expectation, rhs: Any?) {
|
||||
lhs.to(beIdenticalTo(rhs))
|
||||
}
|
||||
|
||||
public static 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?) -> Predicate<Any> {
|
||||
return beIdenticalTo(expected)
|
||||
}
|
||||
|
||||
#if canImport(Darwin)
|
||||
import class Foundation.NSObject
|
||||
|
||||
extension NMBPredicate {
|
||||
@objc public class func beIdenticalToMatcher(_ expected: NSObject?) -> NMBPredicate {
|
||||
return NMBPredicate { actualExpression in
|
||||
let aExpr = actualExpression.cast { $0 as Any? }
|
||||
return try beIdenticalTo(expected).satisfies(aExpr).toObjectiveC()
|
||||
}
|
||||
}
|
||||
}
|
||||
#endif
|
||||
@@ -1,40 +0,0 @@
|
||||
/// A Nimble matcher that succeeds when the actual value is less than the expected value.
|
||||
public func beLessThan<T: Comparable>(_ expectedValue: T?) -> Predicate<T> {
|
||||
let message = "be less than <\(stringify(expectedValue))>"
|
||||
return Predicate.simple(message) { actualExpression in
|
||||
guard let actual = try actualExpression.evaluate(), let expected = expectedValue else { return .fail }
|
||||
|
||||
return PredicateStatus(bool: actual < expected)
|
||||
}
|
||||
}
|
||||
|
||||
public func <<T: Comparable>(lhs: Expectation<T>, rhs: T) {
|
||||
lhs.to(beLessThan(rhs))
|
||||
}
|
||||
|
||||
#if canImport(Darwin)
|
||||
import enum Foundation.ComparisonResult
|
||||
|
||||
/// A Nimble matcher that succeeds when the actual value is less than the expected value.
|
||||
public func beLessThan(_ expectedValue: NMBComparable?) -> Predicate<NMBComparable> {
|
||||
let message = "be less than <\(stringify(expectedValue))>"
|
||||
return Predicate.simple(message) { actualExpression in
|
||||
let actualValue = try actualExpression.evaluate()
|
||||
let matches = actualValue != nil && actualValue!.NMB_compare(expectedValue) == ComparisonResult.orderedAscending
|
||||
return PredicateStatus(bool: matches)
|
||||
}
|
||||
}
|
||||
|
||||
public func < (lhs: Expectation<NMBComparable>, rhs: NMBComparable?) {
|
||||
lhs.to(beLessThan(rhs))
|
||||
}
|
||||
|
||||
extension NMBPredicate {
|
||||
@objc public class func beLessThanMatcher(_ expected: NMBComparable?) -> NMBPredicate {
|
||||
return NMBPredicate { actualExpression in
|
||||
let expr = actualExpression.cast { $0 as? NMBComparable }
|
||||
return try beLessThan(expected).satisfies(expr).toObjectiveC()
|
||||
}
|
||||
}
|
||||
}
|
||||
#endif
|
||||
@@ -1,40 +0,0 @@
|
||||
/// A Nimble matcher that succeeds when the actual value is less than
|
||||
/// or equal to the expected value.
|
||||
public func beLessThanOrEqualTo<T: Comparable>(_ expectedValue: T?) -> Predicate<T> {
|
||||
return Predicate.simple("be less than or equal to <\(stringify(expectedValue))>") { actualExpression in
|
||||
guard let actual = try actualExpression.evaluate(), let expected = expectedValue else { return .fail }
|
||||
|
||||
return PredicateStatus(bool: actual <= expected)
|
||||
}
|
||||
}
|
||||
|
||||
public func <=<T: Comparable>(lhs: Expectation<T>, rhs: T) {
|
||||
lhs.to(beLessThanOrEqualTo(rhs))
|
||||
}
|
||||
|
||||
#if canImport(Darwin)
|
||||
import enum Foundation.ComparisonResult
|
||||
|
||||
/// A Nimble matcher that succeeds when the actual value is less than
|
||||
/// or equal to the expected value.
|
||||
public func beLessThanOrEqualTo<T: NMBComparable>(_ expectedValue: T?) -> Predicate<T> {
|
||||
return Predicate.simple("be less than or equal to <\(stringify(expectedValue))>") { actualExpression in
|
||||
let actualValue = try actualExpression.evaluate()
|
||||
let matches = actualValue.map { $0.NMB_compare(expectedValue) != .orderedDescending } ?? false
|
||||
return PredicateStatus(bool: matches)
|
||||
}
|
||||
}
|
||||
|
||||
public func <=<T: NMBComparable>(lhs: Expectation<T>, rhs: T) {
|
||||
lhs.to(beLessThanOrEqualTo(rhs))
|
||||
}
|
||||
|
||||
extension NMBPredicate {
|
||||
@objc public class func beLessThanOrEqualToMatcher(_ expected: NMBComparable?) -> NMBPredicate {
|
||||
return NMBPredicate { actualExpression in
|
||||
let expr = actualExpression.cast { $0 as? NMBComparable }
|
||||
return try beLessThanOrEqualTo(expected).satisfies(expr).toObjectiveC()
|
||||
}
|
||||
}
|
||||
}
|
||||
#endif
|
||||
-154
@@ -1,154 +0,0 @@
|
||||
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 rename<T>(_ matcher: Predicate<T>, failureMessage message: ExpectationMessage) -> Predicate<T> {
|
||||
return Predicate { actualExpression in
|
||||
let result = try matcher.satisfies(actualExpression)
|
||||
return PredicateResult(status: result.status, message: message)
|
||||
}.requireNonNil
|
||||
}
|
||||
|
||||
// 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() -> Predicate<Bool> {
|
||||
return rename(equal(true), failureMessage: .expectedActualValueTo("be true"))
|
||||
}
|
||||
|
||||
/// A Nimble matcher that succeeds when the actual value is exactly false.
|
||||
/// This matcher will not match against nils.
|
||||
public func beFalse() -> Predicate<Bool> {
|
||||
return rename(equal(false), failureMessage: .expectedActualValueTo("be false"))
|
||||
}
|
||||
|
||||
// MARK: beTruthy() / beFalsy()
|
||||
|
||||
/// A Nimble matcher that succeeds when the actual value is not logically false.
|
||||
public func beTruthy<T: ExpressibleByBooleanLiteral & Equatable>() -> Predicate<T> {
|
||||
return Predicate.simpleNilable("be truthy") { actualExpression in
|
||||
let actualValue = try actualExpression.evaluate()
|
||||
if let actualValue = actualValue {
|
||||
return PredicateStatus(bool: actualValue == (true as T))
|
||||
}
|
||||
return PredicateStatus(bool: actualValue != nil)
|
||||
}
|
||||
}
|
||||
|
||||
/// A Nimble matcher that succeeds when the actual value is logically false.
|
||||
/// This matcher will match against nils.
|
||||
public func beFalsy<T: ExpressibleByBooleanLiteral & Equatable>() -> Predicate<T> {
|
||||
return Predicate.simpleNilable("be falsy") { actualExpression in
|
||||
let actualValue = try actualExpression.evaluate()
|
||||
if let actualValue = actualValue {
|
||||
return PredicateStatus(bool: actualValue == (false as T))
|
||||
}
|
||||
return PredicateStatus(bool: actualValue == nil)
|
||||
}
|
||||
}
|
||||
|
||||
#if canImport(Darwin)
|
||||
extension NMBPredicate {
|
||||
@objc public class func beTruthyMatcher() -> NMBPredicate {
|
||||
return NMBPredicate { actualExpression in
|
||||
let expr = actualExpression.cast { ($0 as? NSNumber)?.boolValue ?? false }
|
||||
return try beTruthy().satisfies(expr).toObjectiveC()
|
||||
}
|
||||
}
|
||||
|
||||
@objc public class func beFalsyMatcher() -> NMBPredicate {
|
||||
return NMBPredicate { actualExpression in
|
||||
let expr = actualExpression.cast { ($0 as? NSNumber)?.boolValue ?? false }
|
||||
return try beFalsy().satisfies(expr).toObjectiveC()
|
||||
}
|
||||
}
|
||||
|
||||
@objc public class func beTrueMatcher() -> NMBPredicate {
|
||||
return NMBPredicate { actualExpression in
|
||||
let expr = actualExpression.cast { ($0 as? NSNumber)?.boolValue ?? false }
|
||||
return try beTrue().satisfies(expr).toObjectiveC()
|
||||
}
|
||||
}
|
||||
|
||||
@objc public class func beFalseMatcher() -> NMBPredicate {
|
||||
return NMBPredicate { actualExpression in
|
||||
let expr = actualExpression.cast { value -> Bool? in
|
||||
guard let value = value else { return nil }
|
||||
return (value as? NSNumber)?.boolValue ?? false
|
||||
}
|
||||
return try beFalse().satisfies(expr).toObjectiveC()
|
||||
}
|
||||
}
|
||||
}
|
||||
#endif
|
||||
-19
@@ -1,19 +0,0 @@
|
||||
/// A Nimble matcher that succeeds when the actual value is nil.
|
||||
public func beNil<T>() -> Predicate<T> {
|
||||
return Predicate.simpleNilable("be nil") { actualExpression in
|
||||
let actualValue = try actualExpression.evaluate()
|
||||
return PredicateStatus(bool: actualValue == nil)
|
||||
}
|
||||
}
|
||||
|
||||
#if canImport(Darwin)
|
||||
import Foundation
|
||||
|
||||
extension NMBPredicate {
|
||||
@objc public class func beNilMatcher() -> NMBPredicate {
|
||||
return NMBPredicate { actualExpression in
|
||||
return try beNil().satisfies(actualExpression).toObjectiveC()
|
||||
}
|
||||
}
|
||||
}
|
||||
#endif
|
||||
-17
@@ -1,17 +0,0 @@
|
||||
/// A Nimble matcher that succeeds when the actual value is Void.
|
||||
public func beVoid() -> Predicate<()> {
|
||||
return Predicate.simpleNilable("be void") { actualExpression in
|
||||
let actualValue: ()? = try actualExpression.evaluate()
|
||||
return PredicateStatus(bool: actualValue != nil)
|
||||
}
|
||||
}
|
||||
|
||||
extension Expectation where T == () {
|
||||
public static func == (lhs: Expectation<()>, rhs: ()) {
|
||||
lhs.to(beVoid())
|
||||
}
|
||||
|
||||
public static func != (lhs: Expectation<()>, rhs: ()) {
|
||||
lhs.toNot(beVoid())
|
||||
}
|
||||
}
|
||||
-57
@@ -1,57 +0,0 @@
|
||||
import Foundation
|
||||
|
||||
/// A Nimble matcher that succeeds when the actual sequence's first element
|
||||
/// is equal to the expected value.
|
||||
public func beginWith<S: Sequence>(_ startingElement: S.Element) -> Predicate<S> where S.Element: Equatable {
|
||||
return Predicate.simple("begin with <\(startingElement)>") { actualExpression in
|
||||
guard let actualValue = try actualExpression.evaluate() else { return .fail }
|
||||
|
||||
var actualGenerator = actualValue.makeIterator()
|
||||
return PredicateStatus(bool: actualGenerator.next() == startingElement)
|
||||
}
|
||||
}
|
||||
|
||||
/// A Nimble matcher that succeeds when the actual collection's first element
|
||||
/// is equal to the expected object.
|
||||
public func beginWith(_ startingElement: Any) -> Predicate<NMBOrderedCollection> {
|
||||
return Predicate.simple("begin with <\(startingElement)>") { actualExpression in
|
||||
guard let collection = try actualExpression.evaluate() else { return .fail }
|
||||
guard collection.count > 0 else { return .doesNotMatch }
|
||||
#if os(Linux)
|
||||
guard let collectionValue = collection.object(at: 0) as? NSObject else {
|
||||
return .fail
|
||||
}
|
||||
#else
|
||||
let collectionValue = collection.object(at: 0) as AnyObject
|
||||
#endif
|
||||
return PredicateStatus(bool: 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) -> Predicate<String> {
|
||||
return Predicate.simple("begin with <\(startingSubstring)>") { actualExpression in
|
||||
guard let actual = try actualExpression.evaluate() else { return .fail }
|
||||
|
||||
return PredicateStatus(bool: actual.hasPrefix(startingSubstring))
|
||||
}
|
||||
}
|
||||
|
||||
#if canImport(Darwin)
|
||||
extension NMBPredicate {
|
||||
@objc public class func beginWithMatcher(_ expected: Any) -> NMBPredicate {
|
||||
return NMBPredicate { actualExpression in
|
||||
let actual = try actualExpression.evaluate()
|
||||
if actual is String {
|
||||
let expr = actualExpression.cast { $0 as? String }
|
||||
// swiftlint:disable:next force_cast
|
||||
return try beginWith(expected as! String).satisfies(expr).toObjectiveC()
|
||||
} else {
|
||||
let expr = actualExpression.cast { $0 as? NMBOrderedCollection }
|
||||
return try beginWith(expected).satisfies(expr).toObjectiveC()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
#endif
|
||||
@@ -1,39 +0,0 @@
|
||||
/// A Nimble matcher that succeeds when the exepected sequence is a prefix of the actual sequence.
|
||||
///
|
||||
/// This is a matcher abstraction for https://developer.apple.com/documentation/swift/sequence/2854218-starts
|
||||
public func beginWith<Seq1: Sequence, Seq2: Sequence>(prefix expectedPrefix: Seq2?)
|
||||
-> Predicate<Seq1> where Seq1.Element: Equatable, Seq1.Element == Seq2.Element {
|
||||
return Predicate.define("begin with <\(stringify(expectedPrefix))>") { (actualExpression, msg) in
|
||||
let actualPrefix = try actualExpression.evaluate()
|
||||
switch (expectedPrefix, actualPrefix) {
|
||||
case (nil, _?):
|
||||
return PredicateResult(status: .fail, message: msg.appendedBeNilHint())
|
||||
case (nil, nil), (_, nil):
|
||||
return PredicateResult(status: .fail, message: msg)
|
||||
case (let expected?, let actual?):
|
||||
let matches = actual.starts(with: expected)
|
||||
return PredicateResult(bool: matches, message: msg)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A Nimble matcher that succeeds when the expected sequence is the prefix of the actual sequence, using the given predicate as the equivalence test.
|
||||
///
|
||||
/// This is a matcher abstraction for https://developer.apple.com/documentation/swift/sequence/2996828-starts
|
||||
public func beginWith<Seq1: Sequence, Seq2: Sequence>(
|
||||
prefix expectedPrefix: Seq2?,
|
||||
by areEquivalent: @escaping (Seq1.Element, Seq2.Element) -> Bool
|
||||
) -> Predicate<Seq1> {
|
||||
return Predicate.define("begin with <\(stringify(expectedPrefix))>") { (actualExpression, msg) in
|
||||
let actualPrefix = try actualExpression.evaluate()
|
||||
switch (expectedPrefix, actualPrefix) {
|
||||
case (nil, _?):
|
||||
return PredicateResult(status: .fail, message: msg.appendedBeNilHint())
|
||||
case (nil, nil), (_, nil):
|
||||
return PredicateResult(status: .fail, message: msg)
|
||||
case (let expected?, let actual?):
|
||||
let matches = actual.starts(with: expected, by: areEquivalent)
|
||||
return PredicateResult(bool: matches, message: msg)
|
||||
}
|
||||
}
|
||||
}
|
||||
-138
@@ -1,138 +0,0 @@
|
||||
#if canImport(Foundation)
|
||||
import Foundation
|
||||
#endif
|
||||
|
||||
/// A Nimble matcher that succeeds when the actual sequence contains the expected values.
|
||||
public func contain<S: Sequence>(_ items: S.Element...) -> Predicate<S> where S.Element: Equatable {
|
||||
return contain(items)
|
||||
}
|
||||
|
||||
/// A Nimble matcher that succeeds when the actual sequence contains the expected values.
|
||||
public func contain<S: Sequence>(_ items: [S.Element]) -> Predicate<S> where S.Element: Equatable {
|
||||
return Predicate.simple("contain <\(arrayAsString(items))>") { actualExpression in
|
||||
guard let actual = try actualExpression.evaluate() else { return .fail }
|
||||
|
||||
let matches = items.allSatisfy {
|
||||
return actual.contains($0)
|
||||
}
|
||||
return PredicateStatus(bool: matches)
|
||||
}
|
||||
}
|
||||
|
||||
/// A Nimble matcher that succeeds when the actual set contains the expected values.
|
||||
public func contain<S: SetAlgebra>(_ items: S.Element...) -> Predicate<S> where S.Element: Equatable {
|
||||
return contain(items)
|
||||
}
|
||||
|
||||
/// A Nimble matcher that succeeds when the actual set contains the expected values.
|
||||
public func contain<S: SetAlgebra>(_ items: [S.Element]) -> Predicate<S> where S.Element: Equatable {
|
||||
return Predicate.simple("contain <\(arrayAsString(items))>") { actualExpression in
|
||||
guard let actual = try actualExpression.evaluate() else { return .fail }
|
||||
|
||||
let matches = items.allSatisfy {
|
||||
return actual.contains($0)
|
||||
}
|
||||
return PredicateStatus(bool: matches)
|
||||
}
|
||||
}
|
||||
|
||||
/// A Nimble matcher that succeeds when the actual set contains the expected values.
|
||||
public func contain<S: Sequence & SetAlgebra>(_ items: S.Element...) -> Predicate<S> where S.Element: Equatable {
|
||||
return contain(items)
|
||||
}
|
||||
|
||||
/// A Nimble matcher that succeeds when the actual set contains the expected values.
|
||||
public func contain<S: Sequence & SetAlgebra>(_ items: [S.Element]) -> Predicate<S> where S.Element: Equatable {
|
||||
return Predicate.simple("contain <\(arrayAsString(items))>") { actualExpression in
|
||||
guard let actual = try actualExpression.evaluate() else { return .fail }
|
||||
|
||||
let matches = items.allSatisfy {
|
||||
return actual.contains($0)
|
||||
}
|
||||
return PredicateStatus(bool: matches)
|
||||
}
|
||||
}
|
||||
|
||||
/// A Nimble matcher that succeeds when the actual string contains the expected substring.
|
||||
public func contain(_ substrings: String...) -> Predicate<String> {
|
||||
return contain(substrings)
|
||||
}
|
||||
|
||||
public func contain(_ substrings: [String]) -> Predicate<String> {
|
||||
return Predicate.simple("contain <\(arrayAsString(substrings))>") { actualExpression in
|
||||
guard let actual = try actualExpression.evaluate() else { return .fail }
|
||||
|
||||
let matches = substrings.allSatisfy {
|
||||
let range = actual.range(of: $0)
|
||||
return range != nil && !range!.isEmpty
|
||||
}
|
||||
return PredicateStatus(bool: matches)
|
||||
}
|
||||
}
|
||||
|
||||
#if canImport(Foundation)
|
||||
/// A Nimble matcher that succeeds when the actual string contains the expected substring.
|
||||
public func contain(_ substrings: NSString...) -> Predicate<NSString> {
|
||||
return contain(substrings)
|
||||
}
|
||||
|
||||
public func contain(_ substrings: [NSString]) -> Predicate<NSString> {
|
||||
return Predicate.simple("contain <\(arrayAsString(substrings))>") { actualExpression in
|
||||
guard let actual = try actualExpression.evaluate() else { return .fail }
|
||||
|
||||
let matches = substrings.allSatisfy { actual.range(of: $0.description).length != 0 }
|
||||
return PredicateStatus(bool: matches)
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
/// A Nimble matcher that succeeds when the actual collection contains the expected object.
|
||||
public func contain(_ items: Any?...) -> Predicate<NMBContainer> {
|
||||
return contain(items)
|
||||
}
|
||||
|
||||
public func contain(_ items: [Any?]) -> Predicate<NMBContainer> {
|
||||
return Predicate.simple("contain <\(arrayAsString(items))>") { actualExpression in
|
||||
guard let actual = try actualExpression.evaluate() else { return .fail }
|
||||
|
||||
let matches = items.allSatisfy { item in
|
||||
return item.map { actual.contains($0) } ?? false
|
||||
}
|
||||
return PredicateStatus(bool: matches)
|
||||
}
|
||||
}
|
||||
|
||||
#if canImport(Darwin)
|
||||
extension NMBPredicate {
|
||||
@objc public class func containMatcher(_ expected: [NSObject]) -> NMBPredicate {
|
||||
return NMBPredicate { actualExpression 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).satisfies(expr).toObjectiveC()
|
||||
} else if let value = actualValue as? NSString {
|
||||
let expr = Expression(expression: ({ value as String }), location: location)
|
||||
// swiftlint:disable:next force_cast
|
||||
return try contain(expected as! [String]).satisfies(expr).toObjectiveC()
|
||||
}
|
||||
|
||||
let message: ExpectationMessage
|
||||
if actualValue != nil {
|
||||
message = ExpectationMessage.expectedActualValueTo(
|
||||
// swiftlint:disable:next line_length
|
||||
"contain <\(arrayAsString(expected))> (only works for NSArrays, NSSets, NSHashTables, and NSStrings)"
|
||||
)
|
||||
} else {
|
||||
message = ExpectationMessage
|
||||
.expectedActualValueTo("contain <\(arrayAsString(expected))>")
|
||||
.appendedBeNilHint()
|
||||
}
|
||||
return NMBPredicateResult(status: .fail, message: message.toObjectiveC())
|
||||
}
|
||||
}
|
||||
}
|
||||
#endif
|
||||
@@ -1,61 +0,0 @@
|
||||
public func containElementSatisfying<S: Sequence>(
|
||||
_ predicate: @escaping ((S.Element) -> Bool), _ predicateDescription: String = ""
|
||||
) -> Predicate<S> {
|
||||
return Predicate.define { actualExpression in
|
||||
let message: ExpectationMessage
|
||||
if predicateDescription == "" {
|
||||
message = .expectedTo("find object in collection that satisfies predicate")
|
||||
} else {
|
||||
message = .expectedTo("find object in collection \(predicateDescription)")
|
||||
}
|
||||
|
||||
if let sequence = try actualExpression.evaluate() {
|
||||
for object in sequence {
|
||||
if predicate(object) {
|
||||
return PredicateResult(bool: true, message: message)
|
||||
}
|
||||
}
|
||||
|
||||
return PredicateResult(bool: false, message: message)
|
||||
}
|
||||
|
||||
return PredicateResult(status: .fail, message: message)
|
||||
}
|
||||
}
|
||||
|
||||
#if canImport(Darwin)
|
||||
import class Foundation.NSObject
|
||||
import struct Foundation.NSFastEnumerationIterator
|
||||
import protocol Foundation.NSFastEnumeration
|
||||
|
||||
extension NMBPredicate {
|
||||
@objc public class func containElementSatisfyingMatcher(_ predicate: @escaping ((NSObject) -> Bool)) -> NMBPredicate {
|
||||
return NMBPredicate { actualExpression in
|
||||
let value = try actualExpression.evaluate()
|
||||
guard let enumeration = value as? NSFastEnumeration else {
|
||||
let message = ExpectationMessage.fail(
|
||||
"containElementSatisfying must be provided an NSFastEnumeration object"
|
||||
)
|
||||
return NMBPredicateResult(status: .fail, message: message.toObjectiveC())
|
||||
}
|
||||
|
||||
let message = ExpectationMessage
|
||||
.expectedTo("find object in collection that satisfies predicate")
|
||||
.toObjectiveC()
|
||||
|
||||
var iterator = NSFastEnumerationIterator(enumeration)
|
||||
while let item = iterator.next() {
|
||||
guard let object = item as? NSObject else {
|
||||
continue
|
||||
}
|
||||
|
||||
if predicate(object) {
|
||||
return NMBPredicateResult(status: .matches, message: message)
|
||||
}
|
||||
}
|
||||
|
||||
return NMBPredicateResult(status: .doesNotMatch, message: message)
|
||||
}
|
||||
}
|
||||
}
|
||||
#endif
|
||||
@@ -1,42 +0,0 @@
|
||||
/// A Nimble matcher that succeeds when the actual sequence and the exepected sequence contain the same elements in
|
||||
/// the same order.
|
||||
///
|
||||
/// This is a matcher abstraction for https://developer.apple.com/documentation/swift/sequence/2854213-elementsequal
|
||||
public func elementsEqual<Seq1: Sequence, Seq2: Sequence>(
|
||||
_ expectedValue: Seq2?
|
||||
) -> Predicate<Seq1> where Seq1.Element: Equatable, Seq1.Element == Seq2.Element {
|
||||
return Predicate.define("elementsEqual <\(stringify(expectedValue))>") { (actualExpression, msg) in
|
||||
let actualValue = try actualExpression.evaluate()
|
||||
switch (expectedValue, actualValue) {
|
||||
case (nil, _?):
|
||||
return PredicateResult(status: .fail, message: msg.appendedBeNilHint())
|
||||
case (nil, nil), (_, nil):
|
||||
return PredicateResult(status: .fail, message: msg)
|
||||
case (let expected?, let actual?):
|
||||
let matches = expected.elementsEqual(actual)
|
||||
return PredicateResult(bool: matches, message: msg)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A Nimble matcher that succeeds when the actual sequence and the exepected sequence contain equivalent elements in
|
||||
/// the same order, using the given predicate as the equivalence test.
|
||||
///
|
||||
/// This is a matcher abstraction for https://developer.apple.com/documentation/swift/sequence/2949668-elementsequal
|
||||
public func elementsEqual<Seq1: Sequence, Seq2: Sequence>(
|
||||
_ expectedValue: Seq2?,
|
||||
by areEquivalent: @escaping (Seq1.Element, Seq2.Element) -> Bool
|
||||
) -> Predicate<Seq1> {
|
||||
return Predicate.define("elementsEqual <\(stringify(expectedValue))>") { (actualExpression, msg) in
|
||||
let actualValue = try actualExpression.evaluate()
|
||||
switch (expectedValue, actualValue) {
|
||||
case (nil, _?):
|
||||
return PredicateResult(status: .fail, message: msg.appendedBeNilHint())
|
||||
case (nil, nil), (_, nil):
|
||||
return PredicateResult(status: .fail, message: msg)
|
||||
case (let expected?, let actual?):
|
||||
let matches = actual.elementsEqual(expected, by: areEquivalent)
|
||||
return PredicateResult(bool: matches, message: msg)
|
||||
}
|
||||
}
|
||||
}
|
||||
-67
@@ -1,67 +0,0 @@
|
||||
import Foundation
|
||||
|
||||
/// A Nimble matcher that succeeds when the actual sequence's last element
|
||||
/// is equal to the expected value.
|
||||
public func endWith<S: Sequence>(_ endingElement: S.Element) -> Predicate<S> where S.Element: Equatable {
|
||||
return Predicate.simple("end with <\(endingElement)>") { actualExpression in
|
||||
guard let actualValue = try actualExpression.evaluate() else { return .fail }
|
||||
|
||||
var actualGenerator = actualValue.makeIterator()
|
||||
var lastItem: S.Element?
|
||||
var item: S.Element?
|
||||
repeat {
|
||||
lastItem = item
|
||||
item = actualGenerator.next()
|
||||
} while(item != nil)
|
||||
|
||||
return PredicateStatus(bool: lastItem == endingElement)
|
||||
}
|
||||
}
|
||||
|
||||
/// A Nimble matcher that succeeds when the actual collection's last element
|
||||
/// is equal to the expected object.
|
||||
public func endWith(_ endingElement: Any) -> Predicate<NMBOrderedCollection> {
|
||||
return Predicate.simple("end with <\(endingElement)>") { actualExpression in
|
||||
guard let collection = try actualExpression.evaluate() else { return .fail }
|
||||
|
||||
guard collection.count > 0 else { return PredicateStatus(bool: false) }
|
||||
#if os(Linux)
|
||||
guard let collectionValue = collection.object(at: collection.count - 1) as? NSObject else {
|
||||
return .fail
|
||||
}
|
||||
#else
|
||||
let collectionValue = collection.object(at: collection.count - 1) as AnyObject
|
||||
#endif
|
||||
|
||||
return PredicateStatus(bool: 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) -> Predicate<String> {
|
||||
return Predicate.simple("end with <\(endingSubstring)>") { actualExpression in
|
||||
guard let collection = try actualExpression.evaluate() else { return .fail }
|
||||
|
||||
return PredicateStatus(bool: collection.hasSuffix(endingSubstring))
|
||||
}
|
||||
}
|
||||
|
||||
#if canImport(Darwin)
|
||||
extension NMBPredicate {
|
||||
@objc public class func endWithMatcher(_ expected: Any) -> NMBPredicate {
|
||||
return NMBPredicate { actualExpression in
|
||||
let actual = try actualExpression.evaluate()
|
||||
if actual is String {
|
||||
let expr = actualExpression.cast { $0 as? String }
|
||||
// swiftlint:disable:next force_cast
|
||||
return try endWith(expected as! String).satisfies(expr).toObjectiveC()
|
||||
} else {
|
||||
let expr = actualExpression.cast { $0 as? NMBOrderedCollection }
|
||||
return try endWith(expected).satisfies(expr).toObjectiveC()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
#endif
|
||||
-148
@@ -1,148 +0,0 @@
|
||||
/// 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<T: Equatable>(_ expectedValue: T?) -> Predicate<T> {
|
||||
return Predicate.define("equal <\(stringify(expectedValue))>") { actualExpression, msg in
|
||||
let actualValue = try actualExpression.evaluate()
|
||||
switch (expectedValue, actualValue) {
|
||||
case (nil, _?):
|
||||
return PredicateResult(status: .fail, message: msg.appendedBeNilHint())
|
||||
case (nil, nil), (_, nil):
|
||||
return PredicateResult(status: .fail, message: msg)
|
||||
case (let expected?, let actual?):
|
||||
let matches = expected == actual
|
||||
return PredicateResult(bool: matches, message: msg)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A Nimble matcher allowing comparison of collection with optional type
|
||||
public func equal<T: Equatable>(_ expectedValue: [T?]) -> Predicate<[T?]> {
|
||||
return Predicate.define("equal <\(stringify(expectedValue))>") { actualExpression, msg in
|
||||
guard let actualValue = try actualExpression.evaluate() else {
|
||||
return PredicateResult(
|
||||
status: .fail,
|
||||
message: msg.appendedBeNilHint()
|
||||
)
|
||||
}
|
||||
|
||||
let matches = expectedValue == actualValue
|
||||
return PredicateResult(bool: matches, message: msg)
|
||||
}
|
||||
}
|
||||
|
||||
/// A Nimble matcher that succeeds when the actual set is equal to the expected set.
|
||||
public func equal<T>(_ expectedValue: Set<T>?) -> Predicate<Set<T>> {
|
||||
return equal(expectedValue, stringify: { stringify($0) })
|
||||
}
|
||||
|
||||
/// A Nimble matcher that succeeds when the actual set is equal to the expected set.
|
||||
public func equal<T: Comparable>(_ expectedValue: Set<T>?) -> Predicate<Set<T>> {
|
||||
return equal(expectedValue, stringify: {
|
||||
if let set = $0 {
|
||||
return stringify(Array(set).sorted { $0 < $1 })
|
||||
} else {
|
||||
return "nil"
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
private func equal<T>(_ expectedValue: Set<T>?, stringify: @escaping (Set<T>?) -> String) -> Predicate<Set<T>> {
|
||||
return Predicate { actualExpression in
|
||||
var errorMessage: ExpectationMessage =
|
||||
.expectedActualValueTo("equal <\(stringify(expectedValue))>")
|
||||
|
||||
guard let expectedValue = expectedValue else {
|
||||
return PredicateResult(
|
||||
status: .fail,
|
||||
message: errorMessage.appendedBeNilHint()
|
||||
)
|
||||
}
|
||||
|
||||
guard let actualValue = try actualExpression.evaluate() else {
|
||||
return PredicateResult(
|
||||
status: .fail,
|
||||
message: errorMessage.appendedBeNilHint()
|
||||
)
|
||||
}
|
||||
|
||||
errorMessage = .expectedCustomValueTo(
|
||||
"equal <\(stringify(expectedValue))>",
|
||||
actual: "<\(stringify(actualValue))>"
|
||||
)
|
||||
|
||||
if expectedValue == actualValue {
|
||||
return PredicateResult(
|
||||
status: .matches,
|
||||
message: errorMessage
|
||||
)
|
||||
}
|
||||
|
||||
let missing = expectedValue.subtracting(actualValue)
|
||||
if missing.count > 0 {
|
||||
errorMessage = errorMessage.appended(message: ", missing <\(stringify(missing))>")
|
||||
}
|
||||
|
||||
let extra = actualValue.subtracting(expectedValue)
|
||||
if extra.count > 0 {
|
||||
errorMessage = errorMessage.appended(message: ", extra <\(stringify(extra))>")
|
||||
}
|
||||
return PredicateResult(
|
||||
status: .doesNotMatch,
|
||||
message: errorMessage
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
public func ==<T: Equatable>(lhs: Expectation<T>, rhs: T?) {
|
||||
lhs.to(equal(rhs))
|
||||
}
|
||||
|
||||
public func !=<T: Equatable>(lhs: Expectation<T>, rhs: T?) {
|
||||
lhs.toNot(equal(rhs))
|
||||
}
|
||||
|
||||
public func ==<T: Equatable>(lhs: Expectation<[T]>, rhs: [T]?) {
|
||||
lhs.to(equal(rhs))
|
||||
}
|
||||
|
||||
public func !=<T: Equatable>(lhs: Expectation<[T]>, rhs: [T]?) {
|
||||
lhs.toNot(equal(rhs))
|
||||
}
|
||||
|
||||
public func == <T>(lhs: Expectation<Set<T>>, rhs: Set<T>?) {
|
||||
lhs.to(equal(rhs))
|
||||
}
|
||||
|
||||
public func != <T>(lhs: Expectation<Set<T>>, rhs: Set<T>?) {
|
||||
lhs.toNot(equal(rhs))
|
||||
}
|
||||
|
||||
public func ==<T: Comparable>(lhs: Expectation<Set<T>>, rhs: Set<T>?) {
|
||||
lhs.to(equal(rhs))
|
||||
}
|
||||
|
||||
public func !=<T: Comparable>(lhs: Expectation<Set<T>>, rhs: Set<T>?) {
|
||||
lhs.toNot(equal(rhs))
|
||||
}
|
||||
|
||||
public func ==<T, C: Equatable>(lhs: Expectation<[T: C]>, rhs: [T: C]?) {
|
||||
lhs.to(equal(rhs))
|
||||
}
|
||||
|
||||
public func !=<T, C: Equatable>(lhs: Expectation<[T: C]>, rhs: [T: C]?) {
|
||||
lhs.toNot(equal(rhs))
|
||||
}
|
||||
|
||||
#if canImport(Darwin)
|
||||
import class Foundation.NSObject
|
||||
|
||||
extension NMBPredicate {
|
||||
@objc public class func equalMatcher(_ expected: NSObject) -> NMBPredicate {
|
||||
return NMBPredicate { actualExpression in
|
||||
return try equal(expected).satisfies(actualExpression).toObjectiveC()
|
||||
}
|
||||
}
|
||||
}
|
||||
#endif
|
||||
-74
@@ -1,74 +0,0 @@
|
||||
// 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<T: Collection>(_ expectedValue: Int) -> Predicate<T> {
|
||||
return Predicate.define { actualExpression in
|
||||
if let actualValue = try actualExpression.evaluate() {
|
||||
let message = ExpectationMessage
|
||||
.expectedCustomValueTo(
|
||||
"have \(prettyCollectionType(actualValue)) with count \(stringify(expectedValue))",
|
||||
actual: "\(actualValue.count)"
|
||||
)
|
||||
.appended(details: "Actual Value: \(stringify(actualValue))")
|
||||
|
||||
let result = expectedValue == actualValue.count
|
||||
return PredicateResult(bool: result, message: message)
|
||||
} else {
|
||||
return PredicateResult(status: .fail, message: .fail(""))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A Nimble matcher that succeeds when the actual collection's count equals
|
||||
/// the expected value
|
||||
public func haveCount(_ expectedValue: Int) -> Predicate<NMBCollection> {
|
||||
return Predicate { actualExpression in
|
||||
if let actualValue = try actualExpression.evaluate() {
|
||||
let message = ExpectationMessage
|
||||
.expectedCustomValueTo(
|
||||
"have \(prettyCollectionType(actualValue)) with count \(stringify(expectedValue))",
|
||||
actual: "\(actualValue.count)"
|
||||
)
|
||||
.appended(details: "Actual Value: \(stringify(actualValue))")
|
||||
|
||||
let result = expectedValue == actualValue.count
|
||||
return PredicateResult(bool: result, message: message)
|
||||
} else {
|
||||
return PredicateResult(status: .fail, message: .fail(""))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#if canImport(Darwin)
|
||||
import Foundation
|
||||
|
||||
extension NMBPredicate {
|
||||
@objc public class func haveCountMatcher(_ expected: NSNumber) -> NMBPredicate {
|
||||
return NMBPredicate { actualExpression 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).satisfies(expr).toObjectiveC()
|
||||
}
|
||||
|
||||
let message: ExpectationMessage
|
||||
if let actualValue = actualValue {
|
||||
message = ExpectationMessage.expectedCustomValueTo(
|
||||
"get type of NSArray, NSSet, NSDictionary, or NSHashTable",
|
||||
actual: "\(String(describing: type(of: actualValue)))"
|
||||
)
|
||||
} else {
|
||||
message = ExpectationMessage
|
||||
.expectedActualValueTo("have a collection with count \(stringify(expected.intValue))")
|
||||
.appendedBeNilHint()
|
||||
}
|
||||
return NMBPredicateResult(status: .fail, message: message.toObjectiveC())
|
||||
}
|
||||
}
|
||||
}
|
||||
#endif
|
||||
-23
@@ -1,23 +0,0 @@
|
||||
/// A Nimble matcher that succeeds when the actual string satisfies the regular expression
|
||||
/// described by the expected string.
|
||||
public func match(_ expectedValue: String?) -> Predicate<String> {
|
||||
return Predicate.simple("match <\(stringify(expectedValue))>") { actualExpression in
|
||||
guard let actual = try actualExpression.evaluate(), let regexp = expectedValue else { return .fail }
|
||||
|
||||
let bool = actual.range(of: regexp, options: .regularExpression) != nil
|
||||
return PredicateStatus(bool: bool)
|
||||
}
|
||||
}
|
||||
|
||||
#if canImport(Darwin)
|
||||
import class Foundation.NSString
|
||||
|
||||
extension NMBPredicate {
|
||||
@objc public class func matchMatcher(_ expected: NSString) -> NMBPredicate {
|
||||
return NMBPredicate { actualExpression in
|
||||
let actual = actualExpression.cast { $0 as? String }
|
||||
return try match(expected.description).satisfies(actual).toObjectiveC()
|
||||
}
|
||||
}
|
||||
}
|
||||
#endif
|
||||
@@ -1,68 +0,0 @@
|
||||
/// 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 comparison by _domain and _code.
|
||||
public func matchError<T: Error>(_ error: T) -> Predicate<Error> {
|
||||
return Predicate.define { actualExpression in
|
||||
let actualError = try actualExpression.evaluate()
|
||||
|
||||
let message = messageForError(
|
||||
postfixMessageVerb: "match",
|
||||
actualError: actualError,
|
||||
error: error
|
||||
)
|
||||
|
||||
var matches = false
|
||||
if let actualError = actualError, errorMatchesExpectedError(actualError, expectedError: error) {
|
||||
matches = true
|
||||
}
|
||||
|
||||
return PredicateResult(bool: matches, message: message)
|
||||
}
|
||||
}
|
||||
|
||||
/// 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<T: Error & Equatable>(_ error: T) -> Predicate<Error> {
|
||||
return Predicate.define { actualExpression in
|
||||
let actualError = try actualExpression.evaluate()
|
||||
|
||||
let message = messageForError(
|
||||
postfixMessageVerb: "match",
|
||||
actualError: actualError,
|
||||
error: error
|
||||
)
|
||||
|
||||
var matches = false
|
||||
if let actualError = actualError as? T, error == actualError {
|
||||
matches = true
|
||||
}
|
||||
|
||||
return PredicateResult(bool: matches, message: message)
|
||||
}
|
||||
}
|
||||
|
||||
/// A Nimble matcher that succeeds when the actual expression evaluates to an
|
||||
/// error of the specified type
|
||||
public func matchError<T: Error>(_ errorType: T.Type) -> Predicate<Error> {
|
||||
return Predicate.define { actualExpression in
|
||||
let actualError = try actualExpression.evaluate()
|
||||
|
||||
let message = messageForError(
|
||||
postfixMessageVerb: "match",
|
||||
actualError: actualError,
|
||||
errorType: errorType
|
||||
)
|
||||
|
||||
var matches = false
|
||||
if actualError as? T != nil {
|
||||
matches = true
|
||||
}
|
||||
|
||||
return PredicateResult(bool: matches, message: message)
|
||||
}
|
||||
}
|
||||
@@ -1,87 +0,0 @@
|
||||
/// DEPRECATED: A convenience API to build matchers that don't need special negation
|
||||
/// behavior. The toNot() behavior is the negation of to().
|
||||
///
|
||||
/// @see NonNilMatcherFunc if you prefer to have this matcher fail when nil
|
||||
/// values are received in an expectation.
|
||||
///
|
||||
/// You may use this when implementing your own custom matchers.
|
||||
///
|
||||
/// Use the Matcher protocol instead of this type to accept custom matchers as
|
||||
/// input parameters.
|
||||
/// @see allPass for an example that uses accepts other matchers as input.
|
||||
@available(*, deprecated, message: "Use Predicate instead")
|
||||
public struct MatcherFunc<T>: Matcher {
|
||||
public let matcher: (Expression<T>, FailureMessage) throws -> Bool
|
||||
|
||||
public init(_ matcher: @escaping (Expression<T>, FailureMessage) throws -> Bool) {
|
||||
self.matcher = matcher
|
||||
}
|
||||
|
||||
public func matches(_ actualExpression: Expression<T>, failureMessage: FailureMessage) throws -> Bool {
|
||||
return try matcher(actualExpression, failureMessage)
|
||||
}
|
||||
|
||||
public func doesNotMatch(_ actualExpression: Expression<T>, failureMessage: FailureMessage) throws -> Bool {
|
||||
return try !matcher(actualExpression, failureMessage)
|
||||
}
|
||||
|
||||
/// Compatibility layer to new Matcher API. Converts an old-style matcher to a new one.
|
||||
/// Note: You should definitely spend the time to convert to the new api as soon as possible
|
||||
/// since this struct type is deprecated.
|
||||
@available(*, deprecated, message: "Use Predicate directly instead")
|
||||
public var predicate: Predicate<T> {
|
||||
return Predicate.fromDeprecatedMatcher(self)
|
||||
}
|
||||
}
|
||||
|
||||
/// DEPRECATED: A convenience API to build matchers that don't need special negation
|
||||
/// behavior. The toNot() behavior is the negation of to().
|
||||
///
|
||||
/// Unlike MatcherFunc, this will always fail if an expectation contains nil.
|
||||
/// This applies regardless of using to() or toNot().
|
||||
///
|
||||
/// You may use this when implementing your own custom matchers.
|
||||
///
|
||||
/// Use the Matcher protocol instead of this type to accept custom matchers as
|
||||
/// input parameters.
|
||||
/// @see allPass for an example that uses accepts other matchers as input.
|
||||
@available(*, deprecated, message: "Use Predicate instead")
|
||||
public struct NonNilMatcherFunc<T>: Matcher {
|
||||
public let matcher: (Expression<T>, FailureMessage) throws -> Bool
|
||||
|
||||
public init(_ matcher: @escaping (Expression<T>, FailureMessage) throws -> Bool) {
|
||||
self.matcher = matcher
|
||||
}
|
||||
|
||||
public func matches(_ actualExpression: Expression<T>, failureMessage: FailureMessage) throws -> Bool {
|
||||
let pass = try matcher(actualExpression, failureMessage)
|
||||
if try attachNilErrorIfNeeded(actualExpression, failureMessage: failureMessage) {
|
||||
return false
|
||||
}
|
||||
return pass
|
||||
}
|
||||
|
||||
public func doesNotMatch(_ actualExpression: Expression<T>, failureMessage: FailureMessage) throws -> Bool {
|
||||
let pass = try !matcher(actualExpression, failureMessage)
|
||||
if try attachNilErrorIfNeeded(actualExpression, failureMessage: failureMessage) {
|
||||
return false
|
||||
}
|
||||
return pass
|
||||
}
|
||||
|
||||
internal func attachNilErrorIfNeeded(_ actualExpression: Expression<T>, failureMessage: FailureMessage) throws -> Bool {
|
||||
if try actualExpression.evaluate() == nil {
|
||||
failureMessage.postfixActual = " (use beNil() to match nils)"
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
/// Compatibility layer to new Matcher API. Converts an old-style matcher to a new one.
|
||||
/// Note: You should definitely spend the time to convert to the new api as soon as possible
|
||||
/// since this struct type is deprecated.
|
||||
@available(*, deprecated, message: "Use Predicate directly instead")
|
||||
public var predicate: Predicate<T> {
|
||||
return Predicate.fromDeprecatedMatcher(self)
|
||||
}
|
||||
}
|
||||
@@ -1,153 +0,0 @@
|
||||
import Foundation
|
||||
// `CGFloat` is in Foundation (swift-corelibs-foundation) on Linux.
|
||||
#if canImport(Darwin)
|
||||
import CoreGraphics
|
||||
#endif
|
||||
|
||||
/// Implement this protocol to implement a custom matcher for Swift
|
||||
@available(*, deprecated, message: "Use Predicate instead")
|
||||
public protocol Matcher {
|
||||
associatedtype ValueType
|
||||
func matches(_ actualExpression: Expression<ValueType>, failureMessage: FailureMessage) throws -> Bool
|
||||
func doesNotMatch(_ actualExpression: Expression<ValueType>, failureMessage: FailureMessage) throws -> Bool
|
||||
}
|
||||
|
||||
@available(*, deprecated)
|
||||
extension Matcher {
|
||||
var predicate: Predicate<ValueType> {
|
||||
return Predicate.fromDeprecatedMatcher(self)
|
||||
}
|
||||
|
||||
var toClosure: (Expression<ValueType>, FailureMessage, Bool) throws -> Bool {
|
||||
return { expr, msg, expectedResult in
|
||||
if expectedResult {
|
||||
return try self.matches(expr, failureMessage: msg)
|
||||
} else {
|
||||
return try self.doesNotMatch(expr, failureMessage: msg)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#if canImport(Darwin)
|
||||
/// Objective-C interface to the Swift variant of Matcher.
|
||||
@objc public protocol NMBMatcher {
|
||||
func matches(_ actualBlock: @escaping () -> NSObject?, failureMessage: FailureMessage, location: SourceLocation) -> Bool
|
||||
func doesNotMatch(_ actualBlock: @escaping () -> NSObject?, failureMessage: FailureMessage, location: SourceLocation) -> Bool
|
||||
}
|
||||
#endif
|
||||
|
||||
/// Protocol for types that support contain() matcher.
|
||||
public protocol NMBContainer {
|
||||
func contains(_ anObject: Any) -> Bool
|
||||
}
|
||||
|
||||
#if canImport(Darwin)
|
||||
// swiftlint:disable:next todo
|
||||
// FIXME: NSHashTable can not conform to NMBContainer since swift-DEVELOPMENT-SNAPSHOT-2016-04-25-a
|
||||
//extension NSHashTable : NMBContainer {} // Corelibs Foundation does not include this class yet
|
||||
#endif
|
||||
|
||||
extension NSArray: NMBContainer {}
|
||||
extension NSSet: NMBContainer {}
|
||||
|
||||
/// Protocol for types that support only beEmpty(), haveCount() matchers
|
||||
public protocol NMBCollection {
|
||||
var count: Int { get }
|
||||
}
|
||||
|
||||
#if canImport(Darwin)
|
||||
extension NSHashTable: NMBCollection {} // Corelibs Foundation does not include these classes yet
|
||||
extension NSMapTable: NMBCollection {}
|
||||
#endif
|
||||
|
||||
extension NSSet: NMBCollection {}
|
||||
extension NSIndexSet: NMBCollection {}
|
||||
extension NSDictionary: NMBCollection {}
|
||||
|
||||
/// Protocol for types that support beginWith(), endWith(), beEmpty() matchers
|
||||
public protocol NMBOrderedCollection: NMBCollection {
|
||||
func object(at index: Int) -> Any
|
||||
}
|
||||
|
||||
extension NSArray: NMBOrderedCollection {}
|
||||
|
||||
public protocol NMBDoubleConvertible {
|
||||
var doubleValue: CDouble { get }
|
||||
}
|
||||
|
||||
extension Double: NMBDoubleConvertible {
|
||||
public var doubleValue: CDouble {
|
||||
return self
|
||||
}
|
||||
}
|
||||
|
||||
extension Float: NMBDoubleConvertible {
|
||||
public var doubleValue: CDouble {
|
||||
return CDouble(self)
|
||||
}
|
||||
}
|
||||
|
||||
extension CGFloat: NMBDoubleConvertible {
|
||||
public var doubleValue: CDouble {
|
||||
return CDouble(self)
|
||||
}
|
||||
}
|
||||
|
||||
extension NSNumber: NMBDoubleConvertible {
|
||||
}
|
||||
|
||||
private let dateFormatter: DateFormatter = {
|
||||
let formatter = DateFormatter()
|
||||
formatter.dateFormat = "yyyy-MM-dd HH:mm:ss.SSSS"
|
||||
formatter.locale = Locale(identifier: "en_US_POSIX")
|
||||
|
||||
return formatter
|
||||
}()
|
||||
|
||||
extension Date: NMBDoubleConvertible {
|
||||
public var doubleValue: CDouble {
|
||||
return self.timeIntervalSinceReferenceDate
|
||||
}
|
||||
}
|
||||
|
||||
extension NSDate: NMBDoubleConvertible {
|
||||
public var doubleValue: CDouble {
|
||||
return self.timeIntervalSinceReferenceDate
|
||||
}
|
||||
}
|
||||
|
||||
extension Date: TestOutputStringConvertible {
|
||||
public var testDescription: String {
|
||||
return dateFormatter.string(from: self)
|
||||
}
|
||||
}
|
||||
|
||||
extension NSDate: TestOutputStringConvertible {
|
||||
public var testDescription: String {
|
||||
return dateFormatter.string(from: Date(timeIntervalSinceReferenceDate: self.timeIntervalSinceReferenceDate))
|
||||
}
|
||||
}
|
||||
|
||||
#if canImport(Darwin)
|
||||
/// Protocol for types to support beLessThan(), beLessThanOrEqualTo(),
|
||||
/// beGreaterThan(), beGreaterThanOrEqualTo(), and equal() matchers.
|
||||
///
|
||||
/// Types that conform to Swift's Comparable protocol will work implicitly too
|
||||
@objc public protocol NMBComparable {
|
||||
func NMB_compare(_ otherObject: NMBComparable!) -> ComparisonResult
|
||||
}
|
||||
|
||||
extension NSNumber: NMBComparable {
|
||||
public func NMB_compare(_ otherObject: NMBComparable!) -> ComparisonResult {
|
||||
// swiftlint:disable:next force_cast
|
||||
return compare(otherObject as! NSNumber)
|
||||
}
|
||||
}
|
||||
extension NSString: NMBComparable {
|
||||
public func NMB_compare(_ otherObject: NMBComparable!) -> ComparisonResult {
|
||||
// swiftlint:disable:next force_cast
|
||||
return compare(otherObject as! String)
|
||||
}
|
||||
}
|
||||
#endif
|
||||
@@ -1,147 +0,0 @@
|
||||
#if canImport(Foundation)
|
||||
import Foundation
|
||||
|
||||
internal class NotificationCollector {
|
||||
private(set) var observedNotifications: [Notification]
|
||||
private let notificationCenter: NotificationCenter
|
||||
private let names: Set<Notification.Name>
|
||||
private var tokens: [NSObjectProtocol]
|
||||
|
||||
required init(notificationCenter: NotificationCenter, names: Set<Notification.Name> = []) {
|
||||
self.notificationCenter = notificationCenter
|
||||
self.observedNotifications = []
|
||||
self.names = names
|
||||
self.tokens = []
|
||||
}
|
||||
|
||||
func startObserving() {
|
||||
func addObserver(forName name: Notification.Name?) -> NSObjectProtocol {
|
||||
return notificationCenter.addObserver(forName: name, object: nil, queue: nil) { [weak self] notification in
|
||||
// linux-swift gets confused by .append(n)
|
||||
self?.observedNotifications.append(notification)
|
||||
}
|
||||
}
|
||||
|
||||
if names.isEmpty {
|
||||
tokens.append(addObserver(forName: nil))
|
||||
} else {
|
||||
names.forEach { name in
|
||||
tokens.append(addObserver(forName: name))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
deinit {
|
||||
tokens.forEach { token in
|
||||
notificationCenter.removeObserver(token)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private let mainThread = pthread_self()
|
||||
|
||||
private func _postNotifications<Out>(
|
||||
_ predicate: Predicate<[Notification]>,
|
||||
from center: NotificationCenter,
|
||||
names: Set<Notification.Name> = []
|
||||
) -> Predicate<Out> {
|
||||
_ = mainThread // Force lazy-loading of this value
|
||||
let collector = NotificationCollector(notificationCenter: center, names: names)
|
||||
collector.startObserving()
|
||||
var once: Bool = false
|
||||
|
||||
return Predicate { actualExpression in
|
||||
let collectorNotificationsExpression = Expression(
|
||||
memoizedExpression: { _ in
|
||||
return collector.observedNotifications
|
||||
},
|
||||
location: actualExpression.location,
|
||||
withoutCaching: true
|
||||
)
|
||||
|
||||
assert(pthread_equal(mainThread, pthread_self()) != 0, "Only expecting closure to be evaluated on main thread.")
|
||||
if !once {
|
||||
once = true
|
||||
_ = try actualExpression.evaluate()
|
||||
}
|
||||
|
||||
let actualValue: String
|
||||
if collector.observedNotifications.isEmpty {
|
||||
actualValue = "no notifications"
|
||||
} else {
|
||||
actualValue = "<\(stringify(collector.observedNotifications))>"
|
||||
}
|
||||
|
||||
var result = try predicate.satisfies(collectorNotificationsExpression)
|
||||
result.message = result.message.replacedExpectation { message in
|
||||
return .expectedCustomValueTo(message.expectedMessage, actual: actualValue)
|
||||
}
|
||||
return result
|
||||
}
|
||||
}
|
||||
|
||||
public func postNotifications<Out>(
|
||||
_ predicate: Predicate<[Notification]>,
|
||||
from center: NotificationCenter = .default
|
||||
) -> Predicate<Out> {
|
||||
_postNotifications(predicate, from: center)
|
||||
}
|
||||
|
||||
@available(*, deprecated, renamed: "postNotifications(_:from:)")
|
||||
public func postNotifications<Out>(
|
||||
_ predicate: Predicate<[Notification]>,
|
||||
fromNotificationCenter center: NotificationCenter
|
||||
) -> Predicate<Out> {
|
||||
postNotifications(predicate, from: center)
|
||||
}
|
||||
|
||||
#if os(macOS)
|
||||
public func postDistributedNotifications<Out>(
|
||||
_ predicate: Predicate<[Notification]>,
|
||||
from center: DistributedNotificationCenter = .default(),
|
||||
names: Set<Notification.Name>
|
||||
) -> Predicate<Out> {
|
||||
_postNotifications(predicate, from: center, names: names)
|
||||
}
|
||||
#endif
|
||||
|
||||
@available(*, deprecated, message: "Use Predicate instead")
|
||||
public func postNotifications<T>(
|
||||
_ notificationsMatcher: T,
|
||||
from center: NotificationCenter = .default
|
||||
) -> Predicate<Any> where T: Matcher, T.ValueType == [Notification] {
|
||||
_ = mainThread // Force lazy-loading of this value
|
||||
let collector = NotificationCollector(notificationCenter: center)
|
||||
collector.startObserving()
|
||||
var once: Bool = false
|
||||
|
||||
return Predicate { actualExpression in
|
||||
let collectorNotificationsExpression = Expression(memoizedExpression: { _ in
|
||||
return collector.observedNotifications
|
||||
}, location: actualExpression.location, withoutCaching: true)
|
||||
|
||||
assert(pthread_equal(mainThread, pthread_self()) != 0, "Only expecting closure to be evaluated on main thread.")
|
||||
if !once {
|
||||
once = true
|
||||
_ = try actualExpression.evaluate()
|
||||
}
|
||||
|
||||
let failureMessage = FailureMessage()
|
||||
let match = try notificationsMatcher.matches(collectorNotificationsExpression, failureMessage: failureMessage)
|
||||
if collector.observedNotifications.isEmpty {
|
||||
failureMessage.actualValue = "no notifications"
|
||||
} else {
|
||||
failureMessage.actualValue = "<\(stringify(collector.observedNotifications))>"
|
||||
}
|
||||
return PredicateResult(bool: match, message: failureMessage.toExpectationMessage())
|
||||
}
|
||||
}
|
||||
|
||||
@available(*, deprecated, renamed: "postNotifications(_:from:)")
|
||||
public func postNotifications<T>(
|
||||
_ notificationsMatcher: T,
|
||||
fromNotificationCenter center: NotificationCenter
|
||||
) -> Predicate<Any> where T: Matcher, T.ValueType == [Notification] {
|
||||
return postNotifications(notificationsMatcher, from: center)
|
||||
}
|
||||
#endif
|
||||
-363
@@ -1,363 +0,0 @@
|
||||
// New Matcher API
|
||||
//
|
||||
|
||||
/// A Predicate is part of the new matcher API that provides assertions to expectations.
|
||||
///
|
||||
/// Given a code snippet:
|
||||
///
|
||||
/// expect(1).to(equal(2))
|
||||
/// ^^^^^^^^
|
||||
/// Called a "matcher"
|
||||
///
|
||||
/// A matcher consists of two parts a constructor function and the Predicate. The term Predicate
|
||||
/// is used as a separate name from Matcher to help transition custom matchers to the new Nimble
|
||||
/// matcher API.
|
||||
///
|
||||
/// The Predicate provide the heavy lifting on how to assert against a given value. Internally,
|
||||
/// predicates are simple wrappers around closures to provide static type information and
|
||||
/// allow composition and wrapping of existing behaviors.
|
||||
public struct Predicate<T> {
|
||||
fileprivate var matcher: (Expression<T>) throws -> PredicateResult
|
||||
|
||||
/// Constructs a predicate that knows how take a given value
|
||||
public init(_ matcher: @escaping (Expression<T>) throws -> PredicateResult) {
|
||||
self.matcher = matcher
|
||||
}
|
||||
|
||||
/// Uses a predicate on a given value to see if it passes the predicate.
|
||||
///
|
||||
/// @param expression The value to run the predicate's logic against
|
||||
/// @returns A predicate result indicate passing or failing and an associated error message.
|
||||
public func satisfies(_ expression: Expression<T>) throws -> PredicateResult {
|
||||
return try matcher(expression)
|
||||
}
|
||||
}
|
||||
|
||||
/// Provides convenience helpers to defining predicates
|
||||
extension Predicate {
|
||||
/// Like Predicate() constructor, but automatically guard against nil (actual) values
|
||||
public static func define(matcher: @escaping (Expression<T>) throws -> PredicateResult) -> Predicate<T> {
|
||||
return Predicate<T> { actual in
|
||||
return try matcher(actual)
|
||||
}.requireNonNil
|
||||
}
|
||||
|
||||
/// Defines a predicate with a default message that can be returned in the closure
|
||||
/// Also ensures the predicate's actual value cannot pass with `nil` given.
|
||||
public static func define(_ message: String = "match", matcher: @escaping (Expression<T>, ExpectationMessage) throws -> PredicateResult) -> Predicate<T> {
|
||||
return Predicate<T> { actual in
|
||||
return try matcher(actual, .expectedActualValueTo(message))
|
||||
}.requireNonNil
|
||||
}
|
||||
|
||||
/// Defines a predicate with a default message that can be returned in the closure
|
||||
/// Unlike `define`, this allows nil values to succeed if the given closure chooses to.
|
||||
public static func defineNilable(_ message: String = "match", matcher: @escaping (Expression<T>, ExpectationMessage) throws -> PredicateResult) -> Predicate<T> {
|
||||
return Predicate<T> { actual in
|
||||
return try matcher(actual, .expectedActualValueTo(message))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension Predicate {
|
||||
/// Provides a simple predicate definition that provides no control over the predefined
|
||||
/// error message.
|
||||
///
|
||||
/// Also ensures the predicate's actual value cannot pass with `nil` given.
|
||||
public static func simple(_ message: String = "match", matcher: @escaping (Expression<T>) throws -> PredicateStatus) -> Predicate<T> {
|
||||
return Predicate<T> { actual in
|
||||
return PredicateResult(status: try matcher(actual), message: .expectedActualValueTo(message))
|
||||
}.requireNonNil
|
||||
}
|
||||
|
||||
/// Provides a simple predicate definition that provides no control over the predefined
|
||||
/// error message.
|
||||
///
|
||||
/// Unlike `simple`, this allows nil values to succeed if the given closure chooses to.
|
||||
public static func simpleNilable(_ message: String = "match", matcher: @escaping (Expression<T>) throws -> PredicateStatus) -> Predicate<T> {
|
||||
return Predicate<T> { actual in
|
||||
return PredicateResult(status: try matcher(actual), message: .expectedActualValueTo(message))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// The Expectation style intended for comparison to a PredicateStatus.
|
||||
public enum ExpectationStyle {
|
||||
case toMatch, toNotMatch
|
||||
}
|
||||
|
||||
/// The value that a Predicates return to describe if the given (actual) value matches the
|
||||
/// predicate.
|
||||
public struct PredicateResult {
|
||||
/// Status indicates if the predicate matches, does not match, or fails.
|
||||
public var status: PredicateStatus
|
||||
/// The error message that can be displayed if it does not match
|
||||
public var message: ExpectationMessage
|
||||
|
||||
/// Constructs a new PredicateResult with a given status and error message
|
||||
public init(status: PredicateStatus, message: ExpectationMessage) {
|
||||
self.status = status
|
||||
self.message = message
|
||||
}
|
||||
|
||||
/// Shorthand to PredicateResult(status: PredicateStatus(bool: bool), message: message)
|
||||
public init(bool: Bool, message: ExpectationMessage) {
|
||||
self.status = PredicateStatus(bool: bool)
|
||||
self.message = message
|
||||
}
|
||||
|
||||
/// Converts the result to a boolean based on what the expectation intended
|
||||
public func toBoolean(expectation style: ExpectationStyle) -> Bool {
|
||||
return status.toBoolean(expectation: style)
|
||||
}
|
||||
}
|
||||
|
||||
/// PredicateStatus is a trinary that indicates if a Predicate matches a given value or not
|
||||
public enum PredicateStatus {
|
||||
/// Matches indicates if the predicate / matcher passes with the given value
|
||||
///
|
||||
/// For example, `equals(1)` returns `.matches` for `expect(1).to(equal(1))`.
|
||||
case matches
|
||||
/// DoesNotMatch indicates if the predicate / matcher fails with the given value, but *would*
|
||||
/// succeed if the expectation was inverted.
|
||||
///
|
||||
/// For example, `equals(2)` returns `.doesNotMatch` for `expect(1).toNot(equal(2))`.
|
||||
case doesNotMatch
|
||||
/// Fail indicates the predicate will never satisfy with the given value in any case.
|
||||
/// A perfect example is that most matchers fail whenever given `nil`.
|
||||
///
|
||||
/// Using `equal(1)` fails both `expect(nil).to(equal(1))` and `expect(nil).toNot(equal(1))`.
|
||||
/// Note: Predicate's `requireNonNil` property will also provide this feature mostly for free.
|
||||
/// Your predicate will still need to guard against nils, but error messaging will be
|
||||
/// handled for you.
|
||||
case fail
|
||||
|
||||
/// Converts a boolean to either .matches (if true) or .doesNotMatch (if false).
|
||||
public init(bool matches: Bool) {
|
||||
if matches {
|
||||
self = .matches
|
||||
} else {
|
||||
self = .doesNotMatch
|
||||
}
|
||||
}
|
||||
|
||||
private func shouldMatch() -> Bool {
|
||||
switch self {
|
||||
case .matches: return true
|
||||
case .doesNotMatch, .fail: return false
|
||||
}
|
||||
}
|
||||
|
||||
private func shouldNotMatch() -> Bool {
|
||||
switch self {
|
||||
case .doesNotMatch: return true
|
||||
case .matches, .fail: return false
|
||||
}
|
||||
}
|
||||
|
||||
/// Converts the PredicateStatus result to a boolean based on what the expectation intended
|
||||
internal func toBoolean(expectation style: ExpectationStyle) -> Bool {
|
||||
if style == .toMatch {
|
||||
return shouldMatch()
|
||||
} else {
|
||||
return shouldNotMatch()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension Predicate {
|
||||
/// Compatibility layer for old Matcher API, deprecated.
|
||||
/// Emulates the MatcherFunc API
|
||||
internal static func _fromDeprecatedClosure(_ matcher: @escaping (Expression<T>, FailureMessage) throws -> Bool) -> Predicate {
|
||||
// swiftlint:disable:previous identifier_name
|
||||
return Predicate { actual in
|
||||
let failureMessage = FailureMessage()
|
||||
let result = try matcher(actual, failureMessage)
|
||||
return PredicateResult(
|
||||
status: PredicateStatus(bool: result),
|
||||
message: failureMessage.toExpectationMessage()
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Backwards compatibility until Old Matcher API removal
|
||||
@available(*, deprecated, message: "Use Predicate directly instead")
|
||||
extension Predicate: Matcher {
|
||||
/// Compatibility layer for old Matcher API, deprecated
|
||||
public static func fromDeprecatedFullClosure(_ matcher: @escaping (Expression<T>, FailureMessage, Bool) throws -> Bool) -> Predicate {
|
||||
return Predicate { actual in
|
||||
let failureMessage = FailureMessage()
|
||||
let result = try matcher(actual, failureMessage, true)
|
||||
return PredicateResult(
|
||||
status: PredicateStatus(bool: result),
|
||||
message: failureMessage.toExpectationMessage()
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/// Compatibility layer for old Matcher API, deprecated.
|
||||
/// Emulates the MatcherFunc API
|
||||
public static func fromDeprecatedClosure(_ matcher: @escaping (Expression<T>, FailureMessage) throws -> Bool) -> Predicate {
|
||||
return _fromDeprecatedClosure(matcher)
|
||||
}
|
||||
|
||||
/// Compatibility layer for old Matcher API, deprecated.
|
||||
/// Same as calling .predicate on a MatcherFunc or NonNilMatcherFunc type.
|
||||
public static func fromDeprecatedMatcher<M>(_ matcher: M) -> Predicate where M: Matcher, M.ValueType == T {
|
||||
return self.fromDeprecatedFullClosure(matcher.toClosure)
|
||||
}
|
||||
|
||||
/// Deprecated Matcher API, use satisfies(_:_) instead
|
||||
public func matches(_ actualExpression: Expression<T>, failureMessage: FailureMessage) throws -> Bool {
|
||||
let result = try satisfies(actualExpression)
|
||||
result.message.update(failureMessage: failureMessage)
|
||||
return result.toBoolean(expectation: .toMatch)
|
||||
}
|
||||
|
||||
/// Deprecated Matcher API, use satisfies(_:_) instead
|
||||
public func doesNotMatch(_ actualExpression: Expression<T>, failureMessage: FailureMessage) throws -> Bool {
|
||||
let result = try satisfies(actualExpression)
|
||||
result.message.update(failureMessage: failureMessage)
|
||||
return result.toBoolean(expectation: .toNotMatch)
|
||||
}
|
||||
}
|
||||
|
||||
extension Predicate {
|
||||
// Someday, make this public? Needs documentation
|
||||
internal func after(f: @escaping (Expression<T>, PredicateResult) throws -> PredicateResult) -> Predicate<T> {
|
||||
// swiftlint:disable:previous identifier_name
|
||||
return Predicate { actual -> PredicateResult in
|
||||
let result = try self.satisfies(actual)
|
||||
return try f(actual, result)
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns a new Predicate based on the current one that always fails if nil is given as
|
||||
/// the actual value.
|
||||
///
|
||||
/// This replaces `NonNilMatcherFunc`.
|
||||
public var requireNonNil: Predicate<T> {
|
||||
return after { actual, result in
|
||||
if try actual.evaluate() == nil {
|
||||
return PredicateResult(
|
||||
status: .fail,
|
||||
message: result.message.appendedBeNilHint()
|
||||
)
|
||||
}
|
||||
return result
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#if canImport(Darwin)
|
||||
import class Foundation.NSObject
|
||||
|
||||
public typealias PredicateBlock = (_ actualExpression: Expression<NSObject>) throws -> NMBPredicateResult
|
||||
|
||||
public class NMBPredicate: NSObject {
|
||||
private let predicate: PredicateBlock
|
||||
|
||||
public init(predicate: @escaping PredicateBlock) {
|
||||
self.predicate = predicate
|
||||
}
|
||||
|
||||
func satisfies(_ expression: @escaping () throws -> NSObject?, location: SourceLocation) -> NMBPredicateResult {
|
||||
let expr = Expression(expression: expression, location: location)
|
||||
do {
|
||||
return try self.predicate(expr)
|
||||
} catch let error {
|
||||
return PredicateResult(status: .fail, message: .fail("unexpected error thrown: <\(error)>")).toObjectiveC()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension NMBPredicate: NMBMatcher {
|
||||
public func matches(_ actualBlock: @escaping () -> NSObject?, failureMessage: FailureMessage, location: SourceLocation) -> Bool {
|
||||
let result = satisfies(actualBlock, location: location).toSwift()
|
||||
result.message.update(failureMessage: failureMessage)
|
||||
return result.status.toBoolean(expectation: .toMatch)
|
||||
}
|
||||
|
||||
public func doesNotMatch(_ actualBlock: @escaping () -> NSObject?, failureMessage: FailureMessage, location: SourceLocation) -> Bool {
|
||||
let result = satisfies(actualBlock, location: location).toSwift()
|
||||
result.message.update(failureMessage: failureMessage)
|
||||
return result.status.toBoolean(expectation: .toNotMatch)
|
||||
}
|
||||
}
|
||||
|
||||
final public class NMBPredicateResult: NSObject {
|
||||
public var status: NMBPredicateStatus
|
||||
public var message: NMBExpectationMessage
|
||||
|
||||
public init(status: NMBPredicateStatus, message: NMBExpectationMessage) {
|
||||
self.status = status
|
||||
self.message = message
|
||||
}
|
||||
|
||||
public init(bool success: Bool, message: NMBExpectationMessage) {
|
||||
self.status = NMBPredicateStatus.from(bool: success)
|
||||
self.message = message
|
||||
}
|
||||
|
||||
public func toSwift() -> PredicateResult {
|
||||
return PredicateResult(status: status.toSwift(),
|
||||
message: message.toSwift())
|
||||
}
|
||||
}
|
||||
|
||||
extension PredicateResult {
|
||||
public func toObjectiveC() -> NMBPredicateResult {
|
||||
return NMBPredicateResult(status: status.toObjectiveC(), message: message.toObjectiveC())
|
||||
}
|
||||
}
|
||||
|
||||
final public class NMBPredicateStatus: NSObject {
|
||||
private let status: Int
|
||||
private init(status: Int) {
|
||||
self.status = status
|
||||
}
|
||||
|
||||
public static let matches: NMBPredicateStatus = NMBPredicateStatus(status: 0)
|
||||
public static let doesNotMatch: NMBPredicateStatus = NMBPredicateStatus(status: 1)
|
||||
public static let fail: NMBPredicateStatus = NMBPredicateStatus(status: 2)
|
||||
|
||||
public override var hash: Int { return self.status.hashValue }
|
||||
|
||||
public override func isEqual(_ object: Any?) -> Bool {
|
||||
guard let otherPredicate = object as? NMBPredicateStatus else {
|
||||
return false
|
||||
}
|
||||
return self.status == otherPredicate.status
|
||||
}
|
||||
|
||||
public static func from(status: PredicateStatus) -> NMBPredicateStatus {
|
||||
switch status {
|
||||
case .matches: return self.matches
|
||||
case .doesNotMatch: return self.doesNotMatch
|
||||
case .fail: return self.fail
|
||||
}
|
||||
}
|
||||
|
||||
public static func from(bool success: Bool) -> NMBPredicateStatus {
|
||||
return self.from(status: PredicateStatus(bool: success))
|
||||
}
|
||||
|
||||
public func toSwift() -> PredicateStatus {
|
||||
switch status {
|
||||
case NMBPredicateStatus.matches.status: return .matches
|
||||
case NMBPredicateStatus.doesNotMatch.status: return .doesNotMatch
|
||||
case NMBPredicateStatus.fail.status: return .fail
|
||||
default:
|
||||
internalError("Unhandle status for NMBPredicateStatus")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension PredicateStatus {
|
||||
public func toObjectiveC() -> NMBPredicateStatus {
|
||||
return NMBPredicateStatus.from(status: self)
|
||||
}
|
||||
}
|
||||
|
||||
#endif
|
||||
@@ -1,222 +0,0 @@
|
||||
// This matcher requires the Objective-C, and being built by Xcode rather than the Swift Package Manager
|
||||
#if canImport(Darwin) && !SWIFT_PACKAGE
|
||||
import class Foundation.NSObject
|
||||
import class Foundation.NSDictionary
|
||||
import class Foundation.NSException
|
||||
|
||||
/// A Nimble matcher that succeeds when the actual expression raises an
|
||||
/// exception with the specified name, reason, and/or userInfo.
|
||||
///
|
||||
/// Alternatively, you can pass a closure to do any arbitrary custom matching
|
||||
/// to the raised exception. The closure only gets called when an exception
|
||||
/// is raised.
|
||||
///
|
||||
/// nil arguments indicates that the matcher should not attempt to match against
|
||||
/// that parameter.
|
||||
public func raiseException<Out>(
|
||||
named: NSExceptionName? = nil,
|
||||
reason: String? = nil,
|
||||
userInfo: NSDictionary? = nil,
|
||||
closure: ((NSException) -> Void)? = nil
|
||||
) -> Predicate<Out> {
|
||||
return raiseException(named: named?.rawValue, reason: reason, userInfo: userInfo, closure: closure)
|
||||
}
|
||||
|
||||
/// A Nimble matcher that succeeds when the actual expression raises an
|
||||
/// exception with the specified name, reason, and/or userInfo.
|
||||
///
|
||||
/// Alternatively, you can pass a closure to do any arbitrary custom matching
|
||||
/// to the raised exception. The closure only gets called when an exception
|
||||
/// is raised.
|
||||
///
|
||||
/// nil arguments indicates that the matcher should not attempt to match against
|
||||
/// that parameter.
|
||||
public func raiseException<Out>(
|
||||
named: String?,
|
||||
reason: String? = nil,
|
||||
userInfo: NSDictionary? = nil,
|
||||
closure: ((NSException) -> Void)? = nil
|
||||
) -> Predicate<Out> {
|
||||
return Predicate { actualExpression in
|
||||
var exception: NSException?
|
||||
let capture = NMBExceptionCapture(handler: ({ e in
|
||||
exception = e
|
||||
}), finally: nil)
|
||||
|
||||
do {
|
||||
try capture.tryBlockThrows {
|
||||
_ = try actualExpression.evaluate()
|
||||
}
|
||||
} catch {
|
||||
return PredicateResult(status: .fail, message: .fail("unexpected error thrown: <\(error)>"))
|
||||
}
|
||||
|
||||
let message = messageForException(
|
||||
exception: exception,
|
||||
named: named,
|
||||
reason: reason,
|
||||
userInfo: userInfo,
|
||||
closure: closure
|
||||
)
|
||||
|
||||
let matches = exceptionMatchesNonNilFieldsOrClosure(
|
||||
exception,
|
||||
named: named,
|
||||
reason: reason,
|
||||
userInfo: userInfo,
|
||||
closure: closure
|
||||
)
|
||||
return PredicateResult(bool: matches, message: message)
|
||||
}
|
||||
}
|
||||
|
||||
internal func messageForException(
|
||||
exception: NSException?,
|
||||
named: String?,
|
||||
reason: String?,
|
||||
userInfo: NSDictionary?,
|
||||
closure: ((NSException) -> Void)?
|
||||
) -> ExpectationMessage {
|
||||
var rawMessage: String = "raise exception"
|
||||
|
||||
if let named = named {
|
||||
rawMessage += " with name <\(named)>"
|
||||
}
|
||||
if let reason = reason {
|
||||
rawMessage += " with reason <\(reason)>"
|
||||
}
|
||||
if let userInfo = userInfo {
|
||||
rawMessage += " with userInfo <\(userInfo)>"
|
||||
}
|
||||
if closure != nil {
|
||||
rawMessage += " that satisfies block"
|
||||
}
|
||||
if named == nil && reason == nil && userInfo == nil && closure == nil {
|
||||
rawMessage = "raise any exception"
|
||||
}
|
||||
|
||||
let actual: String
|
||||
if let exception = exception {
|
||||
// swiftlint:disable:next line_length
|
||||
actual = "\(String(describing: type(of: exception))) { name=\(exception.name), reason='\(stringify(exception.reason))', userInfo=\(stringify(exception.userInfo)) }"
|
||||
} else {
|
||||
actual = "no exception"
|
||||
}
|
||||
|
||||
return .expectedCustomValueTo(rawMessage, actual: actual)
|
||||
}
|
||||
|
||||
internal func exceptionMatchesNonNilFieldsOrClosure(
|
||||
_ exception: NSException?,
|
||||
named: String?,
|
||||
reason: String?,
|
||||
userInfo: NSDictionary?,
|
||||
closure: ((NSException) -> Void)?) -> Bool {
|
||||
var matches = false
|
||||
|
||||
if let exception = exception {
|
||||
matches = true
|
||||
|
||||
if let named = named, exception.name.rawValue != named {
|
||||
matches = false
|
||||
}
|
||||
if reason != nil && exception.reason != reason {
|
||||
matches = false
|
||||
}
|
||||
if let userInfo = userInfo, let exceptionUserInfo = exception.userInfo,
|
||||
(exceptionUserInfo as NSDictionary) != userInfo {
|
||||
matches = false
|
||||
}
|
||||
if let closure = closure {
|
||||
let assertions = gatherFailingExpectations {
|
||||
closure(exception)
|
||||
}
|
||||
let messages = assertions.map { $0.message }
|
||||
if messages.count > 0 {
|
||||
matches = false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return matches
|
||||
}
|
||||
|
||||
public class NMBObjCRaiseExceptionPredicate: NMBPredicate {
|
||||
private let _name: String?
|
||||
private let _reason: String?
|
||||
private let _userInfo: NSDictionary?
|
||||
private let _block: ((NSException) -> Void)?
|
||||
|
||||
fileprivate init(name: String?, reason: String?, userInfo: NSDictionary?, block: ((NSException) -> Void)?) {
|
||||
_name = name
|
||||
_reason = reason
|
||||
_userInfo = userInfo
|
||||
_block = block
|
||||
|
||||
let predicate: Predicate<NSObject> = raiseException(
|
||||
named: name,
|
||||
reason: reason,
|
||||
userInfo: userInfo,
|
||||
closure: block
|
||||
)
|
||||
let predicateBlock: PredicateBlock = { actualExpression in
|
||||
return try predicate.satisfies(actualExpression).toObjectiveC()
|
||||
}
|
||||
super.init(predicate: predicateBlock)
|
||||
}
|
||||
|
||||
@objc public var named: (_ name: String) -> NMBObjCRaiseExceptionPredicate {
|
||||
let (reason, userInfo, block) = (_reason, _userInfo, _block)
|
||||
return { name in
|
||||
return NMBObjCRaiseExceptionPredicate(
|
||||
name: name,
|
||||
reason: reason,
|
||||
userInfo: userInfo,
|
||||
block: block
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@objc public var reason: (_ reason: String?) -> NMBObjCRaiseExceptionPredicate {
|
||||
let (name, userInfo, block) = (_name, _userInfo, _block)
|
||||
return { reason in
|
||||
return NMBObjCRaiseExceptionPredicate(
|
||||
name: name,
|
||||
reason: reason,
|
||||
userInfo: userInfo,
|
||||
block: block
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@objc public var userInfo: (_ userInfo: NSDictionary?) -> NMBObjCRaiseExceptionPredicate {
|
||||
let (name, reason, block) = (_name, _reason, _block)
|
||||
return { userInfo in
|
||||
return NMBObjCRaiseExceptionPredicate(
|
||||
name: name,
|
||||
reason: reason,
|
||||
userInfo: userInfo,
|
||||
block: block
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@objc public var satisfyingBlock: (_ block: ((NSException) -> Void)?) -> NMBObjCRaiseExceptionPredicate {
|
||||
let (name, reason, userInfo) = (_name, _reason, _userInfo)
|
||||
return { block in
|
||||
return NMBObjCRaiseExceptionPredicate(
|
||||
name: name,
|
||||
reason: reason,
|
||||
userInfo: userInfo,
|
||||
block: block
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension NMBPredicate {
|
||||
@objc public class func raiseExceptionMatcher() -> NMBObjCRaiseExceptionPredicate {
|
||||
return NMBObjCRaiseExceptionPredicate(name: nil, reason: nil, userInfo: nil, block: nil)
|
||||
}
|
||||
}
|
||||
#endif
|
||||
@@ -1,87 +0,0 @@
|
||||
/// A Nimble matcher that succeeds when the actual value matches with all of the matchers
|
||||
/// provided in the variable list of matchers.
|
||||
public func satisfyAllOf<T>(_ predicates: Predicate<T>...) -> Predicate<T> {
|
||||
return satisfyAllOf(predicates)
|
||||
}
|
||||
|
||||
/// A Nimble matcher that succeeds when the actual value matches with all of the matchers
|
||||
/// provided in the variable list of matchers.
|
||||
@available(*, deprecated, message: "Use Predicate instead")
|
||||
public func satisfyAllOf<T, U>(_ matchers: U...) -> Predicate<T>
|
||||
where U: Matcher, U.ValueType == T {
|
||||
return satisfyAllOf(matchers.map { $0.predicate })
|
||||
}
|
||||
|
||||
internal func satisfyAllOf<T>(_ predicates: [Predicate<T>]) -> Predicate<T> {
|
||||
return Predicate.define { actualExpression in
|
||||
var postfixMessages = [String]()
|
||||
var matches = true
|
||||
for predicate in predicates {
|
||||
let result = try predicate.satisfies(actualExpression)
|
||||
if result.toBoolean(expectation: .toNotMatch) {
|
||||
matches = false
|
||||
}
|
||||
postfixMessages.append("{\(result.message.expectedMessage)}")
|
||||
}
|
||||
|
||||
var msg: ExpectationMessage
|
||||
if let actualValue = try actualExpression.evaluate() {
|
||||
msg = .expectedCustomValueTo(
|
||||
"match all of: " + postfixMessages.joined(separator: ", and "),
|
||||
actual: "\(actualValue)"
|
||||
)
|
||||
} else {
|
||||
msg = .expectedActualValueTo(
|
||||
"match all of: " + postfixMessages.joined(separator: ", and ")
|
||||
)
|
||||
}
|
||||
|
||||
return PredicateResult(bool: matches, message: msg)
|
||||
}
|
||||
}
|
||||
|
||||
public func && <T>(left: Predicate<T>, right: Predicate<T>) -> Predicate<T> {
|
||||
return satisfyAllOf(left, right)
|
||||
}
|
||||
|
||||
#if canImport(Darwin)
|
||||
import class Foundation.NSObject
|
||||
|
||||
extension NMBPredicate {
|
||||
@objc public class func satisfyAllOfMatcher(_ matchers: [NMBMatcher]) -> NMBPredicate {
|
||||
return NMBPredicate { actualExpression in
|
||||
if matchers.isEmpty {
|
||||
return NMBPredicateResult(
|
||||
status: NMBPredicateStatus.fail,
|
||||
message: NMBExpectationMessage(
|
||||
fail: "satisfyAllOf must be called with at least one matcher"
|
||||
)
|
||||
)
|
||||
}
|
||||
|
||||
var elementEvaluators = [Predicate<NSObject>]()
|
||||
for matcher in matchers {
|
||||
let elementEvaluator = Predicate<NSObject> { expression in
|
||||
if let predicate = matcher as? NMBPredicate {
|
||||
// swiftlint:disable:next line_length
|
||||
return predicate.satisfies({ try expression.evaluate() }, location: actualExpression.location).toSwift()
|
||||
} else {
|
||||
let failureMessage = FailureMessage()
|
||||
let success = matcher.matches(
|
||||
// swiftlint:disable:next force_try
|
||||
{ try! expression.evaluate() },
|
||||
failureMessage: failureMessage,
|
||||
location: actualExpression.location
|
||||
)
|
||||
return PredicateResult(bool: success, message: failureMessage.toExpectationMessage())
|
||||
}
|
||||
}
|
||||
|
||||
elementEvaluators.append(elementEvaluator)
|
||||
}
|
||||
|
||||
return try satisfyAllOf(elementEvaluators).satisfies(actualExpression).toObjectiveC()
|
||||
}
|
||||
}
|
||||
}
|
||||
#endif
|
||||
@@ -1,97 +0,0 @@
|
||||
/// A Nimble matcher that succeeds when the actual value matches with any of the matchers
|
||||
/// provided in the variable list of matchers.
|
||||
public func satisfyAnyOf<T>(_ predicates: Predicate<T>...) -> Predicate<T> {
|
||||
return satisfyAnyOf(predicates)
|
||||
}
|
||||
|
||||
/// A Nimble matcher that succeeds when the actual value matches with any of the matchers
|
||||
/// provided in the variable list of matchers.
|
||||
@available(*, deprecated, message: "Use Predicate instead")
|
||||
public func satisfyAnyOf<T, U>(_ matchers: U...) -> Predicate<T>
|
||||
where U: Matcher, U.ValueType == T {
|
||||
return satisfyAnyOf(matchers.map { $0.predicate })
|
||||
}
|
||||
|
||||
internal func satisfyAnyOf<T>(_ predicates: [Predicate<T>]) -> Predicate<T> {
|
||||
return Predicate.define { actualExpression in
|
||||
var postfixMessages = [String]()
|
||||
var matches = false
|
||||
for predicate in predicates {
|
||||
let result = try predicate.satisfies(actualExpression)
|
||||
if result.toBoolean(expectation: .toMatch) {
|
||||
matches = true
|
||||
}
|
||||
postfixMessages.append("{\(result.message.expectedMessage)}")
|
||||
}
|
||||
|
||||
var msg: ExpectationMessage
|
||||
if let actualValue = try actualExpression.evaluate() {
|
||||
msg = .expectedCustomValueTo(
|
||||
"match one of: " + postfixMessages.joined(separator: ", or "),
|
||||
actual: "\(actualValue)"
|
||||
)
|
||||
} else {
|
||||
msg = .expectedActualValueTo(
|
||||
"match one of: " + postfixMessages.joined(separator: ", or ")
|
||||
)
|
||||
}
|
||||
|
||||
return PredicateResult(bool: matches, message: msg)
|
||||
}
|
||||
}
|
||||
|
||||
public func || <T>(left: Predicate<T>, right: Predicate<T>) -> Predicate<T> {
|
||||
return satisfyAnyOf(left, right)
|
||||
}
|
||||
|
||||
@available(*, deprecated, message: "Use Predicate instead")
|
||||
public func || <T>(left: NonNilMatcherFunc<T>, right: NonNilMatcherFunc<T>) -> Predicate<T> {
|
||||
return satisfyAnyOf(left, right)
|
||||
}
|
||||
|
||||
@available(*, deprecated, message: "Use Predicate instead")
|
||||
public func || <T>(left: MatcherFunc<T>, right: MatcherFunc<T>) -> Predicate<T> {
|
||||
return satisfyAnyOf(left, right)
|
||||
}
|
||||
|
||||
#if canImport(Darwin)
|
||||
import class Foundation.NSObject
|
||||
|
||||
extension NMBPredicate {
|
||||
@objc public class func satisfyAnyOfMatcher(_ matchers: [NMBMatcher]) -> NMBPredicate {
|
||||
return NMBPredicate { actualExpression in
|
||||
if matchers.isEmpty {
|
||||
return NMBPredicateResult(
|
||||
status: NMBPredicateStatus.fail,
|
||||
message: NMBExpectationMessage(
|
||||
fail: "satisfyAnyOf must be called with at least one matcher"
|
||||
)
|
||||
)
|
||||
}
|
||||
|
||||
var elementEvaluators = [Predicate<NSObject>]()
|
||||
for matcher in matchers {
|
||||
let elementEvaluator = Predicate<NSObject> { expression in
|
||||
if let predicate = matcher as? NMBPredicate {
|
||||
// swiftlint:disable:next line_length
|
||||
return predicate.satisfies({ try expression.evaluate() }, location: actualExpression.location).toSwift()
|
||||
} else {
|
||||
let failureMessage = FailureMessage()
|
||||
let success = matcher.matches(
|
||||
// swiftlint:disable:next force_try
|
||||
{ try! expression.evaluate() },
|
||||
failureMessage: failureMessage,
|
||||
location: actualExpression.location
|
||||
)
|
||||
return PredicateResult(bool: success, message: failureMessage.toExpectationMessage())
|
||||
}
|
||||
}
|
||||
|
||||
elementEvaluators.append(elementEvaluator)
|
||||
}
|
||||
|
||||
return try satisfyAnyOf(elementEvaluators).satisfies(actualExpression).toObjectiveC()
|
||||
}
|
||||
}
|
||||
}
|
||||
#endif
|
||||
@@ -1,51 +0,0 @@
|
||||
#if canImport(CwlPreconditionTesting) && (os(macOS) || os(iOS))
|
||||
import CwlPreconditionTesting
|
||||
#elseif canImport(CwlPosixPreconditionTesting)
|
||||
import CwlPosixPreconditionTesting
|
||||
#endif
|
||||
|
||||
public func throwAssertion<Out>() -> Predicate<Out> {
|
||||
return Predicate { actualExpression in
|
||||
#if arch(x86_64) && canImport(Darwin)
|
||||
let message = ExpectationMessage.expectedTo("throw an assertion")
|
||||
|
||||
var actualError: Error?
|
||||
let caughtException: BadInstructionException? = catchBadInstruction {
|
||||
#if os(tvOS)
|
||||
if !NimbleEnvironment.activeInstance.suppressTVOSAssertionWarning {
|
||||
print()
|
||||
print("[Nimble Warning]: If you're getting stuck on a debugger breakpoint for a " +
|
||||
"fatal error while using throwAssertion(), please disable 'Debug Executable' " +
|
||||
"in your scheme. Go to 'Edit Scheme > Test > Info' and uncheck " +
|
||||
"'Debug Executable'. If you've already done that, suppress this warning " +
|
||||
"by setting `NimbleEnvironment.activeInstance.suppressTVOSAssertionWarning = true`. " +
|
||||
"This is required because the standard methods of catching assertions " +
|
||||
"(mach APIs) are unavailable for tvOS. Instead, the same mechanism the " +
|
||||
"debugger uses is the fallback method for tvOS."
|
||||
)
|
||||
print()
|
||||
NimbleEnvironment.activeInstance.suppressTVOSAssertionWarning = true
|
||||
}
|
||||
#endif
|
||||
do {
|
||||
_ = try actualExpression.evaluate()
|
||||
} catch {
|
||||
actualError = error
|
||||
}
|
||||
}
|
||||
|
||||
if let actualError = actualError {
|
||||
return PredicateResult(
|
||||
bool: false,
|
||||
message: message.appended(message: "; threw error instead <\(actualError)>")
|
||||
)
|
||||
} else {
|
||||
return PredicateResult(bool: caughtException != nil, message: message)
|
||||
}
|
||||
#else
|
||||
fatalError("The throwAssertion Nimble matcher can only run on x86_64 platforms with " +
|
||||
"Objective-C (e.g. macOS, iPhone 5s or later simulators). You can silence this error " +
|
||||
"by placing the test case inside an #if arch(x86_64) or canImport(Darwin) conditional statement")
|
||||
#endif
|
||||
}
|
||||
}
|
||||
-261
@@ -1,261 +0,0 @@
|
||||
/// A Nimble matcher that succeeds when the actual expression throws an
|
||||
/// error of the specified type or from the specified case.
|
||||
///
|
||||
/// Errors are tried to be compared by their implementation of Equatable,
|
||||
/// otherwise they fallback to comparison by _domain and _code.
|
||||
///
|
||||
/// Alternatively, you can pass a closure to do any arbitrary custom matching
|
||||
/// to the thrown error. The closure only gets called when an error was thrown.
|
||||
///
|
||||
/// nil arguments indicates that the matcher should not attempt to match against
|
||||
/// that parameter.
|
||||
public func throwError<Out>() -> Predicate<Out> {
|
||||
return Predicate { actualExpression in
|
||||
var actualError: Error?
|
||||
do {
|
||||
_ = try actualExpression.evaluate()
|
||||
} catch {
|
||||
actualError = error
|
||||
}
|
||||
|
||||
if let actualError = actualError {
|
||||
return PredicateResult(
|
||||
bool: true,
|
||||
message: .expectedCustomValueTo("throw any error", actual: "<\(actualError)>")
|
||||
)
|
||||
} else {
|
||||
return PredicateResult(
|
||||
bool: false,
|
||||
message: .expectedCustomValueTo("throw any error", actual: "no error")
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A Nimble matcher that succeeds when the actual expression throws an
|
||||
/// error of the specified type or from the specified case.
|
||||
///
|
||||
/// Errors are tried to be compared by their implementation of Equatable,
|
||||
/// otherwise they fallback to comparision by _domain and _code.
|
||||
///
|
||||
/// Alternatively, you can pass a closure to do any arbitrary custom matching
|
||||
/// to the thrown error. The closure only gets called when an error was thrown.
|
||||
///
|
||||
/// nil arguments indicates that the matcher should not attempt to match against
|
||||
/// that parameter.
|
||||
public func throwError<T: Error, Out>(_ error: T, closure: ((Error) -> Void)? = nil) -> Predicate<Out> {
|
||||
return Predicate { actualExpression in
|
||||
var actualError: Error?
|
||||
do {
|
||||
_ = try actualExpression.evaluate()
|
||||
} catch {
|
||||
actualError = error
|
||||
}
|
||||
|
||||
let message = messageForError(
|
||||
actualError: actualError,
|
||||
error: error,
|
||||
errorType: nil,
|
||||
closure: closure
|
||||
)
|
||||
|
||||
var matches = false
|
||||
if let actualError = actualError, errorMatchesExpectedError(actualError, expectedError: error) {
|
||||
matches = true
|
||||
|
||||
if let closure = closure {
|
||||
let assertions = gatherFailingExpectations {
|
||||
closure(actualError)
|
||||
}
|
||||
let messages = assertions.map { $0.message }
|
||||
if !messages.isEmpty {
|
||||
matches = false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return PredicateResult(bool: matches, message: message)
|
||||
}
|
||||
}
|
||||
|
||||
/// A Nimble matcher that succeeds when the actual expression throws an
|
||||
/// error of the specified type or from the specified case.
|
||||
///
|
||||
/// Errors are tried to be compared by their implementation of Equatable,
|
||||
/// otherwise they fallback to comparision by _domain and _code.
|
||||
///
|
||||
/// Alternatively, you can pass a closure to do any arbitrary custom matching
|
||||
/// to the thrown error. The closure only gets called when an error was thrown.
|
||||
///
|
||||
/// nil arguments indicates that the matcher should not attempt to match against
|
||||
/// that parameter.
|
||||
public func throwError<T: Error & Equatable, Out>(_ error: T, closure: ((T) -> Void)? = nil) -> Predicate<Out> {
|
||||
return Predicate { actualExpression in
|
||||
var actualError: Error?
|
||||
do {
|
||||
_ = try actualExpression.evaluate()
|
||||
} catch {
|
||||
actualError = error
|
||||
}
|
||||
|
||||
let message = messageForError(
|
||||
actualError: actualError,
|
||||
error: error,
|
||||
errorType: nil,
|
||||
closure: closure
|
||||
)
|
||||
|
||||
var matches = false
|
||||
if let actualError = actualError as? T, error == actualError {
|
||||
matches = true
|
||||
|
||||
if let closure = closure {
|
||||
let assertions = gatherFailingExpectations {
|
||||
closure(actualError)
|
||||
}
|
||||
let messages = assertions.map { $0.message }
|
||||
if !messages.isEmpty {
|
||||
matches = false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return PredicateResult(bool: matches, message: message)
|
||||
}
|
||||
}
|
||||
|
||||
/// A Nimble matcher that succeeds when the actual expression throws an
|
||||
/// error of the specified type or from the specified case.
|
||||
///
|
||||
/// Errors are tried to be compared by their implementation of Equatable,
|
||||
/// otherwise they fallback to comparision by _domain and _code.
|
||||
///
|
||||
/// Alternatively, you can pass a closure to do any arbitrary custom matching
|
||||
/// to the thrown error. The closure only gets called when an error was thrown.
|
||||
///
|
||||
/// nil arguments indicates that the matcher should not attempt to match against
|
||||
/// that parameter.
|
||||
public func throwError<T: Error, Out>(
|
||||
errorType: T.Type,
|
||||
closure: ((T) -> Void)? = nil
|
||||
) -> Predicate<Out> {
|
||||
return Predicate { actualExpression in
|
||||
var actualError: Error?
|
||||
do {
|
||||
_ = try actualExpression.evaluate()
|
||||
} catch {
|
||||
actualError = error
|
||||
}
|
||||
|
||||
let message = messageForError(
|
||||
actualError: actualError,
|
||||
error: nil,
|
||||
errorType: errorType,
|
||||
closure: closure
|
||||
)
|
||||
|
||||
var matches = false
|
||||
if let actualError = actualError {
|
||||
matches = true
|
||||
|
||||
if let actualError = actualError as? T {
|
||||
if let closure = closure {
|
||||
let assertions = gatherFailingExpectations {
|
||||
closure(actualError)
|
||||
}
|
||||
let messages = assertions.map { $0.message }
|
||||
if !messages.isEmpty {
|
||||
matches = false
|
||||
}
|
||||
}
|
||||
} else {
|
||||
matches = (actualError is T)
|
||||
// The closure expects another ErrorProtocol as argument, so this
|
||||
// is _supposed_ to fail, so that it becomes more obvious.
|
||||
if let closure = closure {
|
||||
let assertions = gatherExpectations {
|
||||
if let actual = actualError as? T {
|
||||
closure(actual)
|
||||
}
|
||||
}
|
||||
let messages = assertions.map { $0.message }
|
||||
if !messages.isEmpty {
|
||||
matches = false
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return PredicateResult(bool: matches, message: message)
|
||||
}
|
||||
}
|
||||
|
||||
/// A Nimble matcher that succeeds when the actual expression throws any
|
||||
/// error or when the passed closures' arbitrary custom matching succeeds.
|
||||
///
|
||||
/// This duplication to it's generic adequate is required to allow to receive
|
||||
/// values of the existential type `Error` in the closure.
|
||||
///
|
||||
/// The closure only gets called when an error was thrown.
|
||||
public func throwError<Out>(closure: @escaping ((Error) -> Void)) -> Predicate<Out> {
|
||||
return Predicate { actualExpression in
|
||||
var actualError: Error?
|
||||
do {
|
||||
_ = try actualExpression.evaluate()
|
||||
} catch {
|
||||
actualError = error
|
||||
}
|
||||
|
||||
let message = messageForError(actualError: actualError, closure: closure)
|
||||
|
||||
var matches = false
|
||||
if let actualError = actualError {
|
||||
matches = true
|
||||
|
||||
let assertions = gatherFailingExpectations {
|
||||
closure(actualError)
|
||||
}
|
||||
let messages = assertions.map { $0.message }
|
||||
if !messages.isEmpty {
|
||||
matches = false
|
||||
}
|
||||
}
|
||||
|
||||
return PredicateResult(bool: matches, message: message)
|
||||
}
|
||||
}
|
||||
|
||||
/// A Nimble matcher that succeeds when the actual expression throws any
|
||||
/// error or when the passed closures' arbitrary custom matching succeeds.
|
||||
///
|
||||
/// This duplication to it's generic adequate is required to allow to receive
|
||||
/// values of the existential type `Error` in the closure.
|
||||
///
|
||||
/// The closure only gets called when an error was thrown.
|
||||
public func throwError<T: Error, Out>(closure: @escaping ((T) -> Void)) -> Predicate<Out> {
|
||||
return Predicate { actualExpression in
|
||||
var actualError: Error?
|
||||
do {
|
||||
_ = try actualExpression.evaluate()
|
||||
} catch {
|
||||
actualError = error
|
||||
}
|
||||
|
||||
let message = messageForError(actualError: actualError, closure: closure)
|
||||
|
||||
var matches = false
|
||||
if let actualError = actualError as? T {
|
||||
matches = true
|
||||
|
||||
let assertions = gatherFailingExpectations {
|
||||
closure(actualError)
|
||||
}
|
||||
let messages = assertions.map { $0.message }
|
||||
if !messages.isEmpty {
|
||||
matches = false
|
||||
}
|
||||
}
|
||||
|
||||
return PredicateResult(bool: matches, message: message)
|
||||
}
|
||||
}
|
||||
-37
@@ -1,37 +0,0 @@
|
||||
/**
|
||||
Used by the `toSucceed` matcher.
|
||||
|
||||
This is the return type for the closure.
|
||||
*/
|
||||
public enum ToSucceedResult {
|
||||
case succeeded
|
||||
case failed(reason: String)
|
||||
}
|
||||
|
||||
/**
|
||||
A Nimble matcher that takes in a closure for validation.
|
||||
|
||||
Return `.succeeded` when the validation succeeds.
|
||||
Return `.failed` with a failure reason when the validation fails.
|
||||
*/
|
||||
public func succeed() -> Predicate<() -> ToSucceedResult> {
|
||||
return Predicate.define { actualExpression in
|
||||
let optActual = try actualExpression.evaluate()
|
||||
guard let actual = optActual else {
|
||||
return PredicateResult(status: .fail, message: .fail("expected a closure, got <nil>"))
|
||||
}
|
||||
|
||||
switch actual() {
|
||||
case .succeeded:
|
||||
return PredicateResult(
|
||||
bool: true,
|
||||
message: .expectedCustomValueTo("succeed", actual: "<succeeded>")
|
||||
)
|
||||
case .failed(let reason):
|
||||
return PredicateResult(
|
||||
bool: false,
|
||||
message: .expectedCustomValueTo("succeed", actual: "<failed> because <\(reason)>")
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
Generated
-12
@@ -1,12 +0,0 @@
|
||||
#import <Foundation/Foundation.h>
|
||||
#import "NMBExceptionCapture.h"
|
||||
#import "NMBStringify.h"
|
||||
#import "DSL.h"
|
||||
|
||||
#if TARGET_OS_OSX || TARGET_OS_IOS
|
||||
#import "CwlMachBadInstructionHandler.h"
|
||||
#import "CwlCatchException.h"
|
||||
#endif
|
||||
|
||||
FOUNDATION_EXPORT double NimbleVersionNumber;
|
||||
FOUNDATION_EXPORT const unsigned char NimbleVersionString[];
|
||||
-371
@@ -1,371 +0,0 @@
|
||||
import CoreFoundation
|
||||
import Dispatch
|
||||
import Foundation
|
||||
|
||||
private let timeoutLeeway = DispatchTimeInterval.milliseconds(1)
|
||||
private let pollLeeway = DispatchTimeInterval.milliseconds(1)
|
||||
|
||||
/// Stores debugging information about callers
|
||||
internal struct WaitingInfo: CustomStringConvertible {
|
||||
let name: String
|
||||
let file: FileString
|
||||
let lineNumber: UInt
|
||||
|
||||
var description: String {
|
||||
return "\(name) at \(file):\(lineNumber)"
|
||||
}
|
||||
}
|
||||
|
||||
internal protocol WaitLock {
|
||||
func acquireWaitingLock(_ fnName: String, file: FileString, line: UInt)
|
||||
func releaseWaitingLock()
|
||||
func isWaitingLocked() -> Bool
|
||||
}
|
||||
|
||||
internal class AssertionWaitLock: WaitLock {
|
||||
private var currentWaiter: WaitingInfo?
|
||||
init() { }
|
||||
|
||||
func acquireWaitingLock(_ fnName: String, file: FileString, line: UInt) {
|
||||
let info = WaitingInfo(name: fnName, file: file, lineNumber: line)
|
||||
let isMainThread = Thread.isMainThread
|
||||
nimblePrecondition(
|
||||
isMainThread,
|
||||
"InvalidNimbleAPIUsage",
|
||||
"\(fnName) can only run on the main thread."
|
||||
)
|
||||
nimblePrecondition(
|
||||
currentWaiter == nil,
|
||||
"InvalidNimbleAPIUsage",
|
||||
"""
|
||||
Nested async expectations are not allowed to avoid creating flaky tests.
|
||||
|
||||
The call to
|
||||
\t\(info)
|
||||
triggered this exception because
|
||||
\t\(currentWaiter!)
|
||||
is currently managing the main run loop.
|
||||
"""
|
||||
)
|
||||
currentWaiter = info
|
||||
}
|
||||
|
||||
func isWaitingLocked() -> Bool {
|
||||
return currentWaiter != nil
|
||||
}
|
||||
|
||||
func releaseWaitingLock() {
|
||||
currentWaiter = nil
|
||||
}
|
||||
}
|
||||
|
||||
internal enum AwaitResult<T> {
|
||||
/// Incomplete indicates None (aka - this value hasn't been fulfilled yet)
|
||||
case incomplete
|
||||
/// TimedOut indicates the result reached its defined timeout limit before returning
|
||||
case timedOut
|
||||
/// BlockedRunLoop indicates the main runloop is too busy processing other blocks to trigger
|
||||
/// the timeout code.
|
||||
///
|
||||
/// This may also mean the async code waiting upon may have never actually ran within the
|
||||
/// required time because other timers & sources are running on the main run loop.
|
||||
case blockedRunLoop
|
||||
/// The async block successfully executed and returned a given result
|
||||
case completed(T)
|
||||
/// When a Swift Error is thrown
|
||||
case errorThrown(Error)
|
||||
/// When an Objective-C Exception is raised
|
||||
case raisedException(NSException)
|
||||
|
||||
func isIncomplete() -> Bool {
|
||||
switch self {
|
||||
case .incomplete: return true
|
||||
default: return false
|
||||
}
|
||||
}
|
||||
|
||||
func isCompleted() -> Bool {
|
||||
switch self {
|
||||
case .completed: return true
|
||||
default: return false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Holds the resulting value from an asynchronous expectation.
|
||||
/// This class is thread-safe at receiving an "response" to this promise.
|
||||
internal final class AwaitPromise<T> {
|
||||
private(set) internal var asyncResult: AwaitResult<T> = .incomplete
|
||||
private var signal: DispatchSemaphore
|
||||
|
||||
init() {
|
||||
signal = DispatchSemaphore(value: 1)
|
||||
}
|
||||
|
||||
deinit {
|
||||
signal.signal()
|
||||
}
|
||||
|
||||
/// Resolves the promise with the given result if it has not been resolved. Repeated calls to
|
||||
/// this method will resolve in a no-op.
|
||||
///
|
||||
/// @returns a Bool that indicates if the async result was accepted or rejected because another
|
||||
/// value was received first.
|
||||
func resolveResult(_ result: AwaitResult<T>) -> Bool {
|
||||
if signal.wait(timeout: .now()) == .success {
|
||||
self.asyncResult = result
|
||||
return true
|
||||
} else {
|
||||
return false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
internal struct AwaitTrigger {
|
||||
let timeoutSource: DispatchSourceTimer
|
||||
let actionSource: DispatchSourceTimer?
|
||||
let start: () throws -> Void
|
||||
}
|
||||
|
||||
/// Factory for building fully configured AwaitPromises and waiting for their results.
|
||||
///
|
||||
/// This factory stores all the state for an async expectation so that Await doesn't
|
||||
/// doesn't have to manage it.
|
||||
internal class AwaitPromiseBuilder<T> {
|
||||
let awaiter: Awaiter
|
||||
let waitLock: WaitLock
|
||||
let trigger: AwaitTrigger
|
||||
let promise: AwaitPromise<T>
|
||||
|
||||
internal init(
|
||||
awaiter: Awaiter,
|
||||
waitLock: WaitLock,
|
||||
promise: AwaitPromise<T>,
|
||||
trigger: AwaitTrigger) {
|
||||
self.awaiter = awaiter
|
||||
self.waitLock = waitLock
|
||||
self.promise = promise
|
||||
self.trigger = trigger
|
||||
}
|
||||
|
||||
func timeout(_ timeoutInterval: DispatchTimeInterval, forcefullyAbortTimeout: DispatchTimeInterval) -> Self {
|
||||
// = Discussion =
|
||||
//
|
||||
// There's a lot of technical decisions here that is useful to elaborate on. This is
|
||||
// definitely more lower-level than the previous NSRunLoop based implementation.
|
||||
//
|
||||
//
|
||||
// Why Dispatch Source?
|
||||
//
|
||||
//
|
||||
// We're using a dispatch source to have better control of the run loop behavior.
|
||||
// A timer source gives us deferred-timing control without having to rely as much on
|
||||
// a run loop's traditional dispatching machinery (eg - NSTimers, DefaultRunLoopMode, etc.)
|
||||
// which is ripe for getting corrupted by application code.
|
||||
//
|
||||
// And unlike dispatch_async(), we can control how likely our code gets prioritized to
|
||||
// executed (see leeway parameter) + DISPATCH_TIMER_STRICT.
|
||||
//
|
||||
// This timer is assumed to run on the HIGH priority queue to ensure it maintains the
|
||||
// highest priority over normal application / test code when possible.
|
||||
//
|
||||
//
|
||||
// Run Loop Management
|
||||
//
|
||||
// In order to properly interrupt the waiting behavior performed by this factory class,
|
||||
// this timer stops the main run loop to tell the waiter code that the result should be
|
||||
// checked.
|
||||
//
|
||||
// In addition, stopping the run loop is used to halt code executed on the main run loop.
|
||||
trigger.timeoutSource.schedule(
|
||||
deadline: DispatchTime.now() + timeoutInterval,
|
||||
repeating: .never,
|
||||
leeway: timeoutLeeway
|
||||
)
|
||||
trigger.timeoutSource.setEventHandler {
|
||||
guard self.promise.asyncResult.isIncomplete() else { return }
|
||||
let timedOutSem = DispatchSemaphore(value: 0)
|
||||
let semTimedOutOrBlocked = DispatchSemaphore(value: 0)
|
||||
semTimedOutOrBlocked.signal()
|
||||
let runLoop = CFRunLoopGetMain()
|
||||
#if canImport(Darwin)
|
||||
let runLoopMode = CFRunLoopMode.defaultMode.rawValue
|
||||
#else
|
||||
let runLoopMode = kCFRunLoopDefaultMode
|
||||
#endif
|
||||
CFRunLoopPerformBlock(runLoop, runLoopMode) {
|
||||
if semTimedOutOrBlocked.wait(timeout: .now()) == .success {
|
||||
timedOutSem.signal()
|
||||
semTimedOutOrBlocked.signal()
|
||||
if self.promise.resolveResult(.timedOut) {
|
||||
CFRunLoopStop(CFRunLoopGetMain())
|
||||
}
|
||||
}
|
||||
}
|
||||
// potentially interrupt blocking code on run loop to let timeout code run
|
||||
CFRunLoopStop(runLoop)
|
||||
let now = DispatchTime.now() + forcefullyAbortTimeout
|
||||
let didNotTimeOut = timedOutSem.wait(timeout: now) != .success
|
||||
let timeoutWasNotTriggered = semTimedOutOrBlocked.wait(timeout: .now()) == .success
|
||||
if didNotTimeOut && timeoutWasNotTriggered {
|
||||
if self.promise.resolveResult(.blockedRunLoop) {
|
||||
CFRunLoopStop(CFRunLoopGetMain())
|
||||
}
|
||||
}
|
||||
}
|
||||
return self
|
||||
}
|
||||
|
||||
/// Blocks for an asynchronous result.
|
||||
///
|
||||
/// @discussion
|
||||
/// This function must be executed on the main thread and cannot be nested. This is because
|
||||
/// this function (and it's related methods) coordinate through the main run loop. Tampering
|
||||
/// with the run loop can cause undesirable behavior.
|
||||
///
|
||||
/// This method will return an AwaitResult in the following cases:
|
||||
///
|
||||
/// - The main run loop is blocked by other operations and the async expectation cannot be
|
||||
/// be stopped.
|
||||
/// - The async expectation timed out
|
||||
/// - The async expectation succeeded
|
||||
/// - The async expectation raised an unexpected exception (objc)
|
||||
/// - The async expectation raised an unexpected error (swift)
|
||||
///
|
||||
/// The returned AwaitResult will NEVER be .incomplete.
|
||||
func wait(_ fnName: String = #function, file: FileString = #file, line: UInt = #line) -> AwaitResult<T> {
|
||||
waitLock.acquireWaitingLock(
|
||||
fnName,
|
||||
file: file,
|
||||
line: line)
|
||||
|
||||
let capture = NMBExceptionCapture(handler: ({ exception in
|
||||
_ = self.promise.resolveResult(.raisedException(exception))
|
||||
}), finally: ({
|
||||
self.waitLock.releaseWaitingLock()
|
||||
}))
|
||||
capture.tryBlock {
|
||||
do {
|
||||
try self.trigger.start()
|
||||
} catch let error {
|
||||
_ = self.promise.resolveResult(.errorThrown(error))
|
||||
}
|
||||
self.trigger.timeoutSource.resume()
|
||||
while self.promise.asyncResult.isIncomplete() {
|
||||
// Stopping the run loop does not work unless we run only 1 mode
|
||||
_ = RunLoop.current.run(mode: .default, before: .distantFuture)
|
||||
}
|
||||
|
||||
self.trigger.timeoutSource.cancel()
|
||||
if let asyncSource = self.trigger.actionSource {
|
||||
asyncSource.cancel()
|
||||
}
|
||||
}
|
||||
|
||||
return promise.asyncResult
|
||||
}
|
||||
}
|
||||
|
||||
internal class Awaiter {
|
||||
let waitLock: WaitLock
|
||||
let timeoutQueue: DispatchQueue
|
||||
let asyncQueue: DispatchQueue
|
||||
|
||||
internal init(
|
||||
waitLock: WaitLock,
|
||||
asyncQueue: DispatchQueue,
|
||||
timeoutQueue: DispatchQueue) {
|
||||
self.waitLock = waitLock
|
||||
self.asyncQueue = asyncQueue
|
||||
self.timeoutQueue = timeoutQueue
|
||||
}
|
||||
|
||||
private func createTimerSource(_ queue: DispatchQueue) -> DispatchSourceTimer {
|
||||
return DispatchSource.makeTimerSource(flags: .strict, queue: queue)
|
||||
}
|
||||
|
||||
func performBlock<T>(
|
||||
file: FileString,
|
||||
line: UInt,
|
||||
_ closure: @escaping (@escaping (T) -> Void) throws -> Void
|
||||
) -> AwaitPromiseBuilder<T> {
|
||||
let promise = AwaitPromise<T>()
|
||||
let timeoutSource = createTimerSource(timeoutQueue)
|
||||
var completionCount = 0
|
||||
let trigger = AwaitTrigger(timeoutSource: timeoutSource, actionSource: nil) {
|
||||
try closure { result in
|
||||
completionCount += 1
|
||||
if completionCount < 2 {
|
||||
func completeBlock() {
|
||||
if promise.resolveResult(.completed(result)) {
|
||||
CFRunLoopStop(CFRunLoopGetMain())
|
||||
}
|
||||
}
|
||||
|
||||
if Thread.isMainThread {
|
||||
completeBlock()
|
||||
} else {
|
||||
DispatchQueue.main.async { completeBlock() }
|
||||
}
|
||||
} else {
|
||||
fail("waitUntil(..) expects its completion closure to be only called once",
|
||||
file: file, line: line)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return AwaitPromiseBuilder(
|
||||
awaiter: self,
|
||||
waitLock: waitLock,
|
||||
promise: promise,
|
||||
trigger: trigger)
|
||||
}
|
||||
|
||||
func poll<T>(_ pollInterval: DispatchTimeInterval, closure: @escaping () throws -> T?) -> AwaitPromiseBuilder<T> {
|
||||
let promise = AwaitPromise<T>()
|
||||
let timeoutSource = createTimerSource(timeoutQueue)
|
||||
let asyncSource = createTimerSource(asyncQueue)
|
||||
let trigger = AwaitTrigger(timeoutSource: timeoutSource, actionSource: asyncSource) {
|
||||
let interval = pollInterval
|
||||
asyncSource.schedule(deadline: .now(), repeating: interval, leeway: pollLeeway)
|
||||
asyncSource.setEventHandler {
|
||||
do {
|
||||
if let result = try closure() {
|
||||
if promise.resolveResult(.completed(result)) {
|
||||
CFRunLoopStop(CFRunLoopGetCurrent())
|
||||
}
|
||||
}
|
||||
} catch let error {
|
||||
if promise.resolveResult(.errorThrown(error)) {
|
||||
CFRunLoopStop(CFRunLoopGetCurrent())
|
||||
}
|
||||
}
|
||||
}
|
||||
asyncSource.resume()
|
||||
}
|
||||
|
||||
return AwaitPromiseBuilder(
|
||||
awaiter: self,
|
||||
waitLock: waitLock,
|
||||
promise: promise,
|
||||
trigger: trigger)
|
||||
}
|
||||
}
|
||||
|
||||
internal func pollBlock(
|
||||
pollInterval: DispatchTimeInterval,
|
||||
timeoutInterval: DispatchTimeInterval,
|
||||
file: FileString,
|
||||
line: UInt,
|
||||
fnName: String = #function,
|
||||
expression: @escaping () throws -> Bool) -> AwaitResult<Bool> {
|
||||
let awaiter = NimbleEnvironment.activeInstance.awaiter
|
||||
let result = awaiter.poll(pollInterval) { () throws -> Bool? in
|
||||
if try expression() {
|
||||
return true
|
||||
}
|
||||
return nil
|
||||
}.timeout(timeoutInterval, forcefullyAbortTimeout: timeoutInterval.divided).wait(fnName, file: file, line: line)
|
||||
|
||||
return result
|
||||
}
|
||||
@@ -1,41 +0,0 @@
|
||||
import Dispatch
|
||||
|
||||
#if canImport(CDispatch)
|
||||
import CDispatch
|
||||
#endif
|
||||
|
||||
extension DispatchTimeInterval {
|
||||
// ** Note: We cannot simply divide the time interval because DispatchTimeInterval associated value type is Int
|
||||
var divided: DispatchTimeInterval {
|
||||
switch self {
|
||||
case let .seconds(val): return val < 2 ? .milliseconds(Int(Float(val)/2*1000)) : .seconds(val/2)
|
||||
case let .milliseconds(val): return .milliseconds(val/2)
|
||||
case let .microseconds(val): return .microseconds(val/2)
|
||||
case let .nanoseconds(val): return .nanoseconds(val/2)
|
||||
case .never: return .never
|
||||
@unknown default: fatalError("Unknown DispatchTimeInterval value")
|
||||
}
|
||||
}
|
||||
|
||||
var description: String {
|
||||
switch self {
|
||||
case let .seconds(val): return val == 1 ? "\(Float(val)) second" : "\(Float(val)) seconds"
|
||||
case let .milliseconds(val): return "\(Float(val)/1_000) seconds"
|
||||
case let .microseconds(val): return "\(Float(val)/1_000_000) seconds"
|
||||
case let .nanoseconds(val): return "\(Float(val)/1_000_000_000) seconds"
|
||||
default: fatalError("Unknown DispatchTimeInterval value")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#if canImport(Foundation)
|
||||
import typealias Foundation.TimeInterval
|
||||
|
||||
extension TimeInterval {
|
||||
var dispatchInterval: DispatchTimeInterval {
|
||||
let microseconds = Int64(self * TimeInterval(USEC_PER_SEC))
|
||||
// perhaps use nanoseconds, though would more often be > Int.max
|
||||
return microseconds < Int.max ? .microseconds(Int(microseconds)) : .seconds(Int(self))
|
||||
}
|
||||
}
|
||||
#endif
|
||||
-63
@@ -1,63 +0,0 @@
|
||||
// Generic
|
||||
|
||||
internal func messageForError<T: Error>(
|
||||
postfixMessageVerb: String = "throw",
|
||||
actualError: Error?,
|
||||
error: T? = nil,
|
||||
errorType: T.Type? = nil,
|
||||
closure: ((T) -> Void)? = nil
|
||||
) -> ExpectationMessage {
|
||||
var rawMessage = "\(postfixMessageVerb) error"
|
||||
|
||||
if let error = error {
|
||||
rawMessage += " <\(error)>"
|
||||
} else if errorType != nil || closure != nil {
|
||||
rawMessage += " from type <\(T.self)>"
|
||||
}
|
||||
if closure != nil {
|
||||
rawMessage += " that satisfies block"
|
||||
}
|
||||
if error == nil && errorType == nil && closure == nil {
|
||||
rawMessage = "\(postfixMessageVerb) any error"
|
||||
}
|
||||
|
||||
let actual: String
|
||||
if let actualError = actualError {
|
||||
actual = "<\(actualError)>"
|
||||
} else {
|
||||
actual = "no error"
|
||||
}
|
||||
|
||||
return .expectedCustomValueTo(rawMessage, actual: actual)
|
||||
}
|
||||
|
||||
internal func errorMatchesExpectedError<T: Error>(
|
||||
_ actualError: Error,
|
||||
expectedError: T) -> Bool {
|
||||
return actualError._domain == expectedError._domain
|
||||
&& actualError._code == expectedError._code
|
||||
}
|
||||
|
||||
// Non-generic
|
||||
|
||||
internal func messageForError(
|
||||
actualError: Error?,
|
||||
closure: ((Error) -> Void)?
|
||||
) -> ExpectationMessage {
|
||||
var rawMessage = "throw error"
|
||||
|
||||
if closure != nil {
|
||||
rawMessage += " that satisfies block"
|
||||
} else {
|
||||
rawMessage = "throw any error"
|
||||
}
|
||||
|
||||
let actual: String
|
||||
if let actualError = actualError {
|
||||
actual = "<\(actualError)>"
|
||||
} else {
|
||||
actual = "no error"
|
||||
}
|
||||
|
||||
return .expectedCustomValueTo(rawMessage, actual: actual)
|
||||
}
|
||||
@@ -1,31 +0,0 @@
|
||||
import Foundation
|
||||
|
||||
// Ideally we would always use `StaticString` as the type for tracking the file name
|
||||
// that expectations originate from, for consistency with `assert` etc. from the
|
||||
// stdlib, and because recent versions of the XCTest overlay require `StaticString`
|
||||
// when calling `XCTFail`. Under the Objective-C runtime (i.e. building on Mac), we
|
||||
// have to use `String` instead because StaticString can't be generated from Objective-C
|
||||
#if SWIFT_PACKAGE
|
||||
public typealias FileString = StaticString
|
||||
#else
|
||||
public typealias FileString = String
|
||||
#endif
|
||||
|
||||
public final class SourceLocation: NSObject {
|
||||
public let file: FileString
|
||||
public let line: UInt
|
||||
|
||||
override init() {
|
||||
file = "Unknown File"
|
||||
line = 0
|
||||
}
|
||||
|
||||
init(file: FileString, line: UInt) {
|
||||
self.file = file
|
||||
self.line = line
|
||||
}
|
||||
|
||||
override public var description: String {
|
||||
return "\(file):\(line)"
|
||||
}
|
||||
}
|
||||
-188
@@ -1,188 +0,0 @@
|
||||
import Foundation
|
||||
|
||||
internal func identityAsString(_ value: Any?) -> String {
|
||||
let anyObject = value as AnyObject?
|
||||
if let value = anyObject {
|
||||
return NSString(format: "<%p>", unsafeBitCast(value, to: Int.self)).description
|
||||
} else {
|
||||
return "nil"
|
||||
}
|
||||
}
|
||||
|
||||
internal func arrayAsString<T>(_ items: [T], joiner: String = ", ") -> String {
|
||||
return items.reduce("") { accum, item in
|
||||
let prefix = (accum.isEmpty ? "" : joiner)
|
||||
return accum + prefix + "\(stringify(item))"
|
||||
}
|
||||
}
|
||||
|
||||
/// A type with a customized test output text representation.
|
||||
///
|
||||
/// This textual representation is produced when values will be
|
||||
/// printed in test runs, and may be useful when producing
|
||||
/// error messages in custom matchers.
|
||||
///
|
||||
/// - SeeAlso: `CustomDebugStringConvertible`
|
||||
public protocol TestOutputStringConvertible {
|
||||
var testDescription: String { get }
|
||||
}
|
||||
|
||||
extension Double: TestOutputStringConvertible {
|
||||
public var testDescription: String {
|
||||
return NSNumber(value: self).testDescription
|
||||
}
|
||||
}
|
||||
|
||||
extension Float: TestOutputStringConvertible {
|
||||
public var testDescription: String {
|
||||
return NSNumber(value: self).testDescription
|
||||
}
|
||||
}
|
||||
|
||||
extension NSNumber: TestOutputStringConvertible {
|
||||
public var testDescription: String {
|
||||
let description = self.description
|
||||
|
||||
if description.contains(".") {
|
||||
let decimalPlaces = description.split(separator: ".")[1]
|
||||
switch decimalPlaces.count {
|
||||
case 1:
|
||||
return String(format: "%0.1f", doubleValue)
|
||||
case 2:
|
||||
return String(format: "%0.2f", doubleValue)
|
||||
case 3:
|
||||
return String(format: "%0.3f", doubleValue)
|
||||
default:
|
||||
return String(format: "%0.4f", doubleValue)
|
||||
}
|
||||
}
|
||||
|
||||
return description
|
||||
}
|
||||
}
|
||||
|
||||
extension Array: TestOutputStringConvertible {
|
||||
public var testDescription: String {
|
||||
let list = self.map(Nimble.stringify).joined(separator: ", ")
|
||||
return "[\(list)]"
|
||||
}
|
||||
}
|
||||
|
||||
extension AnySequence: TestOutputStringConvertible {
|
||||
public var testDescription: String {
|
||||
let generator = self.makeIterator()
|
||||
var strings = [String]()
|
||||
var value: AnySequence.Element?
|
||||
|
||||
repeat {
|
||||
value = generator.next()
|
||||
if let value = value {
|
||||
strings.append(stringify(value))
|
||||
}
|
||||
} while value != nil
|
||||
|
||||
let list = strings.joined(separator: ", ")
|
||||
return "[\(list)]"
|
||||
}
|
||||
}
|
||||
|
||||
extension NSArray: TestOutputStringConvertible {
|
||||
public var testDescription: String {
|
||||
let list = Array(self).map(Nimble.stringify).joined(separator: ", ")
|
||||
return "(\(list))"
|
||||
}
|
||||
}
|
||||
|
||||
extension NSIndexSet: TestOutputStringConvertible {
|
||||
public var testDescription: String {
|
||||
let list = Array(self).map(Nimble.stringify).joined(separator: ", ")
|
||||
return "(\(list))"
|
||||
}
|
||||
}
|
||||
|
||||
extension String: TestOutputStringConvertible {
|
||||
public var testDescription: String {
|
||||
return self
|
||||
}
|
||||
}
|
||||
|
||||
extension Data: TestOutputStringConvertible {
|
||||
public var testDescription: String {
|
||||
return "Data<hash=\((self as NSData).hash),length=\(count)>"
|
||||
}
|
||||
}
|
||||
|
||||
///
|
||||
/// Returns a string appropriate for displaying in test output
|
||||
/// from the provided value.
|
||||
///
|
||||
/// - parameter value: A value that will show up in a test's output.
|
||||
///
|
||||
/// - returns: The string that is returned can be
|
||||
/// customized per type by conforming a type to the `TestOutputStringConvertible`
|
||||
/// protocol. When stringifying a non-`TestOutputStringConvertible` type, this
|
||||
/// function will return the value's debug description and then its
|
||||
/// normal description if available and in that order. Otherwise it
|
||||
/// will return the result of constructing a string from the value.
|
||||
///
|
||||
/// - SeeAlso: `TestOutputStringConvertible`
|
||||
public func stringify<T>(_ value: T?) -> String {
|
||||
guard let value = value else { return "nil" }
|
||||
|
||||
if let value = value as? TestOutputStringConvertible {
|
||||
return value.testDescription
|
||||
}
|
||||
|
||||
if let value = value as? CustomDebugStringConvertible {
|
||||
return value.debugDescription
|
||||
}
|
||||
|
||||
return String(describing: value)
|
||||
}
|
||||
|
||||
#if canImport(Darwin)
|
||||
@objc public class NMBStringer: NSObject {
|
||||
@objc public class func stringify(_ obj: Any?) -> String {
|
||||
return Nimble.stringify(obj)
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
// MARK: Collection Type Stringers
|
||||
|
||||
/// Attempts to generate a pretty type string for a given value. If the value is of a Objective-C
|
||||
/// collection type, or a subclass thereof, (e.g. `NSArray`, `NSDictionary`, etc.).
|
||||
/// This function will return the type name of the root class of the class cluster for better
|
||||
/// readability (e.g. `NSArray` instead of `__NSArrayI`).
|
||||
///
|
||||
/// For values that don't have a type of an Objective-C collection, this function returns the
|
||||
/// default type description.
|
||||
///
|
||||
/// - parameter value: A value that will be used to determine a type name.
|
||||
///
|
||||
/// - returns: The name of the class cluster root class for Objective-C collection types, or the
|
||||
/// the `dynamicType` of the value for values of any other type.
|
||||
public func prettyCollectionType<T>(_ value: T) -> String {
|
||||
switch value {
|
||||
case is NSArray:
|
||||
return String(describing: NSArray.self)
|
||||
case is NSDictionary:
|
||||
return String(describing: NSDictionary.self)
|
||||
case is NSSet:
|
||||
return String(describing: NSSet.self)
|
||||
case is NSIndexSet:
|
||||
return String(describing: NSIndexSet.self)
|
||||
default:
|
||||
return String(describing: value)
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns the type name for a given collection type. This overload is used by Swift
|
||||
/// collection types.
|
||||
///
|
||||
/// - parameter collection: A Swift `CollectionType` value.
|
||||
///
|
||||
/// - returns: A string representing the `dynamicType` of the value.
|
||||
public func prettyCollectionType<T: Collection>(_ collection: T) -> String {
|
||||
return String(describing: type(of: collection))
|
||||
}
|
||||
-389
@@ -1,389 +0,0 @@
|
||||
#import <Foundation/Foundation.h>
|
||||
|
||||
@class NMBExpectation;
|
||||
@class NMBPredicate;
|
||||
@class NMBObjCBeCloseToPredicate;
|
||||
@class NMBObjCRaiseExceptionPredicate;
|
||||
|
||||
|
||||
NS_ASSUME_NONNULL_BEGIN
|
||||
|
||||
|
||||
#define NIMBLE_OVERLOADABLE __attribute__((overloadable))
|
||||
#define NIMBLE_EXPORT FOUNDATION_EXPORT
|
||||
#define NIMBLE_EXPORT_INLINE FOUNDATION_STATIC_INLINE
|
||||
|
||||
#define NIMBLE_VALUE_OF(VAL) ({ \
|
||||
__typeof__((VAL)) val = (VAL); \
|
||||
[NSValue valueWithBytes:&val objCType:@encode(__typeof__((VAL)))]; \
|
||||
})
|
||||
|
||||
#ifdef NIMBLE_DISABLE_SHORT_SYNTAX
|
||||
#define NIMBLE_SHORT(PROTO, ORIGINAL)
|
||||
#define NIMBLE_SHORT_OVERLOADED(PROTO, ORIGINAL)
|
||||
#else
|
||||
#define NIMBLE_SHORT(PROTO, ORIGINAL) FOUNDATION_STATIC_INLINE PROTO { return (ORIGINAL); }
|
||||
#define NIMBLE_SHORT_OVERLOADED(PROTO, ORIGINAL) FOUNDATION_STATIC_INLINE NIMBLE_OVERLOADABLE PROTO { return (ORIGINAL); }
|
||||
#endif
|
||||
|
||||
|
||||
|
||||
#define DEFINE_NMB_EXPECT_OVERLOAD(TYPE, EXPR) \
|
||||
NIMBLE_EXPORT_INLINE NIMBLE_OVERLOADABLE \
|
||||
NMBExpectation *NMB_expect(TYPE(^actualBlock)(void), NSString *file, NSUInteger line) { \
|
||||
return NMB_expect(^id { return EXPR; }, file, line); \
|
||||
}
|
||||
|
||||
NIMBLE_EXPORT NIMBLE_OVERLOADABLE
|
||||
NMBExpectation *NMB_expect(id(^actualBlock)(void), NSString *file, NSUInteger line);
|
||||
|
||||
// overloaded dispatch for nils - expect(nil)
|
||||
DEFINE_NMB_EXPECT_OVERLOAD(void*, nil)
|
||||
DEFINE_NMB_EXPECT_OVERLOAD(NSRange, NIMBLE_VALUE_OF(actualBlock()))
|
||||
DEFINE_NMB_EXPECT_OVERLOAD(long, @(actualBlock()))
|
||||
DEFINE_NMB_EXPECT_OVERLOAD(unsigned long, @(actualBlock()))
|
||||
DEFINE_NMB_EXPECT_OVERLOAD(int, @(actualBlock()))
|
||||
DEFINE_NMB_EXPECT_OVERLOAD(unsigned int, @(actualBlock()))
|
||||
DEFINE_NMB_EXPECT_OVERLOAD(float, @(actualBlock()))
|
||||
DEFINE_NMB_EXPECT_OVERLOAD(double, @(actualBlock()))
|
||||
DEFINE_NMB_EXPECT_OVERLOAD(long long, @(actualBlock()))
|
||||
DEFINE_NMB_EXPECT_OVERLOAD(unsigned long long, @(actualBlock()))
|
||||
DEFINE_NMB_EXPECT_OVERLOAD(char, @(actualBlock()))
|
||||
DEFINE_NMB_EXPECT_OVERLOAD(unsigned char, @(actualBlock()))
|
||||
// bool doesn't get the compiler to dispatch to BOOL types, but using BOOL here seems to allow
|
||||
// the compiler to dispatch to bool.
|
||||
DEFINE_NMB_EXPECT_OVERLOAD(BOOL, @(actualBlock()))
|
||||
DEFINE_NMB_EXPECT_OVERLOAD(char *, @(actualBlock()))
|
||||
|
||||
|
||||
#undef DEFINE_NMB_EXPECT_OVERLOAD
|
||||
|
||||
|
||||
|
||||
NIMBLE_EXPORT NMBExpectation *NMB_expectAction(void(^actualBlock)(void), NSString *file, NSUInteger line);
|
||||
|
||||
|
||||
|
||||
#define DEFINE_OVERLOAD(TYPE, EXPR) \
|
||||
NIMBLE_EXPORT_INLINE NIMBLE_OVERLOADABLE \
|
||||
NMBPredicate *NMB_equal(TYPE expectedValue) { \
|
||||
return NMB_equal((EXPR)); \
|
||||
} \
|
||||
NIMBLE_SHORT_OVERLOADED(NMBPredicate *equal(TYPE expectedValue), NMB_equal(expectedValue));
|
||||
|
||||
|
||||
NIMBLE_EXPORT NIMBLE_OVERLOADABLE
|
||||
NMBPredicate *NMB_equal(__nullable id expectedValue);
|
||||
|
||||
NIMBLE_SHORT_OVERLOADED(NMBPredicate *equal(__nullable id expectedValue),
|
||||
NMB_equal(expectedValue));
|
||||
|
||||
// overloaded dispatch for nils - expect(nil)
|
||||
DEFINE_OVERLOAD(void*__nullable, (id)nil)
|
||||
DEFINE_OVERLOAD(NSRange, NIMBLE_VALUE_OF(expectedValue))
|
||||
DEFINE_OVERLOAD(long, @(expectedValue))
|
||||
DEFINE_OVERLOAD(unsigned long, @(expectedValue))
|
||||
DEFINE_OVERLOAD(int, @(expectedValue))
|
||||
DEFINE_OVERLOAD(unsigned int, @(expectedValue))
|
||||
DEFINE_OVERLOAD(float, @(expectedValue))
|
||||
DEFINE_OVERLOAD(double, @(expectedValue))
|
||||
DEFINE_OVERLOAD(long long, @(expectedValue))
|
||||
DEFINE_OVERLOAD(unsigned long long, @(expectedValue))
|
||||
DEFINE_OVERLOAD(char, @(expectedValue))
|
||||
DEFINE_OVERLOAD(unsigned char, @(expectedValue))
|
||||
// bool doesn't get the compiler to dispatch to BOOL types, but using BOOL here seems to allow
|
||||
// the compiler to dispatch to bool.
|
||||
DEFINE_OVERLOAD(BOOL, @(expectedValue))
|
||||
DEFINE_OVERLOAD(char *, @(expectedValue))
|
||||
|
||||
#undef DEFINE_OVERLOAD
|
||||
|
||||
|
||||
#define DEFINE_OVERLOAD(TYPE, EXPR) \
|
||||
NIMBLE_EXPORT_INLINE NIMBLE_OVERLOADABLE \
|
||||
NMBPredicate *NMB_haveCount(TYPE expectedValue) { \
|
||||
return NMB_haveCount((EXPR)); \
|
||||
} \
|
||||
NIMBLE_SHORT_OVERLOADED(NMBPredicate *haveCount(TYPE expectedValue), \
|
||||
NMB_haveCount(expectedValue));
|
||||
|
||||
|
||||
NIMBLE_EXPORT NIMBLE_OVERLOADABLE
|
||||
NMBPredicate *NMB_haveCount(id expectedValue);
|
||||
|
||||
NIMBLE_SHORT_OVERLOADED(NMBPredicate *haveCount(id expectedValue),
|
||||
NMB_haveCount(expectedValue));
|
||||
|
||||
DEFINE_OVERLOAD(long, @(expectedValue))
|
||||
DEFINE_OVERLOAD(unsigned long, @(expectedValue))
|
||||
DEFINE_OVERLOAD(int, @(expectedValue))
|
||||
DEFINE_OVERLOAD(unsigned int, @(expectedValue))
|
||||
DEFINE_OVERLOAD(long long, @(expectedValue))
|
||||
DEFINE_OVERLOAD(unsigned long long, @(expectedValue))
|
||||
DEFINE_OVERLOAD(char, @(expectedValue))
|
||||
DEFINE_OVERLOAD(unsigned char, @(expectedValue))
|
||||
|
||||
#undef DEFINE_OVERLOAD
|
||||
|
||||
#define DEFINE_OVERLOAD(TYPE, EXPR) \
|
||||
NIMBLE_EXPORT_INLINE NIMBLE_OVERLOADABLE \
|
||||
NMBObjCBeCloseToPredicate *NMB_beCloseTo(TYPE expectedValue) { \
|
||||
return NMB_beCloseTo((NSNumber *)(EXPR)); \
|
||||
} \
|
||||
NIMBLE_SHORT_OVERLOADED(NMBObjCBeCloseToPredicate *beCloseTo(TYPE expectedValue), \
|
||||
NMB_beCloseTo(expectedValue));
|
||||
|
||||
NIMBLE_EXPORT NIMBLE_OVERLOADABLE NMBObjCBeCloseToPredicate *NMB_beCloseTo(NSNumber *expectedValue);
|
||||
NIMBLE_SHORT_OVERLOADED(NMBObjCBeCloseToPredicate *beCloseTo(NSNumber *expectedValue),
|
||||
NMB_beCloseTo(expectedValue));
|
||||
|
||||
// it would be better to only overload float & double, but zero becomes ambigious
|
||||
|
||||
DEFINE_OVERLOAD(long, @(expectedValue))
|
||||
DEFINE_OVERLOAD(unsigned long, @(expectedValue))
|
||||
DEFINE_OVERLOAD(int, @(expectedValue))
|
||||
DEFINE_OVERLOAD(unsigned int, @(expectedValue))
|
||||
DEFINE_OVERLOAD(float, @(expectedValue))
|
||||
DEFINE_OVERLOAD(double, @(expectedValue))
|
||||
DEFINE_OVERLOAD(long long, @(expectedValue))
|
||||
DEFINE_OVERLOAD(unsigned long long, @(expectedValue))
|
||||
DEFINE_OVERLOAD(char, @(expectedValue))
|
||||
DEFINE_OVERLOAD(unsigned char, @(expectedValue))
|
||||
|
||||
#undef DEFINE_OVERLOAD
|
||||
|
||||
NIMBLE_EXPORT NMBPredicate *NMB_beAnInstanceOf(Class expectedClass);
|
||||
NIMBLE_EXPORT_INLINE NMBPredicate *beAnInstanceOf(Class expectedClass) {
|
||||
return NMB_beAnInstanceOf(expectedClass);
|
||||
}
|
||||
|
||||
NIMBLE_EXPORT NMBPredicate *NMB_beAKindOf(Class expectedClass);
|
||||
NIMBLE_EXPORT_INLINE NMBPredicate *beAKindOf(Class expectedClass) {
|
||||
return NMB_beAKindOf(expectedClass);
|
||||
}
|
||||
|
||||
NIMBLE_EXPORT NMBPredicate *NMB_beginWith(id itemElementOrSubstring);
|
||||
NIMBLE_EXPORT_INLINE NMBPredicate *beginWith(id itemElementOrSubstring) {
|
||||
return NMB_beginWith(itemElementOrSubstring);
|
||||
}
|
||||
|
||||
#define DEFINE_OVERLOAD(TYPE, EXPR) \
|
||||
NIMBLE_EXPORT_INLINE NIMBLE_OVERLOADABLE \
|
||||
NMBPredicate *NMB_beGreaterThan(TYPE expectedValue) { \
|
||||
return NMB_beGreaterThan((EXPR)); \
|
||||
} \
|
||||
NIMBLE_SHORT_OVERLOADED(NMBPredicate *beGreaterThan(TYPE expectedValue), NMB_beGreaterThan(expectedValue));
|
||||
|
||||
NIMBLE_EXPORT NIMBLE_OVERLOADABLE
|
||||
NMBPredicate *NMB_beGreaterThan(NSNumber *expectedValue);
|
||||
|
||||
NIMBLE_EXPORT_INLINE NIMBLE_OVERLOADABLE
|
||||
NMBPredicate *beGreaterThan(NSNumber *expectedValue) {
|
||||
return NMB_beGreaterThan(expectedValue);
|
||||
}
|
||||
|
||||
DEFINE_OVERLOAD(long, @(expectedValue))
|
||||
DEFINE_OVERLOAD(unsigned long, @(expectedValue))
|
||||
DEFINE_OVERLOAD(int, @(expectedValue))
|
||||
DEFINE_OVERLOAD(unsigned int, @(expectedValue))
|
||||
DEFINE_OVERLOAD(float, @(expectedValue))
|
||||
DEFINE_OVERLOAD(double, @(expectedValue))
|
||||
DEFINE_OVERLOAD(long long, @(expectedValue))
|
||||
DEFINE_OVERLOAD(unsigned long long, @(expectedValue))
|
||||
DEFINE_OVERLOAD(char, @(expectedValue))
|
||||
DEFINE_OVERLOAD(unsigned char, @(expectedValue))
|
||||
|
||||
#undef DEFINE_OVERLOAD
|
||||
|
||||
#define DEFINE_OVERLOAD(TYPE, EXPR) \
|
||||
NIMBLE_EXPORT_INLINE NIMBLE_OVERLOADABLE \
|
||||
NMBPredicate *NMB_beGreaterThanOrEqualTo(TYPE expectedValue) { \
|
||||
return NMB_beGreaterThanOrEqualTo((EXPR)); \
|
||||
} \
|
||||
NIMBLE_SHORT_OVERLOADED(NMBPredicate *beGreaterThanOrEqualTo(TYPE expectedValue), \
|
||||
NMB_beGreaterThanOrEqualTo(expectedValue));
|
||||
|
||||
NIMBLE_EXPORT NIMBLE_OVERLOADABLE
|
||||
NMBPredicate *NMB_beGreaterThanOrEqualTo(NSNumber *expectedValue);
|
||||
|
||||
NIMBLE_EXPORT_INLINE NIMBLE_OVERLOADABLE
|
||||
NMBPredicate *beGreaterThanOrEqualTo(NSNumber *expectedValue) {
|
||||
return NMB_beGreaterThanOrEqualTo(expectedValue);
|
||||
}
|
||||
|
||||
DEFINE_OVERLOAD(long, @(expectedValue))
|
||||
DEFINE_OVERLOAD(unsigned long, @(expectedValue))
|
||||
DEFINE_OVERLOAD(int, @(expectedValue))
|
||||
DEFINE_OVERLOAD(unsigned int, @(expectedValue))
|
||||
DEFINE_OVERLOAD(float, @(expectedValue))
|
||||
DEFINE_OVERLOAD(double, @(expectedValue))
|
||||
DEFINE_OVERLOAD(long long, @(expectedValue))
|
||||
DEFINE_OVERLOAD(unsigned long long, @(expectedValue))
|
||||
DEFINE_OVERLOAD(char, @(expectedValue))
|
||||
DEFINE_OVERLOAD(unsigned char, @(expectedValue))
|
||||
|
||||
|
||||
#undef DEFINE_OVERLOAD
|
||||
|
||||
NIMBLE_EXPORT NMBPredicate *NMB_beIdenticalTo(id expectedInstance);
|
||||
NIMBLE_SHORT(NMBPredicate *beIdenticalTo(id expectedInstance),
|
||||
NMB_beIdenticalTo(expectedInstance));
|
||||
|
||||
NIMBLE_EXPORT NMBPredicate *NMB_be(id expectedInstance);
|
||||
NIMBLE_SHORT(NMBPredicate *be(id expectedInstance),
|
||||
NMB_be(expectedInstance));
|
||||
|
||||
|
||||
#define DEFINE_OVERLOAD(TYPE, EXPR) \
|
||||
NIMBLE_EXPORT_INLINE NIMBLE_OVERLOADABLE \
|
||||
NMBPredicate *NMB_beLessThan(TYPE expectedValue) { \
|
||||
return NMB_beLessThan((EXPR)); \
|
||||
} \
|
||||
NIMBLE_SHORT_OVERLOADED(NMBPredicate *beLessThan(TYPE expectedValue), \
|
||||
NMB_beLessThan(expectedValue));
|
||||
|
||||
NIMBLE_EXPORT NIMBLE_OVERLOADABLE
|
||||
NMBPredicate *NMB_beLessThan(NSNumber *expectedValue);
|
||||
|
||||
NIMBLE_EXPORT_INLINE NIMBLE_OVERLOADABLE
|
||||
NMBPredicate *beLessThan(NSNumber *expectedValue) {
|
||||
return NMB_beLessThan(expectedValue);
|
||||
}
|
||||
|
||||
DEFINE_OVERLOAD(long, @(expectedValue))
|
||||
DEFINE_OVERLOAD(unsigned long, @(expectedValue))
|
||||
DEFINE_OVERLOAD(int, @(expectedValue))
|
||||
DEFINE_OVERLOAD(unsigned int, @(expectedValue))
|
||||
DEFINE_OVERLOAD(float, @(expectedValue))
|
||||
DEFINE_OVERLOAD(double, @(expectedValue))
|
||||
DEFINE_OVERLOAD(long long, @(expectedValue))
|
||||
DEFINE_OVERLOAD(unsigned long long, @(expectedValue))
|
||||
DEFINE_OVERLOAD(char, @(expectedValue))
|
||||
DEFINE_OVERLOAD(unsigned char, @(expectedValue))
|
||||
|
||||
#undef DEFINE_OVERLOAD
|
||||
|
||||
|
||||
#define DEFINE_OVERLOAD(TYPE, EXPR) \
|
||||
NIMBLE_EXPORT_INLINE NIMBLE_OVERLOADABLE \
|
||||
NMBPredicate *NMB_beLessThanOrEqualTo(TYPE expectedValue) { \
|
||||
return NMB_beLessThanOrEqualTo((EXPR)); \
|
||||
} \
|
||||
NIMBLE_SHORT_OVERLOADED(NMBPredicate *beLessThanOrEqualTo(TYPE expectedValue), \
|
||||
NMB_beLessThanOrEqualTo(expectedValue));
|
||||
|
||||
|
||||
NIMBLE_EXPORT NIMBLE_OVERLOADABLE
|
||||
NMBPredicate *NMB_beLessThanOrEqualTo(NSNumber *expectedValue);
|
||||
|
||||
NIMBLE_EXPORT_INLINE NIMBLE_OVERLOADABLE
|
||||
NMBPredicate *beLessThanOrEqualTo(NSNumber *expectedValue) {
|
||||
return NMB_beLessThanOrEqualTo(expectedValue);
|
||||
}
|
||||
|
||||
DEFINE_OVERLOAD(long, @(expectedValue))
|
||||
DEFINE_OVERLOAD(unsigned long, @(expectedValue))
|
||||
DEFINE_OVERLOAD(int, @(expectedValue))
|
||||
DEFINE_OVERLOAD(unsigned int, @(expectedValue))
|
||||
DEFINE_OVERLOAD(float, @(expectedValue))
|
||||
DEFINE_OVERLOAD(double, @(expectedValue))
|
||||
DEFINE_OVERLOAD(long long, @(expectedValue))
|
||||
DEFINE_OVERLOAD(unsigned long long, @(expectedValue))
|
||||
DEFINE_OVERLOAD(char, @(expectedValue))
|
||||
DEFINE_OVERLOAD(unsigned char, @(expectedValue))
|
||||
|
||||
#undef DEFINE_OVERLOAD
|
||||
|
||||
NIMBLE_EXPORT NMBPredicate *NMB_beTruthy(void);
|
||||
NIMBLE_SHORT(NMBPredicate *beTruthy(void),
|
||||
NMB_beTruthy());
|
||||
|
||||
NIMBLE_EXPORT NMBPredicate *NMB_beFalsy(void);
|
||||
NIMBLE_SHORT(NMBPredicate *beFalsy(void),
|
||||
NMB_beFalsy());
|
||||
|
||||
NIMBLE_EXPORT NMBPredicate *NMB_beTrue(void);
|
||||
NIMBLE_SHORT(NMBPredicate *beTrue(void),
|
||||
NMB_beTrue());
|
||||
|
||||
NIMBLE_EXPORT NMBPredicate *NMB_beFalse(void);
|
||||
NIMBLE_SHORT(NMBPredicate *beFalse(void),
|
||||
NMB_beFalse());
|
||||
|
||||
NIMBLE_EXPORT NMBPredicate *NMB_beNil(void);
|
||||
NIMBLE_SHORT(NMBPredicate *beNil(void),
|
||||
NMB_beNil());
|
||||
|
||||
NIMBLE_EXPORT NMBPredicate *NMB_beEmpty(void);
|
||||
NIMBLE_SHORT(NMBPredicate *beEmpty(void),
|
||||
NMB_beEmpty());
|
||||
|
||||
NIMBLE_EXPORT NMBPredicate *NMB_containWithNilTermination(id itemOrSubstring, ...) NS_REQUIRES_NIL_TERMINATION;
|
||||
#define NMB_contain(...) NMB_containWithNilTermination(__VA_ARGS__, nil)
|
||||
#ifndef NIMBLE_DISABLE_SHORT_SYNTAX
|
||||
#define contain(...) NMB_contain(__VA_ARGS__)
|
||||
#endif
|
||||
|
||||
NIMBLE_EXPORT NMBPredicate *NMB_containElementSatisfying(BOOL(^predicate)(id));
|
||||
NIMBLE_SHORT(NMBPredicate *containElementSatisfying(BOOL(^predicate)(id)),
|
||||
NMB_containElementSatisfying(predicate));
|
||||
|
||||
NIMBLE_EXPORT NMBPredicate *NMB_endWith(id itemElementOrSubstring);
|
||||
NIMBLE_SHORT(NMBPredicate *endWith(id itemElementOrSubstring),
|
||||
NMB_endWith(itemElementOrSubstring));
|
||||
|
||||
NIMBLE_EXPORT NMBObjCRaiseExceptionPredicate *NMB_raiseException(void);
|
||||
NIMBLE_SHORT(NMBObjCRaiseExceptionPredicate *raiseException(void),
|
||||
NMB_raiseException());
|
||||
|
||||
NIMBLE_EXPORT NMBPredicate *NMB_match(id expectedValue);
|
||||
NIMBLE_SHORT(NMBPredicate *match(id expectedValue),
|
||||
NMB_match(expectedValue));
|
||||
|
||||
NIMBLE_EXPORT NMBPredicate *NMB_allPass(id matcher);
|
||||
NIMBLE_SHORT(NMBPredicate *allPass(id matcher),
|
||||
NMB_allPass(matcher));
|
||||
|
||||
NIMBLE_EXPORT NMBPredicate *NMB_satisfyAnyOfWithMatchers(id matchers);
|
||||
#define NMB_satisfyAnyOf(...) NMB_satisfyAnyOfWithMatchers(@[__VA_ARGS__])
|
||||
#ifndef NIMBLE_DISABLE_SHORT_SYNTAX
|
||||
#define satisfyAnyOf(...) NMB_satisfyAnyOf(__VA_ARGS__)
|
||||
#endif
|
||||
|
||||
NIMBLE_EXPORT NMBPredicate *NMB_satisfyAllOfWithMatchers(id matchers);
|
||||
#define NMB_satisfyAllOf(...) NMB_satisfyAllOfWithMatchers(@[__VA_ARGS__])
|
||||
#ifndef NIMBLE_DISABLE_SHORT_SYNTAX
|
||||
#define satisfyAllOf(...) NMB_satisfyAllOf(__VA_ARGS__)
|
||||
#endif
|
||||
|
||||
// In order to preserve breakpoint behavior despite using macros to fill in __FILE__ and __LINE__,
|
||||
// define a builder that populates __FILE__ and __LINE__, and returns a block that takes timeout
|
||||
// and action arguments. See https://github.com/Quick/Quick/pull/185 for details.
|
||||
typedef void (^NMBWaitUntilTimeoutBlock)(NSTimeInterval timeout, void (^action)(void (^)(void)));
|
||||
typedef void (^NMBWaitUntilBlock)(void (^action)(void (^)(void)));
|
||||
|
||||
NIMBLE_EXPORT void NMB_failWithMessage(NSString *msg, NSString *file, NSUInteger line);
|
||||
|
||||
NIMBLE_EXPORT NMBWaitUntilTimeoutBlock NMB_waitUntilTimeoutBuilder(NSString *file, NSUInteger line);
|
||||
NIMBLE_EXPORT NMBWaitUntilBlock NMB_waitUntilBuilder(NSString *file, NSUInteger line);
|
||||
|
||||
NIMBLE_EXPORT void NMB_failWithMessage(NSString *msg, NSString *file, NSUInteger line);
|
||||
|
||||
#define NMB_waitUntilTimeout NMB_waitUntilTimeoutBuilder(@(__FILE__), __LINE__)
|
||||
#define NMB_waitUntil NMB_waitUntilBuilder(@(__FILE__), __LINE__)
|
||||
|
||||
#ifndef NIMBLE_DISABLE_SHORT_SYNTAX
|
||||
#define expect(...) NMB_expect(^{ return (__VA_ARGS__); }, @(__FILE__), __LINE__)
|
||||
#define expectAction(BLOCK) NMB_expectAction((BLOCK), @(__FILE__), __LINE__)
|
||||
#define failWithMessage(msg) NMB_failWithMessage(msg, @(__FILE__), __LINE__)
|
||||
#define fail() failWithMessage(@"fail() always fails")
|
||||
|
||||
|
||||
#define waitUntilTimeout NMB_waitUntilTimeout
|
||||
#define waitUntil NMB_waitUntil
|
||||
|
||||
#undef NIMBLE_VALUE_OF
|
||||
|
||||
#endif
|
||||
|
||||
NS_ASSUME_NONNULL_END
|
||||
-161
@@ -1,161 +0,0 @@
|
||||
#import <Nimble/DSL.h>
|
||||
|
||||
#if __has_include("Nimble-Swift.h")
|
||||
#import "Nimble-Swift.h"
|
||||
#else
|
||||
#import <Nimble/Nimble-Swift.h>
|
||||
#endif
|
||||
|
||||
|
||||
NS_ASSUME_NONNULL_BEGIN
|
||||
|
||||
|
||||
NIMBLE_EXPORT NIMBLE_OVERLOADABLE NMBExpectation *__nonnull NMB_expect(id __nullable(^actualBlock)(void), NSString *__nonnull file, NSUInteger line) {
|
||||
return [[NMBExpectation alloc] initWithActualBlock:actualBlock
|
||||
negative:NO
|
||||
file:file
|
||||
line:line];
|
||||
}
|
||||
|
||||
NIMBLE_EXPORT NMBExpectation *NMB_expectAction(void(^actualBlock)(void), NSString *file, NSUInteger line) {
|
||||
return NMB_expect(^id{
|
||||
actualBlock();
|
||||
return nil;
|
||||
}, file, line);
|
||||
}
|
||||
|
||||
NIMBLE_EXPORT void NMB_failWithMessage(NSString *msg, NSString *file, NSUInteger line) {
|
||||
return [NMBExpectation failWithMessage:msg file:file line:line];
|
||||
}
|
||||
|
||||
NIMBLE_EXPORT NMBPredicate *NMB_beAnInstanceOf(Class expectedClass) {
|
||||
return [NMBPredicate beAnInstanceOfMatcher:expectedClass];
|
||||
}
|
||||
|
||||
NIMBLE_EXPORT NMBPredicate *NMB_beAKindOf(Class expectedClass) {
|
||||
return [NMBPredicate beAKindOfMatcher:expectedClass];
|
||||
}
|
||||
|
||||
NIMBLE_EXPORT NIMBLE_OVERLOADABLE NMBObjCBeCloseToPredicate *NMB_beCloseTo(NSNumber *expectedValue) {
|
||||
return [NMBPredicate beCloseToMatcher:expectedValue within:0.001];
|
||||
}
|
||||
|
||||
NIMBLE_EXPORT NMBPredicate *NMB_beginWith(id itemElementOrSubstring) {
|
||||
return [NMBPredicate beginWithMatcher:itemElementOrSubstring];
|
||||
}
|
||||
|
||||
NIMBLE_EXPORT NIMBLE_OVERLOADABLE NMBPredicate *NMB_beGreaterThan(NSNumber *expectedValue) {
|
||||
return [NMBPredicate beGreaterThanMatcher:expectedValue];
|
||||
}
|
||||
|
||||
NIMBLE_EXPORT NIMBLE_OVERLOADABLE NMBPredicate *NMB_beGreaterThanOrEqualTo(NSNumber *expectedValue) {
|
||||
return [NMBPredicate beGreaterThanOrEqualToMatcher:expectedValue];
|
||||
}
|
||||
|
||||
NIMBLE_EXPORT NMBPredicate *NMB_beIdenticalTo(id expectedInstance) {
|
||||
return [NMBPredicate beIdenticalToMatcher:expectedInstance];
|
||||
}
|
||||
|
||||
NIMBLE_EXPORT NMBPredicate *NMB_be(id expectedInstance) {
|
||||
return [NMBPredicate beIdenticalToMatcher:expectedInstance];
|
||||
}
|
||||
|
||||
NIMBLE_EXPORT NIMBLE_OVERLOADABLE NMBPredicate *NMB_beLessThan(NSNumber *expectedValue) {
|
||||
return [NMBPredicate beLessThanMatcher:expectedValue];
|
||||
}
|
||||
|
||||
NIMBLE_EXPORT NIMBLE_OVERLOADABLE NMBPredicate *NMB_beLessThanOrEqualTo(NSNumber *expectedValue) {
|
||||
return [NMBPredicate beLessThanOrEqualToMatcher:expectedValue];
|
||||
}
|
||||
|
||||
NIMBLE_EXPORT NMBPredicate *NMB_beTruthy() {
|
||||
return [NMBPredicate beTruthyMatcher];
|
||||
}
|
||||
|
||||
NIMBLE_EXPORT NMBPredicate *NMB_beFalsy() {
|
||||
return [NMBPredicate beFalsyMatcher];
|
||||
}
|
||||
|
||||
NIMBLE_EXPORT NMBPredicate *NMB_beTrue() {
|
||||
return [NMBPredicate beTrueMatcher];
|
||||
}
|
||||
|
||||
NIMBLE_EXPORT NMBPredicate *NMB_beFalse() {
|
||||
return [NMBPredicate beFalseMatcher];
|
||||
}
|
||||
|
||||
NIMBLE_EXPORT NMBPredicate *NMB_beNil() {
|
||||
return [NMBPredicate beNilMatcher];
|
||||
}
|
||||
|
||||
NIMBLE_EXPORT NMBPredicate *NMB_beEmpty() {
|
||||
return [NMBPredicate beEmptyMatcher];
|
||||
}
|
||||
|
||||
NIMBLE_EXPORT NMBPredicate *NMB_containWithNilTermination(id itemOrSubstring, ...) {
|
||||
NSMutableArray *itemOrSubstringArray = [NSMutableArray array];
|
||||
|
||||
if (itemOrSubstring) {
|
||||
[itemOrSubstringArray addObject:itemOrSubstring];
|
||||
|
||||
va_list args;
|
||||
va_start(args, itemOrSubstring);
|
||||
id next;
|
||||
while ((next = va_arg(args, id))) {
|
||||
[itemOrSubstringArray addObject:next];
|
||||
}
|
||||
va_end(args);
|
||||
}
|
||||
|
||||
return [NMBPredicate containMatcher:itemOrSubstringArray];
|
||||
}
|
||||
|
||||
NIMBLE_EXPORT NMBPredicate *NMB_containElementSatisfying(BOOL(^predicate)(id)) {
|
||||
return [NMBPredicate containElementSatisfyingMatcher:predicate];
|
||||
}
|
||||
|
||||
NIMBLE_EXPORT NMBPredicate *NMB_endWith(id itemElementOrSubstring) {
|
||||
return [NMBPredicate endWithMatcher:itemElementOrSubstring];
|
||||
}
|
||||
|
||||
NIMBLE_EXPORT NIMBLE_OVERLOADABLE NMBPredicate *NMB_equal(__nullable id expectedValue) {
|
||||
return [NMBPredicate equalMatcher:expectedValue];
|
||||
}
|
||||
|
||||
NIMBLE_EXPORT NIMBLE_OVERLOADABLE NMBPredicate *NMB_haveCount(id expectedValue) {
|
||||
return [NMBPredicate haveCountMatcher:expectedValue];
|
||||
}
|
||||
|
||||
NIMBLE_EXPORT NMBPredicate *NMB_match(id expectedValue) {
|
||||
return [NMBPredicate matchMatcher:expectedValue];
|
||||
}
|
||||
|
||||
NIMBLE_EXPORT NMBPredicate *NMB_allPass(id expectedValue) {
|
||||
return [NMBPredicate allPassMatcher:expectedValue];
|
||||
}
|
||||
|
||||
NIMBLE_EXPORT NMBPredicate *NMB_satisfyAnyOfWithMatchers(id matchers) {
|
||||
return [NMBPredicate satisfyAnyOfMatcher:matchers];
|
||||
}
|
||||
|
||||
NIMBLE_EXPORT NMBPredicate *NMB_satisfyAllOfWithMatchers(id matchers) {
|
||||
return [NMBPredicate satisfyAllOfMatcher:matchers];
|
||||
}
|
||||
|
||||
NIMBLE_EXPORT NMBObjCRaiseExceptionPredicate *NMB_raiseException() {
|
||||
return [NMBPredicate raiseExceptionMatcher];
|
||||
}
|
||||
|
||||
NIMBLE_EXPORT NMBWaitUntilTimeoutBlock NMB_waitUntilTimeoutBuilder(NSString *file, NSUInteger line) {
|
||||
return ^(NSTimeInterval timeout, void (^ _Nonnull action)(void (^ _Nonnull)(void))) {
|
||||
[NMBWait untilTimeout:timeout file:file line:line action:action];
|
||||
};
|
||||
}
|
||||
|
||||
NIMBLE_EXPORT NMBWaitUntilBlock NMB_waitUntilBuilder(NSString *file, NSUInteger line) {
|
||||
return ^(void (^ _Nonnull action)(void (^ _Nonnull)(void))) {
|
||||
[NMBWait untilFile:file line:line action:action];
|
||||
};
|
||||
}
|
||||
|
||||
NS_ASSUME_NONNULL_END
|
||||
@@ -1,11 +0,0 @@
|
||||
#import <Foundation/Foundation.h>
|
||||
#import <dispatch/dispatch.h>
|
||||
|
||||
@interface NMBExceptionCapture : NSObject
|
||||
|
||||
- (nonnull instancetype)initWithHandler:(void(^ _Nullable)(NSException * _Nonnull))handler finally:(void(^ _Nullable)(void))finally;
|
||||
- (void)tryBlock:(__attribute__((noescape)) void(^ _Nonnull)(void))unsafeBlock NS_SWIFT_NAME(tryBlock(_:));
|
||||
|
||||
@end
|
||||
|
||||
typedef void(^NMBSourceCallbackBlock)(BOOL successful);
|
||||
@@ -1,35 +0,0 @@
|
||||
#import "NMBExceptionCapture.h"
|
||||
|
||||
@interface NMBExceptionCapture ()
|
||||
@property (nonatomic, copy) void(^ _Nullable handler)(NSException * _Nullable);
|
||||
@property (nonatomic, copy) void(^ _Nullable finally)(void);
|
||||
@end
|
||||
|
||||
@implementation NMBExceptionCapture
|
||||
|
||||
- (nonnull instancetype)initWithHandler:(void(^ _Nullable)(NSException * _Nonnull))handler finally:(void(^ _Nullable)(void))finally {
|
||||
self = [super init];
|
||||
if (self) {
|
||||
self.handler = handler;
|
||||
self.finally = finally;
|
||||
}
|
||||
return self;
|
||||
}
|
||||
|
||||
- (void)tryBlock:(__attribute__((noescape)) void(^ _Nonnull)(void))unsafeBlock {
|
||||
@try {
|
||||
unsafeBlock();
|
||||
}
|
||||
@catch (NSException *exception) {
|
||||
if (self.handler) {
|
||||
self.handler(exception);
|
||||
}
|
||||
}
|
||||
@finally {
|
||||
if (self.finally) {
|
||||
self.finally();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@end
|
||||
-18
@@ -1,18 +0,0 @@
|
||||
@class NSString;
|
||||
|
||||
/**
|
||||
* Returns a string appropriate for displaying in test output
|
||||
* from the provided value.
|
||||
*
|
||||
* @param anyObject A value that will show up in a test's output.
|
||||
*
|
||||
* @return The string that is returned can be
|
||||
* customized per type by conforming a type to the `TestOutputStringConvertible`
|
||||
* protocol. When stringifying a non-`TestOutputStringConvertible` type, this
|
||||
* function will return the value's debug description and then its
|
||||
* normal description if available and in that order. Otherwise it
|
||||
* will return the result of constructing a string from the value.
|
||||
*
|
||||
* @see `TestOutputStringConvertible`
|
||||
*/
|
||||
extern NSString *_Nonnull NMBStringify(id _Nullable anyObject) __attribute__((warn_unused_result));
|
||||
-11
@@ -1,11 +0,0 @@
|
||||
#import "NMBStringify.h"
|
||||
|
||||
#if __has_include("Nimble-Swift.h")
|
||||
#import "Nimble-Swift.h"
|
||||
#else
|
||||
#import <Nimble/Nimble-Swift.h>
|
||||
#endif
|
||||
|
||||
NSString *_Nonnull NMBStringify(id _Nullable anyObject) {
|
||||
return [NMBStringer stringify:anyObject];
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user