[Pitch] Add Issue Capturing & Test-Utility-specific module to Swift Testing

Hello everyone,

The Swift Testing Workgroup has been discussing this as a pre-pitch for ~1.5 months now. This one grew out of the pitch for polling confirmations, and I feel it's past time to bring it to a wider audience.

You can read the pitch as a rendered document on GitHub here. It is also pasted down below.

This has a working implementation! Try it out by following these steps:

Add my fork of Swift Testing as a dependency, specifying the rbrindle/issue-responder-chain branch:

dependencies: [
  ...
  .package(url: "https://github.com/younata/swift-testing.git", branch: "younata/testing-issue-capturing"),
]

Then, add a target dependency to your target:

.target( // or `testTarget`
  ...
  dependencies: [
    ...
    .product(name: "TestingUtilities", package: "swift-testing"),
  ]

Finally, import the "TestingUtilities" module using import TestingUtilities.


Issue Capturing & the TestingUtilities module

Introduction

Test utility authors have additional needs for the tooling they write compared
to test authors. One such need is the ability to verify that a testing utility
has reported an issue. Adding this has driven out a new approach for handling
issues that will be significantly more flexible and friendly to test utility
authors.

This proposal introduces a new TestingUtilities module with the testing library,
containing APIs specifically intended for test utility authors. The first APIs
in this new module API enable test authors to observe and verify that issues
were reported, as well as to otherwise control how issues are handled.

Motivation

Test utility authors can currently make use of the
withKnownIssue
family of functions in order to verify that an issue was reported.
Unfortunately, the semantics of withKnownIssue are that any issue recorded
inside of withKnownIssue is something that needs to to be fixed. That is,
withKnownIssue is for tests that are not working correctly which the test
author has deprioritized fixing. There is no API for indicating that the issues
recorded inside are expected issues as part of the test or tool working
correctly.

For example, in Nimble's integration with
Swift Testing, the
tests for the integration
utilize withKnownIssue in a semantically-incorrect way to validate that a
failing Nimble expectation is correctly reported to Swift Testing's issue
reporting system. In practice, this results in extraneous and unnecessary
console output and UI when Nimble's
SwiftTestingSupportSuite.reportsAssertionFailuresToSwiftTesting test runs,
which can be confusing to someone who doesn't already expect this.

Ideally, the maintainers of Nimble and other testing utilities who would wish to
write tests against their testing utilities would have an API that doesn't imply
that their correctly-behaving tool doesn't have an issue with it.

Furthermore, adding the ability to record reported issues and act on them opens
up an additional avenue for making use of the Testing DSL. For example, the
Polling Confirmations
pitch makes use of recording issues in order to indicate whether a polling
attempt has succeeded or failed.

The testing workgroup feels that there needs to be some space for APIs intended
for test utility authors which is separate from APIs intended for test authors.
As noted earlier, test utility authors often have need for additional need for
APIs that the vast majority of test authors do not need. Rather than clutter the
API surface of the main Testing module and potentially confuse test authors, we
instead will create a separate module within the Testing package to contain
these APIs intended solely for test utility authors.

Proposed solution

This proposal introduces an entirely new APIs to observe and capture issues
before they are reported to the rest of the testing library:
withIssueCapturing(_:) and withIssueCapturing(_:matching:). Additionally,
this proposal introduces a new instance method on Issue which re-emits any
captured issues: Issue.record().

These APIs will be made available as the first public APIs in the new
TestingUtilities module within the testing library package. TestingUtilities
exists to define tooling specifically to help test utility authors write and
verify their libraries.

Detailed design

New TestingUtilities module

We will introduce a new module within the testing library, to provide the new
withIssueCapturing, and Issue.record APIs.

New functions for capturing issues

We will introduce 4 functions for capturing issues, to be made available in
the new TestingUtilities module:

/// Invoke a function, capture and return any issues recorded during its
/// execution. Issues captured will not be sent to the rest of the testing
/// library.
///
/// - Parameters:
///   - body: The function to invoke.
///
/// Library authors use this function to capture and analyze any issues for
/// later analysis. This is particularly useful for verifying that test helpers
/// correctly record issues.
/// Test authors should consider using
/// ``withKnownIssue(_:isIntermittent:sourceLocation:_:when:matching:)``.
func withIssueCapturing(
  _ body: () throws -> Void
) -> [Issue]

/// Invoke a function, capture and return any issues recorded during its
/// execution. Issues captured will not be sent to the rest of the testing
/// library.
///
/// - Parameters:
///   - body: The function to invoke.
///
/// Library authors use this function to capture and analyze any issues for
/// later analysis. This is particularly useful for verifying that test helpers
/// correctly record issues.
/// Test authors should consider using
/// ``withKnownIssue(_:isIntermittent:sourceLocation:_:when:matching:)``.
func withIssueCapturing(
  _ body: sending @isolated(any) () async throws -> Void
) async -> [Issue]

/// Invoke a function, capture and return any issues recorded during its
/// execution. Issues captured will not be sent to the rest of the testing
/// library.
///
/// - Parameters:
///   - body: The function to invoke.
///   - issueMatcher: A function to invoke when an issue occurs that is used to
///     determine if the issue should be captured. By default, all issues match.
///
/// Library authors use this function to capture and analyze any issues for
/// later analysis. This is particularly useful for verifying that test helpers
/// correctly record issues.
/// Test authors should consider using
/// ``withKnownIssue(_:isIntermittent:sourceLocation:_:when:matching:)``.
func withIssueCapturing(
  _ body: () throws -> Void
  matching issueMatcher: @escaping @Sendable (Issue) -> Bool
) -> [Issue]

/// Invoke a function, capture and return any issues recorded during its
/// execution. Issues captured will not be sent to the rest of the testing
/// library.
///
/// - Parameters:
///   - body: The function to invoke.
///   - issueMatcher: A function to invoke when an issue occurs that is used to
///     determine if the issue should be captured. By default, all issues match.
///
/// Library authors use this function to capture and analyze any issues for
/// later analysis. This is particularly useful for verifying that test helpers
/// correctly record issues.
/// Test authors should consider using
/// ``withKnownIssue(_:isIntermittent:sourceLocation:_:when:matching:)``.
func withIssueCapturing(
  _ body: sending @isolated(any) () async throws -> Void
  matching issueMatcher: @escaping @Sendable (Issue) -> Bool
) async -> [Issue]

withIssueCapturing records any matching issues which pass through it, at the
point in the call stack where withIssueCapturing is added. Additionally,
withIssueCapturing does not pass issues along to the rest of the testing
library.

Public API for re-emitting recording issues

We will introduce a new instance method on Issue specifically for re-emitting
captured issues:

extension Issue {
  /// Record this issue to the testing Library.
  ///
  /// - Returns: The issue that was recorded (`self` or a modified copy of it.)
  @discardableResult
  func record() -> Self
}

The Issue.record instance method will be a part of the TestingUtilities module
specifically because it is intended to be used only with withIssueCapturing.

Source compatibility

This is an additive change to the public API and should not affect source
compatibility of existing test code.

Integration with supporting tools

Testing utilities can and should make use of withIssueCapturing to both verify
that test utilities record issues, as well as to enable new tools to make use of
and expand on the DSL provided by the testing library. Otherwise, this proposal
will not have any effect on existing tools which make use of the ABI of the
Testing Library.

Future directions

More Test-Utility-Author specific APIs in TestingUtilities.

There are several other APIs in the testing library which are also candidates
to be made public in the TestingUtilities module. None of these APIs were
investigated as part of this proposal. Such APIs should be considered on their
own merits as part of separate proposals in order to prevent scope creep of
proposals.

General modification and analysis of Issues before they are recorded

In addition to capturing and observing issues, we could also allow for more
general modification and analysis of issues prior to recording. This would allow
test library authors to, for example, add, remove, or modify comments to all
issues recorded before they are sent to the rest of the testing library. There
are several ways we could handle this. This is excluded from this proposal in
the interest of avoiding scope creep and keeping the public API small.

Local Traits

A potential other way to implement this behavior is to extend the trait system
to allow for temporary, or local, traits. Then, we could use a mechanism like
Issue Handling Traits to record and modify issues as they're recorded.

While local traits are a worthwhile area to investigate in the future, they were
considered to be beyond the scope of this proposal. The existing trait system
was not designed to work on units smaller than a Test.Case, and changing that
would invalidate several assumptions made about traits in the testing library.

In the future, Issue Capturing & Issue Observation could be implemented using
local traits. For the time being, they aren't. Even with a local trait system
in place, there is value in separate withIssueCapturing APIs to wrap the
Traits which ultimately implement these, by returning the captured issues.

Event Capturing

Issues are only one part of the Event subsystem of the Testing Library. In
addition to capturing Issues specifically, we could also add APIs to capture
Events generically. This is not included here because the Event type is not
currently a stable API. Additionally, capturing other events would be a large
expansion of scope, but even with that, capturing issues is useful enough that
it should have a dedicated API for specifically gathering issues.

Alternatives considered

Not creating a separate module for testing utilities

The current methodology for gating APIs specifically for test utility authors is
to use the ForToolsIntegrationOnly SPI. Instead of creating a separate module,
Issue Capturing could have been added as a ForToolsIntegrationOnly API. Or,
it could have been made public without a gating SPI. Either approach would
obviate the need for a separate module.

On the whole, using SPIs is suboptimal as it means that the toolchain-provided
testing library cannot be used in tools that use SPI-gated APIs. This
discourages the use of such APIs as utility authors don't want to require users
to rebuild the testing library, nor do they wish to proliferate a dependency on
the non-toolchain testing library. Thus, to encourage that test utility authors
actually use Issue Capturing, it will not require an SPI.

However, while we do wish to encourage test utility authors to make use of Issue
Capturing, we also want to discourage test authors from making use of it. Issue
Capturing is the only API that can wholely prevent an issue from being reported
without any outside notice. In order to prevent accidental misuse of Issue
Capturing from resulting in valid and desired issues from being hidden, it
should require some amount of extra ceremony to be able to access. Which in this
case, is a separate module.

Module Naming

Originally, this proposal called new TestingUtilities module TestingTools.
This name was dropped after a discussion to decide on what a "testing tool" is.
A testing tool is a separate program that interacts with and consumes the
Testing Library's JSON ABI or console output. XCode, the swift test CLI
command, and VSCode (with appropriate plug-ins) are testing tools. A testing
tool is not a library which builds upon APIs provided by the Testing Library.
For example, Nimble is not considered a testing tool. It is more accurate to
call Nimble a testing library, or a testing utility. Considering that Swift
Testing itself is also referred to as the Testing Library, we want to avoid
confusion and establish that libraries, frameworks, or packages that consume the
APIs provided by the Testing Library as part of APIs the
library/framework/package provides should be called testing utilities, and thus
the new module has been named TestingUtilities, as it provides APIs for these
utilities.

Function Naming

Other names considered while developing this proposal include

  • captureIssues
  • withExpectedIssue

captureIssues was initially used in the early drafts of this proposal, but
was dropped in favor of the more idiomatic withIssueCapturing.

withExpectedIssue was a suggestion from one of the testing workgroup members,
and was not used because of potential confusion with XCTest's
XCTExpectFailure(_:enabled:strict:issuematcher:)
API. Additionally, withExpectedIssue implies that a separate issue should be
recorded if no issue was received, which is not a desired behavior of
withIssueCapturing. withIssueCapturing should not record an issue if no
issue was received during the execution of their respective body closures:
they will instead return an empty array.

Make the Issue.record instance method part of the Testing Library

This proposal adds a public Issue.record() instance method to the
TestingUtilities module. This method could instead be a part of the Testing
Library. The reason that the Issue.record() instance method is part of the
TestingUtilities module is because the only way to get an Issue instance is
via withIssueCapturing. It doesn't make sense to add a method to the Testing
Library that can only be used if you use an API provided in the TestingUtilities
library.

Include API for automatically re-emiting captured issues

An earlier revision of this proposal specified a withIssueObservation API
which automatically re-emited captured issues. Some members of the testing
workgroup had concerns that this observation API would not be used enough to
justify the ongoing maintenance burden of that API. Those concerns, combined
with the fact that withIssueObservation can be implemented by client authors
by combining the withIssueCapturing API with the Issue.record() instance
method, are why withIssueObservation was removed from consideration.

func withIssueObservation(_ body: () throws -> Void) -> [Issue] {
  withIssueCapturing(body).map { $0.record() }
}

There are instances for this withIssueObservation API, such as test helpers
which records additional issues providing context around why a series of issues
were recorded. As such, withIssueObservation may be considered in a future,
separate proposal.

Acknowledgments

This proposal came out of a suggestion that
Brandon Williams had for the
polling confirmations
feature to make use of the issue reporting DSL to determine whether or not a
polling attempt had failed. Thanks to him for that suggestion which led to my
second proposal for Swift Testing.

This API is inspired by Nimble's
gatherExpectations
API. Thanks to Jeff Hui for writing the original
implementation of Nimble's gatherExpectations API.

7 Likes

I've participated quite a bit in the discussions amongst the testing workgroup on this topic, so I am repeating my feedback here in the public pitch.

Overall I am strongly in favor of adding these tools to Swift Testing. Right now there is a pretty big weakness in Swift Testing in that everyone that wants to build their own test helpers outside of the Testing library cannot actually test their tools. Amongst our many open-source projects we have about 177 uses of withKnownIssue (and XCTest's equivalent tool) to assert on how our testing tools work. But none of them are "known" issues. They are all expected issues where we really do want to assert that the issues are recorded.

My feedback on the actual pitch is as follows:

Naming of the functions

I don't think withIssueCapturing is the correct name for either tool. Typically the with… style of functions computes an actual result that is returned. Things like withContinuation, withUnsafeBytes, withLock, withAnimation, etc. are all of the form ((A) -> R) -> R. Even the current withKnownIssue is a bit of an outlier here in that it returns Void, but it at least matches the general shape of ((A) -> Void) -> Void. Here we are shoehorning in an array of issues into the signature, ((A) -> Void) -> [Issue], and it's odd enough that I think there's no reason to draw a parallel to the with… family of functions.

I would prefer to see the version that purely captures issues to be named after the action it is taking and the result it is returning:

let issues = captureIssues {
  #expect((false))
}

// or

let issues = Issue.capture {
  #expect((false))
}

And I would prefer the version that matches on issues to be named similarly to withKnownIssue:

withExpectedIssue {
  …
} matching: {
  …
}

And this latter function does not need to return the array of issues. I think returning such an array is confusing because it's not clear if it returns all reported issues, or just ones that match, or don't match.

And I like that the function name has the word "expect" in it because it really is an expectation, just as any #expect statement is. We are asserting that actual issues are recorded in the trailing closure.

Non-escaping matcher

It seems the matching closure could be non-escaping since the closure does not really escape. I know that withKnownIssue uses an escaping closure, but maybe it can also be separately updated someday.

TestingUtilities

I personally don't think a new TestingUtilities library is necessary. Drawing a line between the tools used to make assertions and the tools used to make assertion helpers seems tricky.

Is captureIssues necessary?

If we wanted to keep things as simple and minimal as possible for this first iteration, it could be argued that maybe only withExpectedIssue is needed right now. From what I can tell it is by far the more needed API over captureIssues, and technically you can implement captureIssues in terms of withExpectedIssue if you really need it.

7 Likes

Thank you for bringing this up!

In fact, we have already built our own system for that, testing our test helper’s behavior. As a library client, we needed a separate expectation helper, so we landed with testableExpect for test assertions and expectTestableIssues for the caller.

In short, an exciting direction I’d love to see shipped yesterday :wink:

I don’t have much feedback on the pitch, but I think withExpectedIssue would be sufficient for us. When testing a test utility, we usually want to ensure that some code raises an issue and it failing to do so is an error. This assertion being singular is acceptable in my eyes – a helpful test utility should be raising exactly one issue most of the time, not many. As such, this simplified direction might actually be the better initial take.

1 Like

I really appreciate the feedback so far. There's several points to address, and I have a lot to say. So, I'll break this up into multiple comments.

Behavior

This pitch has 2 separate audiences, and while I thought they were fairly related, I didn't fully appreciate the differences between their desires. Put more plainly: this pitch largely served the second audience, not so much the first. Despite the fact that the first audience is a lot larger than the second.

The first audience is people who want to verify that their assertion helper functions properly records an issue. They want a function that validates that only the expected issues were recorded, and otherwise rejects the unexpected issues. These are the folks who are better served by @mbrandonw's withExpectedIssue API (or similar, more on that later). There is also a style difference between people who want withExpectedIssue for this usecase, and people who would lean towards withIssueCapturing for this usecase. Again, more on that later.

The second audience is people who want to make use of the expectation DSL in their assertion helper functions. For example, with swift fakes, I'd love to be able to use the assertion dsl for Spy.wasCalled(_:) instead of the boolean-based approach. And for that, the as-proposed withIssueCapturing(_:) will work great for that: If any issue was recorded, then that particular call didn't match.

I think that the expectation DSL can be really useful for improving the capabilities of filter-like functions. Instead of having the filter closure return a boolean, the check is that no issues were recorded while the closure ran. This is not only easier to write (assuming your filters only used the AND boolean operator), but it also provides extra context on where a filter failed. That is why I now think that the matching closure for withExpectedIssue should make use of the expectation DSL for checking if an issue matched.

On style: This is analogous to the Mock vs. Spy debate with regards to test doubles. Very simply, a Mock is a kind of test double that is pre-configured with expected calls and asserts on them at call time. A Spy is a kind of test double that records calls, and expects you to assert on them after the fact. I clearly have a preference, which blinded me to the fact that this is about style, not that one is better than the other. This is to say, I personally would still use withIssueCapturing over withExpectedIssue, because that is my style to do the verification after the fact.

So, I think the actions for this are:

  1. Add a separate withExpectedIssue api, where
    1. It takes in matching parameter.
    2. The matching parameter uses the expectation DSL to validate that an issue matches.
    3. the matching parameter defaults to an empty closure (that is, all issues match).
    4. withExpectedIssue returns Void.

That is, withExpectedIssue behaves similarly to withKnownIssue except matching issues are not marked as known issues, they just aren't sent to the rest of the Testing Library.

Discussion on naming will be a separate comment. I'm using withExpectedIssue because that is the name Brandon gave earlier.

With that in mind, I'm also wondering as to whether withIssueCapturing should still take in a matching closure. Especially considering that, to my mind, withIssueCapturing is really for that second audience of people wanting to use the expectation DSL as part of their test helper (or those who would prefer to do their verification after the fact).

Separate Libraries

The Testing Workgroup has had a desire to add a secondary module to the Testing Library for quite some time. Polling Confirmations was in consideration to drive out this secondary module for a while (because polling confirmations, especially as initially proposed, inherently introduced some amount of instability into your tests). For this pitch, the reason to put it in a secondary module is because it can prevent otherwise valid issues from being recorded (though, you can very much do that with Issue Handling Traits. My thought there is that it's much more obvious when a test is using an Issue Handling Trait, which makes it less likely to cause problems. There's also an amount of "we've already deployed Issue Handling Traits in the main Testing Library"). Less importantly, issue capturing is not something that test authors should use: Relative to the amount of people using the main Testing Library, not that many are actually writing test helpers (and even fewer are writing tests for their test helpers). Even fewer people would create test helpers that would make use of the expectation DSL beyond what Issue.record(...) can do for them. (though, looking at how many people create custom Nimble matchers, there is clearly demand for that). Again, this is far less important than making it more difficult for people to accidentally ignore otherwise valid issues. But it at least informed how I demarcate between what should go in the main Testing Library and what should go in TestingUtilities: TestingUtilities is a way to expose some of the more-externally-useful internals of the main Testing Library. This is also why, looking at my current implementation, everything is actually implemented in the main Testing Library, and the only thing in TestingUtilities is a public function that calls into the Testing Library. For example, a future direction we've discussed is exposing the Event type and being able to intercept/capture/emit custom events. That is also something which should go into TestingUtilities, as it's far less useful to J Random Test Author than it is to those using the Testing Library as a platform.

I'm still of the opinion that we should have this second module, and that issue capturing should go into the second module. Especially considering that, as described in the Future Directions section of the pitch doc, there's additional capabilities which'll go into TestingUtilities.

2 Likes

Naming

withExpectedIssue

With the behavior I described earlier, where withExpectedIssue will record an issue if no issues were recorded while executing the body closure, I think that withExpectedIssue is a pretty good name, with only 1 drawback: the existing XCTExpectFailure API in XCTest. XCTExpectFailure is XCTest's version of the Testing Library's withKnownIssue, and I would loath to cause confusion for test authors by having these APIs which behave differently yet share a very similar name.

I'd like more feedback on that decision.

withIssueCapturing

I changed from captureIssues to withIssueCapturing beacuse, in my view, the with... idiom is not so simple as the ((A) -> R) -> R syntax. Semantically, Swift's with... API seems much more similar to Python's with statement, which is powered by the ContextManager API. These shift the execution context to operate slightly differently, or provide access to data within some boundary. For example, withContinuation is providing an interface context with Swift Concurrency. withUnsafeBytes is allowing you to execute in a context where you can operate on the raw bytes of a type. withLock operates within the context of an acquired lock. withTaskGroup allows access to a parallel execution context. Under that interpretation, withIssueCapturing means that we're operating in the context where issues are captured into an array instead of being sent to the rest of the Testing Library.

Of course, I could be reading semantics into a naming idiom where none exist. I don't know if there's ever been a discussion on that naming and how/when with... should be used.

TestingUtilities

I'm not too attached to this name. As mentioned in the pitch doc, this module was initially named TestingTools. After plenty of discussion, I changed the name because some folks view a Testing Tool as something which operates on the Testing Library ABI (such as an IDE like xcode and vscode), not something which operates on the Testing Library API. In fact, while writing out these comments, I've had a couple other ideas that perhaps better capture the intent here:

  • TestingPlatform
  • TestingAPI

The testing workgroup had also previously discussed calling this TestingExtras, which I think is way too vague of a name. As I type this out, I find myself leaning towards TestingPlatform, but I also want feedback on that.

One thing that isn't clear to me is what happens if there are multiple issues recorded during the execution of the first closure, and not all of them match the second matching: closure? @younata replied here:

If that's the proposed behavior, I'd find that somewhat surprising: If I am testing a helper which can record multiple issues, I want to be sure each one is explicitly handled, and if there are extra/unexpected issues recorded, I think those should still be reflected somewhere in the results rather than silently ignored.

Another few ideas to consider:

  • TestingLibrary
  • LibraryTesting
  • TestingLibraryAdditions

Regardless of the name, I am in favor of placing these in some distinct module, mainly to protect against misuse. As a matter of best practice, ordinary @Test functions shouldn't use these. If there is a "known issue" in a real test you want to suppress, there are other features for helping you deal with that, including withKnownIssue, .enabled(if:), and Issue Handling Traits.

That said, this new module doesn't strictly have to be used from separate testing helper libraries. It can still be used from ordinary test targets, as long as they explicitly import TestingUtilities in relevant files. The idea behind that additional required import is that it forces one to acknowledge they are going outside the confines of common testing APIs. A secondary benefit of having a separate module is that it allows easier auditing of the places in a codebase which serve this "testing utility" purpose, by grep'ing for such module imports.

1 Like

Since our meeting yesterday, I've spent quite a bit of time thinking of how to address and answer @smontgomery's concerns.

Matching Multiple Issues

Essentially, trying to validate this code:

func myBadTestHelper() {
    Issue.record("1")
    Issue.record("2")
}

One way to address this is to suggest that authors should use boolean logic in their matcher code to get this, so something like:

withExpectedIssue {
    myBadTestHelper()
} matching: { issue in
    #expect(issue.comments == ["1"] || issue.comments == ["2"])
}

I am not a fan of this. It's bad practice for a test to have logic in it (especially because this logic tends to reflect the logic in the code being tested, leading to tautological tests). Additionally, one of the benefits I listed of using the expectation DSL in the matcher is to reduce the need for boolean logic, which goes directly against this. If we're going to require boolean logic, then the matcher should just be of form @Sendable (Issue) -> Bool.

One alternative for this is to make use of variadic arguments, and require that each matcher must match 1-1 with a recorded issue. The primary issue with this is that, to the best of my knowledge, variadic arguments do not work well with trailing closure syntax. But, you could write code like:

withExpectedIssue {
    myBadTestHelper()
} matching: {
    #expect($0.comments == ["1"]
} _: {
    #expect($0.comments == ["2"]
}

(With declaration as withExpectedIssue(_ body:matching:_:) to require at least one matcher).

I really like this approach. Not only does it avoid requiring any boolean logic, but it also makes it obvious exactly which issues you expect to be recorded. That said, this does have the issue of precluding the use of non-escaping closures.

Speaking of...

Non-Escaping

I've been thinking about this a lot, and the tl;dr is that while this is a nice-to-have, there's really only one way it's feasible and I don't think it's worth the squeeze.

There's only really one way to make use of non-escaping closures in this: if withExpectedIssue is implemented on top of withIssueCapturing, and it processes issues after they've been recorded. i.e.:

func withExpectedIssue(
    _ body: (Void) throws -> Void,
    matching matcher: @Sendable (Void) throws -> Void
    // not shown: variadic matchers, async support, and so forth.
) {
    let issues = withIssueCapturing(body)
    let unmatchedIssues = issues.filter { issue in
        withIssueCapturing { matcher(issue) }.isEmpty == false
    }
    unmatchedIssues.forEach { $0.record() }
    // only a little more involved, because we also want to record an issue if no issues matched.
}

@smontgomery and @grynspan separantely raised issues with doing the processing after-the-fact. Notably that we want to minimize how many issues we retain in-memory, and that also if we make the matcher closure escaping then we can turn this into a trait later.

Doing the issue matching in-place, like how withKnownIssue currently does things, is infeasible with the API design of the expectation DSL. The current API design requires us to store the issue matcher closure as part of a TaskLocal, thus requiring it to be escaping.

But, as mentioned earlier, the variadic matchers approach also seemingly forces these closures to be escaping? Like, with this declaration:

func withExpectedIssue(
  _ body: () throws -> Void,
  matching matcher: @Sendable (Issue) throws -> Void,
  _ additionalMatchers: @Sendable (Issue) throws -> Void...
)

additionalMatchers is an Array of @escaping @Sendable (Issue) throws -> Void. My knowledge of manipulating variadic arguments is not terribly deep, but I don't know of a way to specify that these are non-escaping.

To me, having the issue matcher(s) be non-escaping is a nice-to-have, but isn't really worth going out of our way to pursue.

Moving on.

Preventing Abuse/Misuse

We spoke about this at the Testing Workgroup meeting on Monday. The main thing is that we want to prevent people being able to slap this on as a way to ignore issues. With withIssueCapturing, we are explicitly transferring issue handling to the user, but with withExpectedIssue, we're in this weird limbo state. And thus, it would be relatively easy for someone to write withExpectedIssue { ... } matching: { } and then ignore all issues reported in the body.

We're not going to entirely prevent bad-faith usage of this API, but we can mitigate it and keep withExpectedIssue from being the "one weird trick to get out of having to think". Already, placing withExpectedIssue inside of the TestingUtilities (or... whatever) module will help to mitigate bad-faith usage.

One mitigation I can think of is to have expected issues be recorded in the testing library as expected issues (and going through the event system as expected issues). This way, we can surface that these issues were marked as expected, and tooling can parse these and show them as expected issues. I'm not terribly a fan of that approach: For good faith cases where I actually am validating that some issues were recorded, I'd rather not have my UI/terminal output cluttered by potentially confusing issues being reported.

Another mitigation is variadic matchers + the requirement for matchers to 1-1 match with expected issues. These will go a long way towards preventing bad-faith usage of withExpectedIssue. If you have to keep adding empty matcher closures, then it's at least a pretty glaring sign to other code reviewers that you're not doing the right thing. It's pretty obvious that

withExpectedIssue {
    ...
} matching: { _ in }
    _: { _ in }
    _: { _ in }
    _: { _ in }
    _: { _ in }
    _: { _ in }

has something going wrong with it.

A third mitigation is to not use the expectation DSL in the matcher closures, and instead use boolean return values. That would only really serve to make it more obvious that something fishy is going on, as it would be a bunch of { _ in true } closures instead.

I think the second mitigation, combined with placing withExpectedIssue in a separate module, is the right play here.

Conclusion

For this comment, at least.

I think that withExpectedIssue still has a place here. I don't think that we should spend effort requiring that the matcher closures be non-escaping. I think that we should add variadic matchers. These won't affect the expect-single-issue case too much (though, there should be a convenience that excludes the additional variadic closures, for autocomplete reasons). And I think that requiring 1-1 matchers to expected issues is a sufficient enough mitigation to prevent abuse & misuse, or at least make it obvious when that is going on.

Thoughts? I'm particularly interested in thoughts from @mbrandonw, as you've been the most vocal about the need for this, though I'm of course curious what others think of this.

I couldn't make the workgroup meeting this week due to family sicknesses, so some of my feedback may be repeated or uninformed based on what was discussed:

I may have missed some discussion, but I wouldn't think #expect is used in the matching trailing closure. It would instead be:

} matching: {
  $0.comments == ["1"] || $0.comments == ["2"]
}

And this is already how withKnownIssue works, and so this isn't anything new, and I personally do not think the logic is a deficiency. This little bit of logic is not a big deal in practice, speaking as someone who's written dozens of tests that assert on multiple issues, and long chains of || can easily be written as:

} matching: {
  ["1", "2", …].contains($0.description)
}

Again I may have missed something from the meeting, but the matcher in the proposal is currently of the form (Issue) -> Bool. Has there been a change to this?

While an interesting use of variadic arguments, I find the _: trailing closures strange, and we would still want a tool that is similar to withKnownIssue for situations that may have a dynamic number of issues reported (e.g. a parameterized test that can cause a different number of issues to be reported based on an argument).

I am not strongly advocating for non-escaping, I only mentioned it because it stood out to me in the function signature, and at face value it definitely does not need to be escaping. I understand that there can be technical reasons it is that way, but perhaps someday it would be worth figuring out how to rework the internals to allow for non-escaping. It absolutely does not need to hold up this proposal.

If this is the main impetus for a separate module, then it feels the ship has already sailed:

import Testing
@Suite(.filterIssues { _ in false }) // Every test passes no matter what
struct MySuite { … }

So I personally don't see what it buys us when it costs teaching people that there is another module to import. It's only my personal opinion, and it would be nice to see get some opinions outside of the testing workgroup too.

You didn't miss too much with regard to this proposal. There was a bit about scheduling (we want this in review by around the next meeting, with an extended review duration because of the winter holidays), a suggestion to look at putting this in a custom availability domain (which is now mentioned as an alternative considered), and some discussion of withExpectedIssue (but nothing really newer than what Stuart and I have written earlier in this thread). But, we intentionally kept discussion brief because you were gone. Afterwards, Stuart, Jonathan, and I had a private discussion on implementing non-escaping, but we've all agreed that it's a nice-to-have but not worth it.

(I hope all is well!)


Using Expectation DSL in withExpectedIssue

See earlier in this thread, when I proposed such a solution. Which, to be fair, is buried in the third paragraph of a comment describing the behavior of withExpectedIssue.

And then continued/made a little more explicit (but without samples) a little further below:

I am biased because I am responsible for an entire library for reducing logic in tests, but I think moving away from boolean logic in test is a great idea and will only improve reliability, readability, and most importantly maintainability of tests. I am also someone who is extremely confident working with boolean logic, but that doesn't mean I'm infallible, and anything I can do to make it easier to reason and determine why a test failed is welcome. I think that the expectation DSL is a great way to express that. Especially with multiple #expect/#require already mapping to boolean AND logic, the only issue is boolean OR logic. For this case, given that the primary use of boolean OR is to accept multiple kinds of issues, I think that is well covered by requiring multiple closures.

withIssueCapturing will still capture and return all recorded issues. It'll serve as an escape hatch for cases such as wanting to match against a variable number of issues.

I think an excellent future direction for this work is adding APIs along the lines of Sequence.expectContains and Sequence.expectAllSatisfy to the main Testing Library. These APIs would use the expectation DSL to validate that at least one (expectContains), or all (expectAllSatisfy) elements in a sequence satisfy the matcher. This will be easier to write than something using boolean logic, and it'll be much easier to determine why an issue was recorded when the overall expectation fails (compared to #expect(sequence.contains { ... })).

Another future direction is that I think we should extend withKnownIssue to adopt this paradigm (as in: add a separate withKnownIssue API that behaves like I'm proposing withExpectedIssue should behave, with at-most marking the existing withKnownIssue API as soft-deprecated). I've gone back and forth on whether this should be a part of this proposal, and right now I'm leaning towards making that a future proposal. Though, unlike with Sequence.expectContains/Sequence.expectAllSatisfy (which very clearly should be a separate proposal), it's less obvious to me which is the correct decision.


Preventing Abuse

It's a multi-layered approach, right? The separate module thing does 2 things:

  1. Adds an additional "should you do this?" check, which will hopefully give some folks pause.
  2. Makes it clear that these APIs are not intended for the average test author. The closest thing to writing testing utilities (like what you and I write) that most test authors get to are simple test helpers that DRY up making a series of expectations on a value (and even then, that's happening less and less, thanks claude). Writing tests for these kinds of test helpers is largely redundant (except when it's not, but, again, most people are not writing test helpers where it's non-obvious when they break)

The second layer for preventing abuse is the multiple-matchers thing, though I treat that more as a secondary benefit, with the main benefit being that it reduces the cognitive overhead for reasoning what kind of issues are expected to be reported by a test.

Interestingly, withIssueCapturing is something that we're ok with as-is, because by returning the list of issues, the responsibility for handling these issues is transferred to the caller. withExpectedIssue gets extra scrutiny because matched issues will be dropped entirely, without any kind of fallback.


Variadic trailing closures

Right? I was surprised that a) trailing-closure syntax supported variadic closures, and b) that was the syntax used by the language. That was my TIL on Tuesday when I was prototyping that API. I'm not a fan of that syntax, but changing that is an entirely separate proposal and it's still nicer to use than without the trailing closure syntax.

BTW, even when you name the variadic closure, it still requires _: for the subsequent closures:

func myFunction(_ first: () -> Void, closures: () -> Void...) { }

myFunction {
} closures: {
} _: {
}

Can you give an example of how #expect helps minimize boolean logic? I've never done much more than just comparing issue.comments. I could see occasionally adding on an issue.severity check too. But I don't think kind or sourceLocation would typically be asserted on for these kinds of tests. So I just want to make sure that the matching logic is so cumbersome as to require such a change to the API.

This seems a bit arbitrary to me since a single little _ = will ignore all issues returned. It's these kinds of demarcations of testing functionality that make me feel a separate module is not worth the effort.

One thing to keep in mind that makes withExpectedIssue less prone to abuse than may seem at first is that its matching argument is required, which is not true of withKnownIssue. In withKnownIssue it is completely legitimate to mark some code as reporting an issue with no matcher so that you can say you want to fix it later. But that use case does not exist for withExpectedIssue. (There also is no equivalent of "intermittent" for withExpectedIssue.)

So, if we require matching then people will really have to go out of their way to use this tool to silence issues:

withExpectedIssue {
  …
} matching: { _ in true }

To me this doesn't see much different than one doing _ = to ignore captured issues. And I still don't quite see how someone either accidentally or purposefully uses this tool to silence issues. If done accidentally they would have to contend with the matching closure, and so that's a road block already, and if done purposefully, well, then they could also just delete their test to the same effect.

I previously brought up that this style of API will not play nicely with a dynamic number of expected issues (such as with parameterized tests). Another potential problem is the strict ordering of expected issues. If testing code that runs some tasks in parallel that each can report issues, you may not be able to force the order and so it will not be possible to use this API.

1 Like

sourceLocation isn't likely going to be the first thing people reach for, but it is a thing that at least some people will want to check, to comprehensively ensure that issues recorded by their test helper show up in the right spot. Or, if withIssueCapturing gets adopted, to validate functions capture and re-emit issues with a changed sourceLocation (and/or other properties).

But, yeah, the Issue API, for now, is more limited than I'd like. For issues recorded using Issue.record, you really only have sourceLocation, and comments to check (and even then, that'll almost certainly be a single-value array, unless you do weird things append to that array using withIssueCapturing and re-emit the issue). Checking issue.kind is still useful for determining the source of the issue (#expect, #require, a confirmation, etc.), though it'll require an if-case-let to check that (which, you can wrap into a #expect call, but it's simpler, for now, to have that be two separate calls).

But, for an example, something like:

await confirmation(
  "hello",
  expectedCount: 2
) { confirm in
  confirm()
}

Personally, I'd verify the comment and kind here. Using a boolean statement:

guard issue.comments == ["hello"] else { return false }
if case .confirmationMiscounted(let actual, let expected) = issue.kind,
    actual == 1,
    expected as? ClosedRange<Int> == 2...2 {
  return true
} else {
  return false
}

Using the expectation dsl:

#expect(issue.comments == ["hello"])
if case .confirmationMiscounted(let actual, let expected) = issue.kind {
  #expect(actual == 1)
  #expect(expected as? ClosedRange<Int> == 2...2)
} else {
  Issue.record("Invalid issue kind, expected confirmationMiscounted, got \(issue.kind)")
}

Both are about equal in terms of readability, but the expectation dsl is far easier to debug: everything that can fail is documented with why it failed.

But, yes, this doesn't account for boolean OR. If you want to do that, you'd still need to write #expect(received == expected1 || received == expected2). In my opinion, that's a pretty strong test smell: being an indicator that you're writing way too vague of an expectation.

For a slightly more concrete example, how about something for someone who wants to DRY up a bunch of comparisons into a single test helper. For simplicity's sake, let's say the just want to verify that every array contains 10 items (and, realistically, this would be a bit more involved, but go with me here):

func validateArray<T>(_ array: Array<T>, sourceLocation: SourceLocation = #Testing::sourceLocation) {
  withIssueCapturing {
    // Using `#expect` specifically so that the array.count == 10 expression is contained in the issue. i.e. we want `issue.kind = .expectationFailed`
    #expect(array.count == 10)
  }.map { issue in
    var issue = issue
    issue.sourceLocation = sourceLocation
    issue.comments = ["some helpful information about why the array must contain 10 items"]
    issue.record()
  }
}

In this case, yes, we would be checking the changed sourceLocation, the single comment, and that issue.kind is expectationFailed. Using the expectation DSL makes this easier to read (at least, checking sourceLocation and the comment), and easier to debug (though, again, depends on how you validate the issue.kind; I would love to able to write #expect(case .expectationFailed = issue.kind).

In the rare cases where your parameterized test expects a dynamic amount of issues, you can use withIssueCapturing and assert on the captured issues directly. Or split these up into separate tests? It is possible to DRY things up too much, which is a cause of test smells.

This might be on me with how I phrased "each matcher must match 1-1 with a recorded issue". The intention is perhaps better expressed as "There is at least 1 matcher for each recorded issue, and never an unmatched matcher" (which also needs wordsmithing). Regardless, I never meant for order to matter when it comes to assigning issues & matchers (which certainly would've made writing that validator easier, but even my early prototype didn't assume order). What I implemented does account for not only the lack of order, but the fact that matchers will almost always not be written comprehensively enough to match only a specific issue. For example, this test currently passes on my branch:

@Test func `multiple issues with overlapping comments`() async {
  withExpectedIssue {
    // hello
    #expect(Bool(false))
    // world
    #expect(Bool(false))
    // hello
    // world
    #expect(Bool(false))
  } matching: { issue in
    #expect(issue.comments == ["// hello", "// world"])
  } _: { issue in
    #expect(issue.comments.last == "// hello")
  } _: { issue in
    #expect(issue.comments.first == "// world")
  }
}

The last issue recorded matches all 3 matchers, but really is intended for the first matcher. The other two matchers are not nearly as comprehensive as they should be, given that they each match 2 issues. But still, the validator can prove that there is a solution here where each recorded issue has it's own matcher, so no issues are reported.

1 Like