1- /// Finds the first bucket which starts with the specified string
1+ use aw_models:: Bucket ;
2+
3+ /// Finds the first bucket which starts with the specified string, and optionally matches a
4+ /// hostname.
25pub fn find_bucket < ' a > (
36 bucket_filter : & str ,
4- bucketnames : impl IntoIterator < Item = & ' a String > ,
7+ hostname_filter : & Option < String > ,
8+ buckets : impl IntoIterator < Item = & ' a Bucket > ,
59) -> Option < String > {
6- for bucketname in bucketnames {
7- if bucketname. starts_with ( bucket_filter) {
8- return Some ( bucketname. to_string ( ) ) ;
10+ for bucket in buckets {
11+ if bucket. id . starts_with ( bucket_filter) {
12+ if let Some ( hostname) = hostname_filter {
13+ if hostname == & bucket. hostname {
14+ return Some ( bucket. id . to_string ( ) ) ;
15+ }
16+ } else {
17+ return Some ( bucket. id . to_string ( ) ) ;
18+ }
919 }
1020 }
1121 None
@@ -14,20 +24,46 @@ pub fn find_bucket<'a>(
1424#[ cfg( test) ]
1525mod tests {
1626 use super :: find_bucket;
27+ use aw_models:: Bucket ;
28+ use aw_models:: BucketMetadata ;
1729
1830 #[ test]
1931 fn test_find_bucket ( ) {
2032 let expected_bucketname = "aw-datastore-test_test-host" . to_string ( ) ;
21- let bucketnames = vec ! [
22- "no match" . to_string( ) ,
23- expected_bucketname. clone( ) ,
24- "no match 2" . to_string( ) ,
25- ] ;
26- let res = find_bucket ( "aw-datastore-test" , & bucketnames) ;
33+ let expected_hostname = "testhost" . to_string ( ) ;
34+ let b1 = Bucket {
35+ bid : None ,
36+ id : "no match" . to_string ( ) ,
37+ _type : "type" . to_string ( ) ,
38+ hostname : expected_hostname. clone ( ) ,
39+ client : "testclient" . to_string ( ) ,
40+ created : None ,
41+ data : json_map ! { } ,
42+ metadata : BucketMetadata :: default ( ) ,
43+ events : None ,
44+ last_updated : None ,
45+ } ;
46+ let mut b2 = b1. clone ( ) ;
47+ b2. id = expected_bucketname. clone ( ) ;
48+ let b3 = b1. clone ( ) ;
49+
50+ let buckets = vec ! [ b1. clone( ) , b2. clone( ) , b3. clone( ) ] ;
51+
52+ // Check that it correctly finds bucket
53+ let res = find_bucket ( "aw-datastore-test" , & Some ( "testhost" . to_string ( ) ) , & buckets) ;
2754 assert_eq ! ( res, Some ( expected_bucketname) ) ;
2855
29- let bucketnames = vec ! [ "no match" . to_string( ) , "no match 2" . to_string( ) ] ;
30- let res = find_bucket ( "aw-datastore-test" , & bucketnames) ;
56+ // Check that it doesn't find a bucket for an unavailable hostname
57+ let res = find_bucket (
58+ "aw-datastore-test" ,
59+ & Some ( "unavailablehost" . to_string ( ) ) ,
60+ & buckets,
61+ ) ;
62+ assert_eq ! ( res, None ) ;
63+
64+ // Check that it doesn't find a bucket for any hostname
65+ let buckets = vec ! [ b1, b3] ;
66+ let res = find_bucket ( "aw-datastore-test" , & None , & buckets) ;
3167 assert_eq ! ( res, None ) ;
3268 }
3369}
0 commit comments