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/mac/scoped_nsobject.h"
12 #include "base/memory/ref_counted.h"
13 #include "base/memory/scoped_ptr.h"
14 #include "base/strings/sys_string_conversions.h"
15 #import "base/test/ios/wait_util.h"
16 #include "ios/web/public/test/response_providers/data_response_provider.h"
17 #include "net/http/http_response_headers.h"
18 #include "testing/gtest/include/gtest/gtest.h"
19 #include "testing/gtest_mac.h"
23 // A response provider that returns a simple string for all requests. Used for
25 class TestResponseProvider : public web::DataResponseProvider {
27 bool CanHandleRequest(const Request& request) override {
31 void GetResponseHeadersAndBody(
32 const Request& request,
33 scoped_refptr<net::HttpResponseHeaders>* headers,
34 std::string* response_body) override {
35 *headers = GetDefaultResponseHeaders();
36 *response_body = response_body_;
38 // The string that is returned in the response body.
39 std::string response_body_;
44 // Tests that a web::test::HttpServer can be started and can send and receive
45 // requests and response from |TestResponseProvider|
46 TEST(HTTPServer, StartAndInterfaceWithResponseProvider) {
47 scoped_ptr<TestResponseProvider> provider(new TestResponseProvider());
48 const std::string kHelloWorld = "Hello World";
49 provider->response_body_ = kHelloWorld;
50 web::test::HttpServer& server = web::test::HttpServer::GetSharedInstance();
51 const NSUInteger kPort = 8080;
52 server.StartOnPort(kPort);
53 EXPECT_TRUE(server.IsRunning());
54 server.AddResponseProvider(provider.release());
57 [NSString stringWithFormat:@"http://localhost:%@/samp", @(kPort)];
58 __block base::scoped_nsobject<NSString> evaluation_result;
59 id completion_handler =
60 ^(NSData* data, NSURLResponse* response, NSError* error) {
61 evaluation_result.reset([[NSString alloc]
62 initWithData:data encoding:NSUTF8StringEncoding]);
64 NSURLSessionDataTask* data_task =
65 [[NSURLSession sharedSession] dataTaskWithURL:[NSURL URLWithString:url]
66 completionHandler:completion_handler];
68 base::test::ios::WaitUntilCondition(^bool() {
69 return evaluation_result;
71 EXPECT_NSEQ(evaluation_result, base::SysUTF8ToNSString(kHelloWorld));
73 EXPECT_FALSE(server.IsRunning());