1 // Copyright 2020 The Chromium Authors. All rights reserved. 2 // Use of this source code is governed by a BSD-style license that can be 3 // found in the LICENSE file. 4 5 #ifndef CONTENT_PUBLIC_TEST_URL_LOADER_MONITOR_H_ 6 #define CONTENT_PUBLIC_TEST_URL_LOADER_MONITOR_H_ 7 8 #include <map> 9 #include <memory> 10 #include <set> 11 12 #include "base/optional.h" 13 #include "base/run_loop.h" 14 #include "base/synchronization/lock.h" 15 #include "base/thread_annotations.h" 16 #include "content/public/test/url_loader_interceptor.h" 17 #include "services/network/public/cpp/resource_request.h" 18 #include "url/gurl.h" 19 20 namespace base { 21 class RunLoop; 22 } 23 24 namespace content { 25 26 // Helper class to monitor parameters passed to URLLoaderFactory calls for 27 // tests. Records parameters of most recent request for each requested URL. 28 // URLLoaderMonitor starts watching requested URLs as soon as it's constructed. 29 class URLLoaderMonitor { 30 public: 31 // If |urls_to_wait_for| to non-null, WaitForUrls() may be invoked once to 32 // wait for the specified URLs to all be observed. 33 explicit URLLoaderMonitor(std::set<GURL> urls_to_wait_for = {}); 34 URLLoaderMonitor(const URLLoaderMonitor&) = delete; 35 URLLoaderMonitor& operator=(const URLLoaderMonitor&) = delete; 36 ~URLLoaderMonitor(); 37 38 // Returns the network::ResourceRequest for the most recently observed request 39 // to |url|. If no such request has been observed, returns nullptr. 40 base::Optional<network::ResourceRequest> GetRequestInfo(const GURL& url); 41 42 // Waits for the URLs passed in to the constructor to all be observers. All 43 // URLs observed after the constructor is invoked are counted. 44 void WaitForUrls(); 45 46 private: 47 bool OnRequest(content::URLLoaderInterceptor::RequestParams* params); 48 49 // This is needed to guard access to |resource_request_map_| and 50 // |urls_to_wait_for_|, as content::URLLoaderInterceptor can invoke its 51 // callback on both the UI and IO threads. 52 base::Lock lock_; 53 std::map<GURL, network::ResourceRequest> GUARDED_BY(lock_) 54 resource_request_map_; 55 std::set<GURL> GUARDED_BY(lock_) urls_to_wait_for_; 56 57 base::RunLoop run_loop_; 58 59 std::unique_ptr<URLLoaderInterceptor> interceptor_; 60 }; 61 62 } // namespace content 63 64 #endif // CONTENT_PUBLIC_TEST_URL_LOADER_MONITOR_H_ 65