stub_url_checker.cc 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. // Copyright 2018 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. #include "components/safe_search_api/stub_url_checker.h"
  5. #include <utility>
  6. #include "base/json/json_writer.h"
  7. #include "base/values.h"
  8. #include "components/safe_search_api/safe_search/safe_search_url_checker_client.h"
  9. #include "components/safe_search_api/url_checker.h"
  10. #include "net/traffic_annotation/network_traffic_annotation_test_helper.h"
  11. #include "services/network/public/cpp/shared_url_loader_factory.h"
  12. #include "services/network/public/cpp/weak_wrapper_shared_url_loader_factory.h"
  13. #include "services/network/public/mojom/url_response_head.mojom.h"
  14. #include "url/gurl.h"
  15. namespace safe_search_api {
  16. namespace {
  17. constexpr char kSafeSearchApiUrl[] =
  18. "https://safesearch.googleapis.com/v1:classify";
  19. std::string BuildResponse(bool is_porn) {
  20. base::Value::Dict dict;
  21. base::Value::Dict classification_dict;
  22. if (is_porn)
  23. classification_dict.Set("pornography", is_porn);
  24. base::Value::List classifications_list;
  25. classifications_list.Append(std::move(classification_dict));
  26. dict.Set("classifications", std::move(classifications_list));
  27. std::string result;
  28. base::JSONWriter::Write(dict, &result);
  29. return result;
  30. }
  31. } // namespace
  32. StubURLChecker::StubURLChecker()
  33. : test_shared_loader_factory_(
  34. base::MakeRefCounted<network::WeakWrapperSharedURLLoaderFactory>(
  35. &test_url_loader_factory_)) {}
  36. StubURLChecker::~StubURLChecker() = default;
  37. std::unique_ptr<URLChecker> StubURLChecker::BuildURLChecker(size_t cache_size) {
  38. return std::make_unique<URLChecker>(
  39. std::make_unique<SafeSearchURLCheckerClient>(
  40. test_shared_loader_factory_, TRAFFIC_ANNOTATION_FOR_TESTS),
  41. cache_size);
  42. }
  43. void StubURLChecker::SetUpValidResponse(bool is_porn) {
  44. SetUpResponse(net::OK, BuildResponse(is_porn));
  45. }
  46. void StubURLChecker::SetUpFailedResponse() {
  47. SetUpResponse(net::ERR_ABORTED, std::string());
  48. }
  49. void StubURLChecker::ClearResponses() {
  50. test_url_loader_factory_.ClearResponses();
  51. }
  52. void StubURLChecker::SetUpResponse(net::Error error,
  53. const std::string& response) {
  54. network::URLLoaderCompletionStatus status(error);
  55. status.decoded_body_length = response.size();
  56. test_url_loader_factory_.AddResponse(GURL(kSafeSearchApiUrl),
  57. network::mojom::URLResponseHead::New(),
  58. response, status);
  59. }
  60. } // namespace safe_search_api