Skip to content

Avoid using withExtendedLifetime in unit tests - #405

Open
calda wants to merge 1 commit into
masterfrom
cal--redundantExtendedLifetime
Open

Avoid using withExtendedLifetime in unit tests#405
calda wants to merge 1 commit into
masterfrom
cal--redundantExtendedLifetime

Conversation

@calda

@calda calda commented Sep 1, 2026

Copy link
Copy Markdown
Member

Summary

This PR proposes a rule to avoid using withExtendedLifetime in unit tests.

Reasoning

We found internally that none of the 400+ uses of withExtendedLifetime in our test suite actually affect runtime behavior since a variable declared in a function scope is never deallocated before the end of that scope.

// WRONG
@Test
func `telescope tracks target`() {
  let observatory = Observatory()
  let telescope = observatory.veryLargeTelescope()

  telescope.track(.mars)
  #expect(telescope.isTracking)

  // Ensure the observatory isn't deallocated before we finish our observation
  withExtendedLifetime(observatory) { }
}

// RIGHT
@Test
func `telescope tracks target`() {
  let observatory = Observatory()
  let telescope = observatory.veryLargeTelescope()

  telescope.track(.mars)
  #expect(telescope.isTracking)
}

However, it is sometimes used to suppress an "unused variable" warning. This sort of usage is fine:

// ALSO RIGHT. Without `withExtendedLifetime`, `cancellable` would cause an "unused variable" warning.
@Test
func `telescope publishes target updates`() {
  let telescope = Telescope()
  var publishedTarget: Planet?
  let cancellable = telescope.targetPublisher.sink { publishedTarget = $0 }

  telescope.track(.mars)
  #expect(publishedTarget == .mars)

  withExtendedLifetime(cancellable) { }
}

@calda
calda force-pushed the cal--redundantExtendedLifetime branch from 11979bf to 902bdcd Compare September 3, 2026 19:06
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant