1 // Copyright 2014 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.
5 #import "ios/web/public/test/http_server.h"
7 #import <Foundation/Foundation.h>
11 #import "base/ios/ios_util.h"
12 #import "base/mac/scoped_nsobject.h"
13 #include "base/memory/ref_counted.h"
14 #include "base/memory/scoped_ptr.h"
15 #include "base/strings/sys_string_conversions.h"
16 #import "base/test/ios/wait_util.h"
17 #include "ios/web/public/test/response_providers/data_response_provider.h"
18 #include "net/http/http_response_headers.h"
19 #include "testing/gtest/include/gtest/gtest.h"
20 #include "testing/gtest_mac.h"
24 // A response provider that returns a simple string for all requests. Used for
26 class TestResponseProvider : public web::DataResponseProvider {
28 bool CanHandleRequest(const Request& request) override {
32 void GetResponseHeadersAndBody(
33 const Request& request,
34 scoped_refptr<net::HttpResponseHeaders>* headers,
35 std::string* response_body) override {
36 *headers = GetDefaultResponseHeaders();
37 *response_body = response_body_;
39 // The string that is returned in the response body.
40 std::string response_body_;
45 // Tests that a web::test::HttpServer can be started and can send and receive
46 // requests and response from |TestResponseProvider|
47 TEST(HTTPServer, StartAndInterfaceWithResponseProvider) {
48 // Disabled on iOS 9 as it fails with App Transport Security error.
49 // Tracked by http://crbug.com/516600 issue.
50 if (base::ios::IsRunningOnIOS9OrLater())
53 scoped_ptr<TestResponseProvider> provider(new TestResponseProvider());
54 const std::string kHelloWorld = "Hello World";
55 provider->response_body_ = kHelloWorld;
56 web::test::HttpServer& server = web::test::HttpServer::GetSharedInstance();
57 const NSUInteger kPort = 8080;
58 server.StartOnPort(kPort);
59 EXPECT_TRUE(server.IsRunning());
60 server.AddResponseProvider(provider.release());
63 [NSString stringWithFormat:@"http://localhost:%@/samp", @(kPort)];
64 __block base::scoped_nsobject<NSString> evaluation_result;
65 id completion_handler =
66 ^(NSData* data, NSURLResponse* response, NSError* error) {
67 evaluation_result.reset([[NSString alloc]
68 initWithData:data encoding:NSUTF8StringEncoding]);
70 NSURLSessionDataTask* data_task =
71 [[NSURLSession sharedSession] dataTaskWithURL:[NSURL URLWithString:url]
72 completionHandler:completion_handler];
74 base::test::ios::WaitUntilCondition(^bool() {
75 return evaluation_result;
77 EXPECT_NSEQ(evaluation_result, base::SysUTF8ToNSString(kHelloWorld));
79 EXPECT_FALSE(server.IsRunning());