Skip to content
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

Parameterless ContainSingle() evaluates IEnumerables twice #1752

Closed
bert2 opened this issue Nov 30, 2021 · 3 comments · Fixed by #1753
Closed

Parameterless ContainSingle() evaluates IEnumerables twice #1752

bert2 opened this issue Nov 30, 2021 · 3 comments · Fixed by #1753

Comments

@bert2
Copy link
Contributor

bert2 commented Nov 30, 2021

Description

The "parameterless" variant of ContainSingle() (without a predicate) evaluates IEnumerables twice. This means any side-effects in the enumerable chain are executed twice which might lead to unexpected behavior.

Complete minimal example reproducing the issue

https://dotnetfiddle.net/SFGRnc

using System.Collections.Generic;
using System.Linq;
using FluentAssertions;

var d = new Dictionary<int, int>();
var xs = new[] { 1 }
    .Select(x => {
        d.Add(x, x); // crashes if executed twice
        return x;
    });

xs.Should().ContainSingle(); // crashes
//xs.Should().ContainSingle(_ => true); // does not crash

Expected behavior:

xs.Should().ContainSingle(); should not crash.

Actual behavior:

xs.Should().ContainSingle(); crashes.

Versions

  • FluentAssertions 6.2.0
  • .NET 6.0

Additional Information

The problem is that ContainSingle() uses Count() here and also SingleOrDefault() here without materializing the enumerable first.

The variant taking a predicate does materialize the enumerable first here.

@dennisdoomen
Copy link
Member

Thank you for reporting this. We would most definitely welcome a PR.

@bert2
Copy link
Contributor Author

bert2 commented Nov 30, 2021

@dennisdoomen Yep, considered doing a PR but wasn't sure when I'd find the time to. Might be tomorrow or next week. So I wanted to report it at least.

@dennisdoomen
Copy link
Member

No worries. Thanks for helping out.

@jnyrup jnyrup linked a pull request Dec 1, 2021 that will close this issue
5 tasks
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging a pull request may close this issue.

2 participants