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

How to test a function fn(&str, &str) -> bool? #75

Closed
febeling opened this issue Apr 26, 2015 · 2 comments
Closed

How to test a function fn(&str, &str) -> bool? #75

febeling opened this issue Apr 26, 2015 · 2 comments
Labels

Comments

@febeling
Copy link

This is a question issue, and I hope that's an acceptable use in this project.

I try to use quickcheck to write tests for function accepting two strings. I haven't been able to adapt the example test to my use case. This is what I have. Is quickcheck able to provide random parameters for strings (or &strs)?

extern crate quickcheck;
// at least difference of the sizes of a and b
#[test]
fn prop_test_() {
    use quickcheck::quickcheck;

    fn at_least_size_difference(a: &str, b: &str) -> bool {
        let size_a = a.chars().count() as i32;
        let size_b = b.chars().count() as i32;
        let diff = (size_a - size_b).abs();

        edit_distance::edit_distance(a, b) > diff;
    }

    quickcheck(at_least_size_difference as fn(a: &str, b: &str) -> bool);
}
@BurntSushi
Copy link
Owner

No. QuickCheck doesn't generate values with type &str. It is much more convenient to limit QuickCheck to owned values (or non-borrowed types that implement Copy, like ints). I don't think it's possible to write a useful implementation of Arbitrary for &str (because it needs to be able to manipulate the strings to do shrinking).

With that said, given your code here, I don't see any reason why you can't use String. If you have a String, then you can get an &str. It will cost you an allocation, but it's usually not a huge deal in this context.

I think if you s/&str/String and change edit_distance(a, b) to edit_distance(&a, &b), then it should work (assuming edit_distance accepts two values with type &str).

@febeling
Copy link
Author

Thank you! It makes sense the way you explain it, and I'm just in the process of forming an idea what the difference between &str and String entails. With this change it works beautifully.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

2 participants