• Stars
    star
    263
  • Rank 155,624 (Top 4 %)
  • Language
    Swift
  • License
    MIT License
  • Created over 1 year ago
  • Updated 3 months ago

Reviews

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

Repository Details

Magical testing tools for Swift macros.

Macro Testing

CI Slack

Magical testing tools for Swift macros.

An animated demonstration of macro tests being inlined.

Learn more

This library was designed to support libraries and episodes produced for Point-Free, a video series exploring the Swift programming language hosted by Brandon Williams and Stephen Celis.

You can watch all of the episodes here.

video poster image

Motivation

This library comes with a tool for testing macros that is more powerful and ergonomic than the default tool that comes with SwiftSyntax. To use the tool, simply specify the macros that you want to expand as well as a string of Swift source code that makes use of the macro.

For example, to test the #stringify macro that comes with SPM's macro template all one needs to do is write the following:

import MacroTesting
import XCTest

class StringifyTests: XCTestCase {
  func testStringify() {
    assertMacro(["stringify": StringifyMacro.self]) {
      """
      #stringify(a + b)
      """
    }
  }
}

When you run this test the library will automatically expand the macros in the source code string and write the expansion into the test file:

func testStringify() {
  assertMacro(["stringify": StringifyMacro.self]) {
    """
    #stringify(a + b)
    """
  } expansion: {
    """
    (a + b, "a + b")
    """
  }
}

That is all it takes.

If in the future the macro's output changes, such as adding labels to the tuple's arguments, then running the test again will produce a nicely formatted message:

โŒ failed - Actual output (+) differed from expected output (โˆ’). Difference: โ€ฆ

- (a + b, "a + b")
+ (result: a + b, code: "a + b")

You can even have the library automatically re-record the macro expansion directly into your test file by providing the record argument to assertMacro:

assertMacro(["stringify": StringifyMacro.self], record: true) {
  """
  #stringify(a + b)
  """
} expansion: {
  """
  (a + b, "a + b")
  """
}

Now when you run the test again the freshest expanded macro will be written to the expansion trailing closure.

If you're writing many tests for a macro, you can avoid the repetitive work of specifying the macros in each assertion by using XCTest's invokeTest method to wrap each test with Macro Testing configuration:

class StringifyMacroTests: XCTestCase {
  override func invokeTest() {
    withMacroTesting(
      macros: ["stringify": StringifyMacro.self]
    ) {
      super.invokeTest()
    }
  }

  func testStringify() {
    assertMacro {  // ๐Ÿ‘ˆ No need to specify the macros being tested
      """
      #stringify(a + b)
      """
    } expansion: {
      """
      (a + b, "a + b")
      """
    }
  }

  // ...
}

You can pass the isRecording parameter to withMacroTesting to re-record every assertion in the test case (or suite, if you're using your own custom base test case class):

override func invokeTest() {
  withMacroTesting(
    isRecording: true
  ) {
    super.invokeTest()
  }
}

Macro Testing can also test diagnostics, such as warnings, errors, notes, and fix-its. When a macro expansion emits a diagnostic, it will render inline in the test. For example, a macro that adds completion handler functions to async functions may emit an error and fix-it when it is applied to a non-async function. The resulting macro test will fully capture this information, including where the diagnostics are emitted, how the fix-its are applied, and how the final macro expands:

func testNonAsyncFunctionDiagnostic() {
  assertMacro {
    """
    @AddCompletionHandler
    func f(a: Int, for b: String) -> String {
      return b
    }
    """
  } diagnostics: {
    """
    @AddCompletionHandler
    func f(a: Int, for b: String) -> String {
    โ”ฌโ”€โ”€โ”€
    โ•ฐโ”€ ๐Ÿ›‘ can only add a completion-handler variant to an 'async' function
       โœ๏ธ add 'async'
      return b
    }
    """
  } fixes: {
    """
    @AddCompletionHandler
    func f(a: Int, for b: String) async -> String {
      return b
    }
    """
  } expansion: {
    """
    func f(a: Int, for b: String) async -> String {
      return b
    }

    func f(a: Int, for b: String, completionHandler: @escaping (String) -> Void) {
      Task {
        completionHandler(await f(a: a, for: b, value))
      }
    }
    """
  }
}

Documentation

The latest documentation for this library is available here.

License

This library is released under the MIT license. See LICENSE for details.

More Repositories

1

swift-composable-architecture

A library for building applications in a consistent and understandable way, with composition, testing, and ergonomics in mind.
Swift
12,150
star
2

swift-snapshot-testing

๐Ÿ“ธ Delightful Swift snapshot testing.
Swift
3,737
star
3

isowords

Open source game built in SwiftUI and the Composable Architecture.
Swift
2,667
star
4

swift-navigation

Bringing simple and powerful navigation tools to all Swift platforms, inspired by SwiftUI.
Swift
1,950
star
5

swift-dependencies

A dependency management library inspired by SwiftUI's "environment."
Swift
1,527
star
6

swift-tagged

๐Ÿท A wrapper type for safer, expressive code.
Swift
1,364
star
7

swift-overture

๐ŸŽผ A library for function composition.
Swift
1,139
star
8

pointfreeco

๐ŸŽฌ The source for www.pointfree.co, a video series on functional programming and the Swift programming language.
Swift
1,098
star
9

episode-code-samples

๐Ÿ’พ Point-Free episode code.
Swift
950
star
10

swift-case-paths

๐Ÿงฐ Case paths extends the key path hierarchy to enum cases.
Swift
905
star
11

swift-parsing

A library for turning nebulous data into well-structured data, with a focus on composition, performance, generality, and ergonomics.
Swift
847
star
12

swift-nonempty

๐ŸŽ A compile-time guarantee that a collection contains a value.
Swift
839
star
13

swift-custom-dump

A collection of tools for debugging, diffing, and testing your application's data structures.
Swift
795
star
14

swift-html

๐Ÿ—บ A Swift DSL for type-safe, extensible, and transformable HTML documents.
Swift
760
star
15

combine-schedulers

โฐ A few schedulers that make working with Combine more testable and more versatile.
Swift
701
star
16

swift-perception

Observable tools, backported.
Swift
536
star
17

swift-identified-collections

A library of data structures for working with collections of identifiable elements in an ergonomic, performant way.
Swift
529
star
18

swift-web

๐Ÿ•ธ A collection of Swift server-side frameworks for handling HTML, CSS, routing and middleware.
Swift
481
star
19

swift-prelude

๐ŸŽถ A collection of types and functions that enhance the Swift language.
Swift
469
star
20

swift-validated

๐Ÿ›‚ A result type that accumulates multiple errors.
Swift
392
star
21

swift-issue-reporting

Report issues in your application and library code as Xcode runtime warnings, breakpoints, assertions, and do so in a testable manner.
Swift
361
star
22

swift-url-routing

A bidirectional router with more type safety and less fuss.
Swift
347
star
23

swift-concurrency-extras

Useful, testable Swift concurrency.
Swift
315
star
24

swift-gen

๐ŸŽฑ Composable, transformable, controllable randomness.
Swift
266
star
25

swift-clocks

โฐ A few clocks that make working with Swift concurrency more testable and more versatile.
Swift
258
star
26

syncups

A rebuild of Appleโ€™s โ€œScrumdingerโ€ application using modern, best practices for SwiftUI development.
Swift
205
star
27

swift-enum-properties

๐Ÿค Struct and enum data access in harmony.
Swift
200
star
28

composable-core-location

A library that bridges the Composable Architecture and Core Location.
Swift
108
star
29

vapor-routing

A bidirectional Vapor router with more type safety and less fuss.
Swift
89
star
30

swift-html-vapor

๐Ÿ’ง Vapor plugin for type-safe, transformable HTML views.
Swift
84
star
31

swift-playground-templates

๐Ÿซ A collection of helpful Xcode playground templates.
Makefile
81
star
32

pointfreeco-server

Point-Free server code.
40
star
33

TrySyncUps

The starting project for our try! Swift 2024 Composable Architecture workshop.
Swift
38
star
34

composable-core-motion

A library that bridges the Composable Architecture and Core Motion.
Swift
29
star
35

swift-boundaries

๐Ÿฃ Functional core, imperative shell.
Swift
28
star
36

swift-quickcheck

๐Ÿ An implementation of QuickCheck in Swift.
Swift
25
star
37

swift-either

For those times you want A or B!
Swift
21
star
38

swift-algebras

Algebraic laws bundled into concrete data types.
20
star
39

swift-parser-printer

โ†”๏ธ Parsing and printing
Swift
15
star
40

swift-html-kitura

โ˜๏ธ Kitura plugin for type-safe, transformable HTML views.
Swift
14
star
41

swiftui-navigation

This package is now Swift Navigation:
Swift
13
star
42

homebrew-swift

Ruby
3
star
43

swift-bugs

3
star
44

Ccmark

Swift
2
star
45

.github

1
star