Skip to content

Fix state sharing bug in .dependency(_:_:) trait #309

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Conversation

TimHendricksenDD
Copy link

When the .dependency(_:_:) function is used with a reference type to override the dependency for a test suite, tests can inadvertently share state because the same instance is used for each test:

@Suite(.serialized, .dependency(\.classClient, ClassClient()))
struct Example {
  @Test
  func test1() {
    @Dependency(\.classClient) var client
    client.count += 1
    #expect(client.count == 1)
  }

  @Test
  func test2() {
    @Dependency(\.classClient) var client
    client.count += 1
    #expect(client.count == 1) // 🛑 Expectation failed: (client.count → 2) == 1
  }
}

To fix this, this PR changes the value argument to be an @autoclosure so that a new instance can be created for each test. Let me know if there's an alternate solution that would be better!

Copy link
Member

@stephencelis stephencelis left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good catch, thanks!

@TimHendricksenDD
Copy link
Author

Fixed in #314

@TimHendricksenDD TimHendricksenDD deleted the fix-state-sharing-bug-in-dependency-trait branch December 5, 2024 22:35
@stephencelis
Copy link
Member

@TimHendricksenDD Sorry that we lost track of this fix and ended up reimplementing! Brandon and I have been traveling and it's been harder to keep track of everything in flight. Thanks for taking the time to dig into the problem and submit a patch all the same.

@TimHendricksenDD
Copy link
Author

That's ok - thanks for following up!

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.

2 participants