• Stars
    star
    355
  • Rank 119,764 (Top 3 %)
  • Language
    Swift
  • License
    MIT License
  • Created almost 2 years ago
  • Updated over 1 year ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Power Assert in Swift.

Swift Power Assert

test workflow Build Status codecov

Power asserts (also known as diagrammed assertions) augment your assertion failures with information about the values produced during evaluation of a condition, and present it in an easily digestible form. Power asserts are a popular feature of Spock (and later the entire Groovy language independent of Spock), ScalaTest and Expecty.

Power asserts provide descriptive assertion messages for your tests, like the following examples:

#assert(numbers[2] == 4)
        โ”‚       โ”‚โ”‚ โ”‚  โ”‚
        โ”‚       โ”‚3 โ”‚  4
        โ”‚       2  false
        [1, 2, 3, 4, 5]

--- [Int] numbers[2]
+++ [Int] 4
โ€“3
+4

[Int] numbers[2]
=> 3
[Int] 4
=> 4

#assert(numbers.contains(6))
        โ”‚       โ”‚        โ”‚
        โ”‚       false    6
        [1, 2, 3, 4, 5]

#assert(string1 == string2)
        โ”‚       โ”‚  โ”‚
        โ”‚       โ”‚  "Hello, Swift!"
        โ”‚       false
        "Hello, world!"

--- [String] string1
+++ [String] string2
Hello, {+S+}w[-orld-]{+ift+}!

[String] string1
=> "Hello, world!"
[String] string2
=> "Hello, Swift!"

Online Playground

Experience the library in action with our online playground! โœจ Click here to access the interactive demo.

Why Power Assert?

When writing tests, we need to use different assertion functions. With Power Assert you only use the #assert() function. There are many Assertion APIs, no need to remember them. Just create an expression that returns a boolean value and Power Assert will automatically display rich error information.

Getting Started

Swift Power Assert is implemented using macros, an experimental feature of Swift. Therefore, Xcode 15 beta must be installed to use this library.

  1. Download and extract Xcode 15 beta. https://developer.apple.com/download/all/
  2. (Optional) To use this library from the command line, go to the Xcode menu and select Settings... > Locations > Locations > Command Line Tools and select "Xcode -beta-15.0".

For Xcode Project

To see PowerAssert in action, go to the Examples directory and run xcodebuild test ....

$ cd Examples/XcodeProject/
$ xcodebuild test -scheme MyApp -destination 'platform=iOS Simulator,name=iPhone 14 Pro,OS=17.0' -parallel-testing-enabled NO

The parameter -parallel-testing-enabled NO is required. Due to recent changes in Xcode, parallel testing is now turned on by default and test messages are no longer output to the console. Therefore, to see assertion messages in the console, disable parallel testing. When parallel testing is enabled, all console logs can be viewed from the result bundle.

Or set the following UserDefaults. This option allows console output even if parallel testing is enabled.

defaults write com.apple.dt.xcodebuild ParallelTestRunnerStdoutMirroringEnabled -bool YES

For Swift Package Manager

To see PowerAssert in action, go to the Examples directory and run swift test.

$ cd Examples/SwiftPackage/
$ swift test

See the following results?

...
Test Suite 'All tests' started at 2023-04-05 07:17:58.800
Test Suite 'swift-power-assert-examplePackageTests.xctest' started at 2023-04-05 07:17:58.801
Test Suite 'PowerAssertTests' started at 2023-04-05 07:17:58.801
Test Case '-[ExampleTests.PowerAssertTests testExample]' started.
/swift-power-assert/Example/"ExampleTests/ExampleTests.swift":8: error: -[ExampleTests.PowerAssertTests testExample] : failed -
#assert(a * b == 91)
        โ”‚ โ”‚ โ”‚ โ”‚  โ”‚
        โ”‚ โ”‚ 9 โ”‚  91
        โ”‚ 90  false
        10

[Int] a
=> 10
[Int] b
=> 9
[Int] a * b
=> 90
[Int] 91
=> 91
/swift-power-assert/Example/"ExampleTests/ExampleTests.swift":11: error: -[ExampleTests.PowerAssertTests testExample] : failed -
#assert(xs.contains(4))
        โ”‚  โ”‚        โ”‚
        โ”‚  false    4
        [1, 2, 3]
...

Modify the code in Example/Tests/ExampleTests.swift to try different patterns you like.

Usage

To use Swift Power Assert in your library or application, first add swift-power-assert to your project.

For the Xcode project, add the swift-power-assert library as a package dependency.

Select PowerAssert as the Package Product and specify the Test Bundle as the target to add.

For the Swift package, configure Package.swift as follows:

// swift-tools-version:5.8
import PackageDescription

let package = Package(
  name: "MyLibrary",
  dependencies: [
    ...,
    .package(
      url: "https://github.com/kishikawakatsumi/swift-power-assert.git",
      from: "0.12.0"
    ),
  ],
  targets: [
    ...,
    .testTarget(
      name: "MyLibraryTests",
      dependencies: [
        ...,
        .product(name: "PowerAssert", package: "swift-power-assert"),
      ]
    ),
  ]
)

Next, you can use Power Assert in your tests with the #assert() macro.

// MyLibraryTests.swift
import XCTest
import PowerAssert
@testable import MyLibrary

final class MyLibraryTests: XCTestCase {
  func testExample() {
    let a = 7
    let b = 4
    let c = 12

    #assert(max(a, b) == c)
  }
}

Concurrency (async/await) support

Swift Power Assert library allows you to write assertions with async/await expressions directly. Here's a sample code demonstrating its seamless support for async/await:

func testConcurrency() async {
  let ok = "OK"
  #assert(await upload(content: "example") == ok)
}

For use on CI

For unattended use (e.g. on CI), you can disable the package validation dialog by

  • individually passing -skipMacroValidation to xcodebuild or
  • globally setting defaults write com.apple.dt.Xcode IDESkipMacroFingerprintValidation -bool YES for that user.

Frequently Asked Questions

Q: Assert failure messages are not displayed.

If you are running your tests from the command line using the xcodebuild test ... command, disable parallel testing. Due to recent changes in Xcode, detailed test logs are not output to the console when parallel testing is enabled. Use the following options to disable parallel testing

-parallel-testing-enabled NO

Alternatively, set the following UserDefaults. This option enables detailed messages to be output to the console even parallel testing enabled.

defaults write com.apple.dt.xcodebuild ParallelTestRunnerStdoutMirroringEnabled -bool YES

Q: I want to display the result even if the test is successful (i.e. the expression in the #assert() function evaluates to true).

A: By default, the #assert() function does not display the result if the expression evaluates to true, because the test was successful. To always print the result, set the verbose argument to true.

For example:

#assert(x == y, verbose: true)

Q: I want to know how the compiler actually expanded the macro.

A: You can use the -dump-macro-expansions option to dump the macro expansion.

For example:

$ cd Examples/SwiftPackage/
$ swift test -Xswiftc -Xfrontend -Xswiftc -dump-macro-expansions

If you run the above with the -dump-macro-expansions option, you will get the following output.

...
@__swiftmacro_12ExampleTests011PowerAssertB0C04testA0yyF6assertfMf_.swift as ()
------------------------------
PowerAssert.Assertion("#assert(a * b == 91)", message: "", file: #""ExampleTests/ExampleTests.swift""#, line: 8, verbose: false, binaryExpressions: [0: "a", 2: "a * b", 3: "91", 1: "b"]) {
    $0.capture($0.capture($0.capture(a .self, column: 8, id: 0) * $0.capture(b .self, column: 12, id: 1), column: 10, id: 2) == $0.capture(91, column: 17, id: 3), column: 14, id: 4)
}
.render()
------------------------------
...

Supporters & Sponsors

Open source projects thrive on the generosity and support of people like you. If you find this project valuable, please consider extending your support. Contributing to the project not only sustains its growth, but also helps drive innovation and improve its features.

To support this project, you can become a sponsor through GitHub Sponsors. Your contribution will be greatly appreciated and will help keep the project alive and thriving. Thanks for your consideration! โค๏ธ

Author

Kishikawa Katsumi

License

The project is released under the MIT License

More Repositories

1

KeychainAccess

Simple Swift wrapper for Keychain that works on iOS, watchOS, tvOS and macOS.
Swift
7,532
star
2

UICKeyChainStore

UICKeyChainStore is a simple wrapper for Keychain on iOS, watchOS, tvOS and macOS. Makes using Keychain APIs as easy as NSUserDefaults.
Objective-C
3,072
star
3

IBPCollectionViewCompositionalLayout

Backport of UICollectionViewCompositionalLayout to earlier iOS 12
Swift
1,467
star
4

PEPhotoCropEditor

Image cropping library for iOS.
Objective-C
1,087
star
5

SECoreTextView

SECoreTextView is multi style text view.
Objective-C
947
star
6

SourceKitForSafari

SourceKit for Safari is a Safari extension for GitHub, that enables Xcode features like go to definition, find references, or documentation on hover.
JavaScript
680
star
7

Kuery

A type-safe Core Data query API using Swift 4's Smart KeyPaths
Swift
621
star
8

ClassicMap

Google Map is back to iOS 6.
Objective-C
541
star
9

JavaScriptBridge

Write iOS apps in Javascript! JavaScriptBridge provides the way to write iOS apps with JavaScript. Powered by JavaScriptCore.framework.
Objective-C
523
star
10

UCZProgressView

UCZProgressView is a circular progress indicator for image loading.
Objective-C
481
star
11

MapKit-Route-Directions

Extend MapKit to add route directions powered by Google Maps API.
Objective-C
350
star
12

ScreenRecorder

Capturing a screen as videos on iOS devices for user testing.
Objective-C
315
star
13

BookReader

Sample code for PDFKit on iOS 11, clone of iBooks.app built on top of PDFKit.
Swift
306
star
14

xcresulttool

A GitHub Action that generates a human-readable test report from the Xcode result bundle and shows it on GitHub Checks.
TypeScript
297
star
15

TextKitExamples

TextKit examples for try! Swift NYC 2016
Swift
294
star
16

AppStore-Clone-CollectionViewCompositionalLayouts

Sample project for implementing App Store.app UI with Collection View Compositional Layouts
Swift
280
star
17

swiftfmt

Format Swift code
Swift
215
star
18

SwiftPowerAssert

Power Assert in Swift. Provides descriptive assertion messages.
Swift
198
star
19

UltimateGuideToAnimations

Swift
184
star
20

JapaneseKeyboardKit

Sample implementation for iOS Custom Keyboard Extension with Mozc (Google Japanese Input)
Objective-C
148
star
21

RealmTypeSafeQuery

A type-safe Realm query extensions using Swift 4 Smart KeyPaths
Swift
131
star
22

swiftui-playground

SwiftUI Online Playground
JavaScript
119
star
23

xcjobs

Support the automation of release process of iOS/OSX apps with CI
Ruby
117
star
24

applelocalization-web

HTML
106
star
25

AutoLayoutManiacs

Swift
93
star
26

deliverbot

Go
81
star
27

WebTranslator

Safari web extension for DeepL translate.
CSS
79
star
28

FlipCardNavigationView

Objective-C
75
star
29

UUIDShortener

Convert UUID 32-character hex string into a Base32 short string and back.
Objective-C
70
star
30

BandwidthLimiter

Swift
69
star
31

YAMapKit

Yet Another MapKit.framework based on Google Maps Javascript API.
Objective-C
67
star
32

DescriptionBuilder

DescriptionBuilder (iPhone Utility Program) - Assists implementing description method.
Objective-C
67
star
33

Mozc-for-iOS

Mozc - Japanese Input Method for Chromium OS, Android, Windows, Mac and Linux
C
65
star
34

VoiceNavigation

UI Navigation by voice dictation on iOS 5.1
Objective-C
46
star
35

swift-ast-explorer-playground

Online playground for Swift AST Explorer
HTML
45
star
36

AUCapture

Swift
44
star
37

SymbolFontKit

Easy to use 'SymbolFont' as image in iOS 6.
Objective-C
38
star
38

TiledLayerView

CATiledLayer with UIScrollView Sample.
Objective-C
37
star
39

hatena-touch

Hatena touch / iPhone
Objective-C
36
star
40

CollectionUtils

Useful utilities for Objective-C collection classes.
Objective-C
36
star
41

ForceOrientationSample-iOS

Force view to enter landscape in iOS like YouTube app
Swift
36
star
42

ldr-touch

LDR touch / iPhone
Objective-C
35
star
43

swift-magic

A Swift wrapper for libmagic
Swift
33
star
44

SwiftAST

Experimental project for parsing an output that `swift -dump-ast` produces
Swift
28
star
45

CropImageSample

Objective-C
27
star
46

FTSKit

Full Text Search Library for iOS SDK.
C
27
star
47

PhotoFlipCardView

Flip card photo galally sample
Objective-C
26
star
48

VirtualCameraComposer-Example

Objective-C++
25
star
49

tv-listings

TV Listings / iPhone
Objective-C
23
star
50

SwiftSyntax

SwiftSyntax SwiftPM module
Swift
22
star
51

UIKeyInput-UITextInput-Sample

Objective-C
21
star
52

Doorlock

Swift
20
star
53

DownloadFont

Sample code for downloading additional font on iOS 6 or 7.
Objective-C
19
star
54

swift-compiler-discord-bot

JavaScript
19
star
55

WithCamera

Swift
16
star
56

KeyboardShortcuts

Sample program of handling keyboard shortcuts or any keyboard input events.
Objective-C
16
star
57

MacCatalystSlackApp

Swift
15
star
58

TiKeyChainStore

KeyChain module for Titanium Mobile iPhone
Objective-C
14
star
59

Realm-Hands-On

Swift
13
star
60

WWDCChecker-iPhone

WWDC 2012 Checker
Objective-C
13
star
61

applelocalization-data

Clojure
9
star
62

WWDCChecker-Mac

WWDC Site Update Checker With Push Notification Support (Via Parse.com)
Objective-C
9
star
63

iOSDC-2020-UICollectionViewCompositionalLayout

9
star
64

applelocalization-tools

Swift
8
star
65

ExplodeChristmas

Let's explode Christmas.
Objective-C
7
star
66

BuildNumber

Objective-C
7
star
67

bitrise-step-xcode-result-bundle-to-checks

A Bitrise Step that generates a human-readable test report from the Xcode result bundle and shows it on GitHub Checks.
JavaScript
7
star
68

attendancebot

Go
5
star
69

UICollectionViewCompositionalLayout-Workshop-Starter

Swift
5
star
70

LeapMotionSwipeLockScreen

Swipe gesture to lock the screen with Leap Motion.
Objective-C
5
star
71

GoogleAnalytics-for-WinJS

GoogleAnalytics for WinJS
JavaScript
4
star
72

TextViewLinks

Customize clickable links with UITextView.
Objective-C
4
star
73

TextViewCompatibility

Workaround for iOS 7 UITextView scrolling bugs.
Objective-C
4
star
74

webpdecoder

Swift package for libwebpdecoder
C
4
star
75

Realm-CoreData-Performance

Benchmark code for Realm and CoreData
Objective-C
4
star
76

swift-power-assert-playground

SwiftPowerAssert online live demo
HTML
4
star
77

TextChatTranslator

Swift
4
star
78

FittingLabel

Swift
3
star
79

coveralls-gcov

Upload coverage information generated by Gcov to coveralls.io.
Ruby
3
star
80

dotfiles

Shell
3
star
81

swift-online-playground-tutorial

HTML
3
star
82

downloadable-ios-apps

Objective-C
3
star
83

SwiftFiddleEditor

Swift
3
star
84

async-await-in-swift

HTML
2
star
85

xcresulttool-static

HTML
2
star
86

xcresulttool-example

Swift
2
star
87

swiftfmt-playground

Swiftfmt online playground
HTML
2
star
88

codespace-swift

Dockerfile
2
star
89

swift-package-libbsd

Simple wrapper around the C Library BSD for use with Swift Package Manager on Linux
Swift
2
star
90

make-check

Create GitHub Checks.
JavaScript
2
star
91

swift-developers-japan-discussion-archive

Swift Developers JapanใฎDiscordใ‚ตใƒผใƒใƒผใซๆŠ•็จฟใ•ใ‚ŒใŸ้ŽๅŽปใฎ่ญฐ่ซ–ใ‚’้–ฒ่ฆงใƒปๆคœ็ดขใงใใ‚‹Webใ‚ตใƒผใƒ“ใ‚นใฎใƒชใƒใ‚ธใƒˆใƒชใงใ™ใ€‚
2
star
92

among-us-server-status

Swift
2
star
93

Tree

Swift
2
star
94

WorkaroundPreprocessInfoPlist

Swift
2
star
95

XcodeCloudMac

Swift
1
star
96

prime-number

Swift
1
star
97

XcodeCloud

Swift
1
star
98

NICOLA-Note

1
star
99

StringWidth

Swift
1
star
100

anime-today

Ruby
1
star