Asserts on roids, test all your assumptions with ease.

Overview

KZAsserts - Asserts on roids, test all your assumptions with ease.

Version Platform

There are many ways in which we can improve quality of our code-base, Assertions are one of them. Yet very few people actually use asserts, why is that?

An assert is used to make certain that a specific condition is true, because our apps don't exist in a vacuum and we often work with other API's (or our own), we need to make sure our assumptions about it are actually valid or we might have really weird bugs.

If our assumption is wrong, assert will crash on the line that checks that condition thus allowing us to find bugs in our code very quickly.

This is great concept, crash early and crash often, it makes it easy to have clean and bug free code.

On the other hand Release build should avoid crashing whenever possible, unless you like 1-star rating?

Because of that normal assertions are not enough, you need to make sure your code handles errors even in release builds, if you just strip assertions from release you are still going to crash if your assumption was wrong (eg. after striping asserts you'll have code that mismatches types etc.)!

How great would it be to assert all assumptions regarding server API responses, so that if backend changes you know it immediately and you can fix your code? So people end up with something like this:

NSParameterAssert([dataFromServer isKindOfClass:[NSDictionary class]]);
if ([dataFromServer isKindOfClass:[NSDictionary class]]) {
  //! create NSError, handle it
}

NSParameterAssert([something isKindOfClass:[NSString class]]);
if ([something isKindOfClass:[NSString class]]) {
  //! create NSError, handle it
}

Obviously they could store that condition once and reuse it in assert and if statement, it still sucks!

Now imagine testing your whole response format, that would be so much unnecesary and hard to read code!

That's why I've come up with KZAsserts around 2 years ago, this is how that could can look:

AssertTrueOrReturnError([dataFromServer isKindOfClass:[NSDictionary class]]);
AssertTrueOrReturnError([something isKindOfClass:[NSString class]]);

This will crash in debug, but in release it will automatically generate NSError for you, it will then return that error object from the current scope. It can also log message to your logger / server / console: IMAGE

And that's not all, you probably write a lot of async code in your apps? KZAsserts handles that as easily:

- (void)downloadFromURL:(NSURL*)url withCompletion:(void (^)(NSData *, NSError *))completionBlock
{
	AssertTrueOrReturnNilBlock([something isKindOfClass:[NSString class]], ^(NSError *error) {
  		completionBlock(nil, error);
	});
	//! ...
}

With those kind of macros, you can now assert all your assumptions. I'd also encourage you to use Asserts for enforcing API contracts: eg. if you have a method that downloads NSData * and the only way to get the results is via completion block, you should assert there actually is completion block. Otherwise you are wasting your user battery/network.

Assert macros

KZAsserts provies following asserts:

  AssertTrueOr[X](condition) - if condition fails to be true, on debug builds it will crash by using Assertion, on Release builds it calls error creation and perform specific action. Asserts with block param will execute ^(NSError *){} passed in block with auto-generated NSError.

  AssertTrueOrReturnError
  AssertTrueOrReturnErrorBlock

  AssertTrueOrReturn
  AssertTrueOrReturnBlock

  AssertTrueOrReturnNo
  AssertTrueOrReturnNoBlock

  AssertTrueOrReturnNil
  AssertTrueOrReturnNilBlock

  AssertTrueOrContinue
  AssertTrueOrContinueBlock

  AssertTrueOrBreak
  AssertTrueOrBreakBlock

Installation

KZAsserts is available through CocoaPods for OSX, iOS and tvOS, to install it simply add the following line to your Podfile:

pod "KZAsserts"

Supplying your own NSError creation function

If you want to have your own NSError creation function you can just add following line on top of your applicationDidFinishLaunching:

[KZAsserts registerErrorFunction:myErrorCreationFunction];

You can also change whole format of logging by defining your own KZAMakeError macro.

Test Assertion flow during debugging

In debug version, the assert aborts the program, sometimes we want quick look, what's will happens in release version. If you adding symbolic breakpoint with action you can check it:

+[KZAsserts debugPass:]    p shouldPass = YES

To copy paste, symbol and action:

+[KZAsserts debugPass:]
p shouldPass = YES

Author

Krzysztof Zablocki, @merowing_ my blog

License

KZAsserts is available under the MIT license. See the LICENSE file for more info.

You might also like...
Identify Intel-Only Apps on your Mac with ease:
Identify Intel-Only Apps on your Mac with ease:

Silicon About Identify Intel-Only Apps on your Mac with ease: License Project is released under the terms of the MIT License. Repository Infos Owner:

This is a control that helps you dramatically ease your infinite scroll processing.

InfiniteScrollControl Example To run the example project, clone the repo, and run pod install from the Example directory first. Requirements Installat

A cross-platform library of Swift utils to ease your iOS | macOS | watchOS | tvOS and Linux development.
A cross-platform library of Swift utils to ease your iOS | macOS | watchOS | tvOS and Linux development.

Mechanica A library of Swift utils to ease your iOS, macOS, watchOS, tvOS and Linux development. Requirements Documentation Installation License Contr

GLWalkthrough is an easily configurable plug-and-play tool to add walkthrough or coachmarker functionality to your app with ease.
GLWalkthrough is an easily configurable plug-and-play tool to add walkthrough or coachmarker functionality to your app with ease.

GLWalkthrough Example To run the example project, clone the repo, and run pod install from the Example directory first. Requirements Installation GLWa

Xcode-developer-disk-image-all-platforms - A repo which shares all developer disk images for iOS, tvOS, watchOS
Xcode-developer-disk-image-all-platforms - A repo which shares all developer disk images for iOS, tvOS, watchOS

Disclaimer: The available resources and files from this repo are uploaded from many contributors. The files are unverified, untested, and could have n

Ease is an event driven animation system that combines the observer pattern with custom spring animations as observers
Ease is an event driven animation system that combines the observer pattern with custom spring animations as observers

Ease is an event driven animation system that combines the observer pattern with custom spring animations as observers. It's magic. Features Animate a

Appz 📱 Launch external apps, and deeplink, with ease using Swift!
Appz 📱 Launch external apps, and deeplink, with ease using Swift!

Appz 📱 Deeplinking to external applications made easy Highlights Web Fallback Support: In case the app can't open the external application, it will f

nef💊a toolset to ease the creation of documentation in the form of Xcode Playgrounds
nef💊a toolset to ease the creation of documentation in the form of Xcode Playgrounds

nef, short for Nefertiti, mother of Ankhesenamun, is a toolset to ease the creation of documentation in the form of Xcode Playgrounds. It provides com

DataKernel is a minimalistic wrapper around CoreData stack to ease persistence operations.

DataKernel What is DataKernel? DataKernel is a minimalistic wrapper around CoreData stack to ease persistence operations. It is heavily inspired by Su

RxReduce is a lightweight framework that ease the implementation of a state container pattern in a Reactive Programming compliant way.
RxReduce is a lightweight framework that ease the implementation of a state container pattern in a Reactive Programming compliant way.

About Architecture concerns RxReduce Installation The key principles How to use RxReduce Tools and dependencies Travis CI Frameworks Platform Licence

Image slide-show viewer with multiple predefined transition styles, with ability to create new transitions with ease.
Image slide-show viewer with multiple predefined transition styles, with ability to create new transitions with ease.

ATGMediaBrowser ATGMediaBrowser is an image slide-show viewer that supports multiple predefined transition styles, and also allows the client to defin

An elegant library for stubbing HTTP requests with ease in Swift

Mockingjay An elegant library for stubbing HTTP requests in Swift, allowing you to stub any HTTP/HTTPS using NSURLConnection or NSURLSession. That inc

📱📲 Navigate between view controllers with ease. 💫 🔜 More stable version (written in Swift 5) coming soon.

CoreNavigation 📱 📲 Navigate between view controllers with ease. 💫 🔜 More stable version (written in Swift 5) coming soon. Getting Started API Refe

Call Swift functions from Rust with ease!

swift-rs Call Swift functions from Rust with ease! Todo Swift class deallocation from rust (implementing Drop and using deallocate_{type} methods) Mor

Use this package in order to ease up working with Combine URLSession.

Use this package in order to ease up working with Combine URLSession. We support working with Codable for all main HTTP methods GET, POST, PUT and DELETE. We also support MultipartUpload

RxReduce is a lightweight framework that ease the implementation of a state container pattern in a Reactive Programming compliant way.
RxReduce is a lightweight framework that ease the implementation of a state container pattern in a Reactive Programming compliant way.

About Architecture concerns RxReduce Installation The key principles How to use RxReduce Tools and dependencies Travis CI Frameworks Platform Licence

DevSwitch - An iOS app for switching between countries on the App Store with ease.
DevSwitch - An iOS app for switching between countries on the App Store with ease.

Archived as of 24/04/2021. Apple has again broken the URLs required for storefront switching. I've decided to archive DevSwitch due to this. If Apple

🚀 Create XCFrameworks with ease! A Command Line Tool to create XCFramework for multiple platforms at one shot! The better way to deal with XCFrameworks for iOS, Mac Catalyst, tvOS, macOS, and watchOS.
🚀 Create XCFrameworks with ease! A Command Line Tool to create XCFramework for multiple platforms at one shot! The better way to deal with XCFrameworks for iOS, Mac Catalyst, tvOS, macOS, and watchOS.

Surmagic 🚀 Create XCFramework with ease! A Command Line Tool to create XCFramework for multiple platforms at one shot! The better way to deal with XC

Lightweight lib around NSURLSession to ease HTTP calls

AeroGear iOS HTTP Thin layer to take care of your http requests working with NSURLSession. Project Info License: Apache License, Version 2.0 Build: Co

Comments
  • Improvements (prefixes, expose interface, warnings)

    Improvements (prefixes, expose interface, warnings)

    • Added KZ_ prefix to colors defines.
    • KZAssert.podspec update deployment_target to 6.0 because are warning: setObject:forKeyedSubscript: is only available on iOS 6.0 or newer.
    • Add two defines: AssertTrueOrIgnore and AssertTrueOrIgnoreBlock.
    • Added public access to userInfo keys and add 'Condition' key. Expand define KZAMakeError.
    • Update KZAssert.podspec. Bump version to 1.2.0.
    • Update README.md.
    opened by trzeciak 0
Releases(1.1.0)
Owner
Krzysztof Zabłocki
Dev, Speaker, Creator. Currently Lead iOS @NYTimes My code powers up more than 70 000 apps.
Krzysztof Zabłocki
An Xcode formatter plug-in to format your swift code.

Swimat Swimat is an Xcode plug-in to format your Swift code. Preview Installation There are three way to install. Install via homebrew-cask # Homebrew

Jintin 1.6k Jan 7, 2023
Find memory leaks in your iOS app at develop time.

中文介绍 | FAQ中文 MLeaksFinder MLeaksFinder helps you find memory leaks in your iOS apps at develop time. It can automatically find leaks in UIView and UIV

Tencent 5.3k Dec 22, 2022
Find memory issues & leaks in your iOS app without instruments

HeapInspector Find memory issues & leaks in your iOS app HeapInspector is a debug tool that monitors the memory heap with backtrace recording in your

Christian Menschel 1.8k Nov 24, 2022
An xcconfig (Xcode configuration) file for easily turning on a boatload of warnings in your project or its targets.

Warnings This is an xcconfig file to make it easy for you to turn on a large suite of useful warnings in your Xcode project. These warnings catch bugs

Peter Hosey 438 Nov 8, 2022
Find common xib and storyboard-related problems without running your app or writing unit tests.

IBAnalyzer Find common xib and storyboard-related problems without running your app or writing unit tests. Usage Pass a path to your project to ibanal

Arek Holko 955 Oct 15, 2022
decoupling between modules in your iOS Project. iOS模块化过程中模块间解耦方案

DecouplingKit 中文readme Podfile platform :ios, '7.0' pod 'DecouplingKit', '~> 0.0.2' DecouplingKit, decoupling between modules in your iOS Project. D

coderyi 139 Aug 23, 2022
A collection of useful test helpers designed to ease the burden of writing tests for iOS applications.

MetovaTestKit is a collection of useful test helpers designed to ease the burden of writing tests for iOS applications. Requirements Installation Usag

null 23 Aug 29, 2021
Test-To-Do-List - Test To Do List with core data

test-To-Do-List This is my first pet project with core data Launch screen Main s

Artem 0 Feb 26, 2022
Kfm-ios-test - Test online for iOS Developer position in Kimia Farma or PT. Buana Varia Komputama

kfm-ios-test Kimia Farma Mobile iOS Test Test online for iOS Developer position

Erwindo Sianipar 3 Feb 23, 2022
Library for iOS Camera API. Massively increase performance and ease of use within your next iOS Project.

CameraKit helps you add reliable camera to your app quickly. Our open source camera platform provides consistent capture results, service that scales,

CameraKit 628 Dec 27, 2022