[GLIB] Use GUniquePtr instead of GOwnPtr
[WebKit-https.git] / Tools / TestWebKitAPI / Tests / WebKit2Gtk / TestWebKitWebContext.cpp
1 /*
2  * Copyright (C) 2011 Igalia S.L.
3  *
4  * This library is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU Lesser General Public
6  * License as published by the Free Software Foundation; either
7  * version 2,1 of the License, or (at your option) any later version.
8  *
9  * This library is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12  * Library General Public License for more details.
13  *
14  * You should have received a copy of the GNU Library General Public License
15  * along with this library; see the file COPYING.LIB.  If not, write to
16  * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
17  * Boston, MA 02110-1301, USA.
18  */
19
20 #include "config.h"
21
22 #include "LoadTrackingTest.h"
23 #include "WebKitTestServer.h"
24 #include <gtk/gtk.h>
25 #include <webkit2/webkit2.h>
26 #include <wtf/HashMap.h>
27 #include <wtf/gobject/GRefPtr.h>
28 #include <wtf/gobject/GUniquePtr.h>
29 #include <wtf/text/StringHash.h>
30
31 static WebKitTestServer* kServer;
32
33 static void testWebContextDefault(Test* test, gconstpointer)
34 {
35     // Check there's a single instance of the default web context.
36     g_assert(webkit_web_context_get_default() == webkit_web_context_get_default());
37 }
38
39 class PluginsTest: public Test {
40 public:
41     MAKE_GLIB_TEST_FIXTURE(PluginsTest);
42
43     PluginsTest()
44         : m_context(webkit_web_context_get_default())
45         , m_mainLoop(g_main_loop_new(0, TRUE))
46         , m_plugins(0)
47     {
48         webkit_web_context_set_additional_plugins_directory(m_context, WEBKIT_TEST_PLUGIN_DIR);
49     }
50
51     ~PluginsTest()
52     {
53         g_main_loop_unref(m_mainLoop);
54         g_list_free_full(m_plugins, g_object_unref);
55     }
56
57     static void getPluginsAsyncReadyCallback(GObject*, GAsyncResult* result, PluginsTest* test)
58     {
59         test->m_plugins = webkit_web_context_get_plugins_finish(test->m_context, result, 0);
60         g_main_loop_quit(test->m_mainLoop);
61     }
62
63     GList* getPlugins()
64     {
65         g_list_free_full(m_plugins, g_object_unref);
66         webkit_web_context_get_plugins(m_context, 0, reinterpret_cast<GAsyncReadyCallback>(getPluginsAsyncReadyCallback), this);
67         g_main_loop_run(m_mainLoop);
68         return m_plugins;
69     }
70
71     WebKitWebContext* m_context;
72     GMainLoop* m_mainLoop;
73     GList* m_plugins;
74 };
75
76 static void testWebContextGetPlugins(PluginsTest* test, gconstpointer)
77 {
78     GList* plugins = test->getPlugins();
79     g_assert(plugins);
80
81     GRefPtr<WebKitPlugin> testPlugin;
82     for (GList* item = plugins; item; item = g_list_next(item)) {
83         WebKitPlugin* plugin = WEBKIT_PLUGIN(item->data);
84         test->assertObjectIsDeletedWhenTestFinishes(G_OBJECT(plugin));
85         if (!g_strcmp0(webkit_plugin_get_name(plugin), "WebKit Test PlugIn")) {
86             testPlugin = plugin;
87             break;
88         }
89     }
90     g_assert(WEBKIT_IS_PLUGIN(testPlugin.get()));
91
92     GUniquePtr<char> pluginPath(g_build_filename(WEBKIT_TEST_PLUGIN_DIR, "libTestNetscapePlugin.so", nullptr));
93     g_assert_cmpstr(webkit_plugin_get_path(testPlugin.get()), ==, pluginPath.get());
94     g_assert_cmpstr(webkit_plugin_get_description(testPlugin.get()), ==, "Simple Netscape┬« plug-in that handles test content for WebKit");
95     GList* mimeInfoList = webkit_plugin_get_mime_info_list(testPlugin.get());
96     g_assert(mimeInfoList);
97     g_assert_cmpuint(g_list_length(mimeInfoList), ==, 2);
98
99     WebKitMimeInfo* mimeInfo = static_cast<WebKitMimeInfo*>(mimeInfoList->data);
100     g_assert_cmpstr(webkit_mime_info_get_mime_type(mimeInfo), ==, "image/png");
101     g_assert_cmpstr(webkit_mime_info_get_description(mimeInfo), ==, "png image");
102     const gchar* const* extensions = webkit_mime_info_get_extensions(mimeInfo);
103     g_assert(extensions);
104     g_assert_cmpstr(extensions[0], ==, "png");
105
106     mimeInfoList = g_list_next(mimeInfoList);
107     mimeInfo = static_cast<WebKitMimeInfo*>(mimeInfoList->data);
108     g_assert_cmpstr(webkit_mime_info_get_mime_type(mimeInfo), ==, "application/x-webkit-test-netscape");
109     g_assert_cmpstr(webkit_mime_info_get_description(mimeInfo), ==, "test netscape content");
110     extensions = webkit_mime_info_get_extensions(mimeInfo);
111     g_assert(extensions);
112     g_assert_cmpstr(extensions[0], ==, "testnetscape");
113 }
114
115 static const char* kBarHTML = "<html><body>Bar</body></html>";
116 static const char* kEchoHTMLFormat = "<html><body>%s</body></html>";
117 static const char* errorDomain = "test";
118 static const int errorCode = 10;
119 static const char* errorMessage = "Error message.";
120
121 class URISchemeTest: public LoadTrackingTest {
122 public:
123     MAKE_GLIB_TEST_FIXTURE(URISchemeTest);
124
125     struct URISchemeHandler {
126         URISchemeHandler()
127             : replyLength(0)
128         {
129         }
130
131         URISchemeHandler(const char* reply, int replyLength, const char* mimeType)
132             : reply(reply)
133             , replyLength(replyLength)
134             , mimeType(mimeType)
135         {
136         }
137
138         CString reply;
139         int replyLength;
140         CString mimeType;
141     };
142
143     static void uriSchemeRequestCallback(WebKitURISchemeRequest* request, gpointer userData)
144     {
145         URISchemeTest* test = static_cast<URISchemeTest*>(userData);
146         test->m_uriSchemeRequest = request;
147         test->assertObjectIsDeletedWhenTestFinishes(G_OBJECT(request));
148
149         g_assert(webkit_uri_scheme_request_get_web_view(request) == test->m_webView);
150
151         GRefPtr<GInputStream> inputStream = adoptGRef(g_memory_input_stream_new());
152         test->assertObjectIsDeletedWhenTestFinishes(G_OBJECT(inputStream.get()));
153
154         const char* scheme = webkit_uri_scheme_request_get_scheme(request);
155         g_assert(scheme);
156         g_assert(test->m_handlersMap.contains(String::fromUTF8(scheme)));
157
158         if (!g_strcmp0(scheme, "error")) {
159             GUniquePtr<GError> error(g_error_new_literal(g_quark_from_string(errorDomain), errorCode, errorMessage));
160             webkit_uri_scheme_request_finish_error(request, error.get());
161             return;
162         }
163
164         const URISchemeHandler& handler = test->m_handlersMap.get(String::fromUTF8(scheme));
165
166         if (!g_strcmp0(scheme, "echo")) {
167             char* replyHTML = g_strdup_printf(handler.reply.data(), webkit_uri_scheme_request_get_path(request));
168             g_memory_input_stream_add_data(G_MEMORY_INPUT_STREAM(inputStream.get()), replyHTML, strlen(replyHTML), g_free);
169         } else if (!g_strcmp0(scheme, "closed"))
170             g_input_stream_close(inputStream.get(), 0, 0);
171         else if (!handler.reply.isNull())
172             g_memory_input_stream_add_data(G_MEMORY_INPUT_STREAM(inputStream.get()), handler.reply.data(), handler.reply.length(), 0);
173
174         webkit_uri_scheme_request_finish(request, inputStream.get(), handler.replyLength, handler.mimeType.data());
175     }
176
177     void registerURISchemeHandler(const char* scheme, const char* reply, int replyLength, const char* mimeType)
178     {
179         m_handlersMap.set(String::fromUTF8(scheme), URISchemeHandler(reply, replyLength, mimeType));
180         webkit_web_context_register_uri_scheme(webkit_web_context_get_default(), scheme, uriSchemeRequestCallback, this, 0);
181     }
182
183     GRefPtr<WebKitURISchemeRequest> m_uriSchemeRequest;
184     HashMap<String, URISchemeHandler> m_handlersMap;
185 };
186
187 static void testWebContextURIScheme(URISchemeTest* test, gconstpointer)
188 {
189     test->registerURISchemeHandler("foo", kBarHTML, strlen(kBarHTML), "text/html");
190     test->loadURI("foo:blank");
191     test->waitUntilLoadFinished();
192     size_t mainResourceDataSize = 0;
193     const char* mainResourceData = test->mainResourceData(mainResourceDataSize);
194     g_assert_cmpint(mainResourceDataSize, ==, strlen(kBarHTML));
195     g_assert(!strncmp(mainResourceData, kBarHTML, mainResourceDataSize));
196
197     test->registerURISchemeHandler("echo", kEchoHTMLFormat, -1, "text/html");
198     test->loadURI("echo:hello world");
199     test->waitUntilLoadFinished();
200     GUniquePtr<char> echoHTML(g_strdup_printf(kEchoHTMLFormat, webkit_uri_scheme_request_get_path(test->m_uriSchemeRequest.get())));
201     mainResourceDataSize = 0;
202     mainResourceData = test->mainResourceData(mainResourceDataSize);
203     g_assert_cmpint(mainResourceDataSize, ==, strlen(echoHTML.get()));
204     g_assert(!strncmp(mainResourceData, echoHTML.get(), mainResourceDataSize));
205
206     test->registerURISchemeHandler("nomime", kBarHTML, -1, 0);
207     test->m_loadEvents.clear();
208     test->loadURI("nomime:foo bar");
209     test->waitUntilLoadFinished();
210     g_assert(test->m_loadEvents.contains(LoadTrackingTest::ProvisionalLoadFailed));
211
212     test->registerURISchemeHandler("empty", 0, 0, "text/html");
213     test->m_loadEvents.clear();
214     test->loadURI("empty:nothing");
215     test->waitUntilLoadFinished();
216     g_assert(!test->m_loadEvents.contains(LoadTrackingTest::ProvisionalLoadFailed));
217     g_assert(!test->m_loadEvents.contains(LoadTrackingTest::LoadFailed));
218
219     test->registerURISchemeHandler("error", 0, 0, 0);
220     test->m_loadEvents.clear();
221     test->loadURI("error:error");
222     test->waitUntilLoadFinished();
223     g_assert(test->m_loadEvents.contains(LoadTrackingTest::ProvisionalLoadFailed));
224     g_assert(test->m_loadFailed);
225     g_assert_error(test->m_error.get(), g_quark_from_string(errorDomain), errorCode);
226     g_assert_cmpstr(test->m_error->message, ==, errorMessage);
227
228     test->registerURISchemeHandler("closed", 0, 0, 0);
229     test->m_loadEvents.clear();
230     test->loadURI("closed:input-stream");
231     test->waitUntilLoadFinished();
232     g_assert(test->m_loadEvents.contains(LoadTrackingTest::ProvisionalLoadFailed));
233     g_assert(test->m_loadFailed);
234     g_assert_error(test->m_error.get(), G_IO_ERROR, G_IO_ERROR_CLOSED);
235 }
236
237 static void testWebContextSpellChecker(Test* test, gconstpointer)
238 {
239     WebKitWebContext* webContext = webkit_web_context_get_default();
240
241     // Check what happens if no spell checking language has been set.
242     const gchar* const* currentLanguage = webkit_web_context_get_spell_checking_languages(webContext);
243     g_assert(!currentLanguage);
244
245     // Set the language to a specific one.
246     GRefPtr<GPtrArray> languages = adoptGRef(g_ptr_array_new());
247     g_ptr_array_add(languages.get(), const_cast<gpointer>(static_cast<const void*>("en_US")));
248     g_ptr_array_add(languages.get(), 0);
249     webkit_web_context_set_spell_checking_languages(webContext, reinterpret_cast<const char* const*>(languages->pdata));
250     currentLanguage = webkit_web_context_get_spell_checking_languages(webContext);
251     g_assert_cmpuint(g_strv_length(const_cast<char**>(currentLanguage)), ==, 1);
252     g_assert_cmpstr(currentLanguage[0], ==, "en_US");
253
254     // Set the language string to list of valid languages.
255     g_ptr_array_remove_index_fast(languages.get(), languages->len - 1);
256     g_ptr_array_add(languages.get(), const_cast<gpointer>(static_cast<const void*>("en_GB")));
257     g_ptr_array_add(languages.get(), 0);
258     webkit_web_context_set_spell_checking_languages(webContext, reinterpret_cast<const char* const*>(languages->pdata));
259     currentLanguage = webkit_web_context_get_spell_checking_languages(webContext);
260     g_assert_cmpuint(g_strv_length(const_cast<char**>(currentLanguage)), ==, 2);
261     g_assert_cmpstr(currentLanguage[0], ==, "en_US");
262     g_assert_cmpstr(currentLanguage[1], ==, "en_GB");
263
264     // Try passing a wrong language along with good ones.
265     g_ptr_array_remove_index_fast(languages.get(), languages->len - 1);
266     g_ptr_array_add(languages.get(), const_cast<gpointer>(static_cast<const void*>("bd_WR")));
267     g_ptr_array_add(languages.get(), 0);
268     webkit_web_context_set_spell_checking_languages(webContext, reinterpret_cast<const char* const*>(languages->pdata));
269     currentLanguage = webkit_web_context_get_spell_checking_languages(webContext);
270     g_assert_cmpuint(g_strv_length(const_cast<char**>(currentLanguage)), ==, 2);
271     g_assert_cmpstr(currentLanguage[0], ==, "en_US");
272     g_assert_cmpstr(currentLanguage[1], ==, "en_GB");
273
274     // Try passing a list with only wrong languages.
275     languages = adoptGRef(g_ptr_array_new());
276     g_ptr_array_add(languages.get(), const_cast<gpointer>(static_cast<const void*>("bd_WR")));
277     g_ptr_array_add(languages.get(), const_cast<gpointer>(static_cast<const void*>("wr_BD")));
278     g_ptr_array_add(languages.get(), 0);
279     webkit_web_context_set_spell_checking_languages(webContext, reinterpret_cast<const char* const*>(languages->pdata));
280     currentLanguage = webkit_web_context_get_spell_checking_languages(webContext);
281     g_assert(!currentLanguage);
282
283     // Check disabling and re-enabling spell checking.
284     webkit_web_context_set_spell_checking_enabled(webContext, FALSE);
285     g_assert(!webkit_web_context_get_spell_checking_enabled(webContext));
286     webkit_web_context_set_spell_checking_enabled(webContext, TRUE);
287     g_assert(webkit_web_context_get_spell_checking_enabled(webContext));
288 }
289
290 static void testWebContextLanguages(WebViewTest* test, gconstpointer)
291 {
292     static const char* expectedDefaultLanguage = "en";
293     test->loadURI(kServer->getURIForPath("/").data());
294     test->waitUntilLoadFinished();
295     size_t mainResourceDataSize = 0;
296     const char* mainResourceData = test->mainResourceData(mainResourceDataSize);
297     g_assert_cmpuint(mainResourceDataSize, ==, strlen(expectedDefaultLanguage));
298     g_assert(!strncmp(mainResourceData, expectedDefaultLanguage, mainResourceDataSize));
299
300     GRefPtr<GPtrArray> languages = adoptGRef(g_ptr_array_new());
301     g_ptr_array_add(languages.get(), const_cast<gpointer>(static_cast<const void*>("en")));
302     g_ptr_array_add(languages.get(), const_cast<gpointer>(static_cast<const void*>("ES_es")));
303     g_ptr_array_add(languages.get(), const_cast<gpointer>(static_cast<const void*>("dE")));
304     g_ptr_array_add(languages.get(), 0);
305     webkit_web_context_set_preferred_languages(webkit_web_context_get_default(), reinterpret_cast<const char* const*>(languages->pdata));
306
307     static const char* expectedLanguages = "en, es-es;q=0.90, de;q=0.80";
308     test->loadURI(kServer->getURIForPath("/").data());
309     test->waitUntilLoadFinished();
310     mainResourceDataSize = 0;
311     mainResourceData = test->mainResourceData(mainResourceDataSize);
312     g_assert_cmpuint(mainResourceDataSize, ==, strlen(expectedLanguages));
313     g_assert(!strncmp(mainResourceData, expectedLanguages, mainResourceDataSize));
314 }
315
316 static void serverCallback(SoupServer* server, SoupMessage* message, const char* path, GHashTable*, SoupClientContext*, gpointer)
317 {
318     if (message->method != SOUP_METHOD_GET) {
319         soup_message_set_status(message, SOUP_STATUS_NOT_IMPLEMENTED);
320         return;
321     }
322
323     if (g_str_equal(path, "/")) {
324         const char* acceptLanguage = soup_message_headers_get_one(message->request_headers, "Accept-Language");
325         soup_message_set_status(message, SOUP_STATUS_OK);
326         soup_message_body_append(message->response_body, SOUP_MEMORY_COPY, acceptLanguage, strlen(acceptLanguage));
327         soup_message_body_complete(message->response_body);
328     } else
329         soup_message_set_status(message, SOUP_STATUS_NOT_FOUND);
330 }
331
332 class SecurityPolicyTest: public Test {
333 public:
334     MAKE_GLIB_TEST_FIXTURE(SecurityPolicyTest);
335
336     enum SecurityPolicy {
337         Local = 1 << 1,
338         NoAccess = 1 << 2,
339         DisplayIsolated = 1 << 3,
340         Secure = 1 << 4,
341         CORSEnabled = 1 << 5,
342         EmptyDocument = 1 << 6
343     };
344
345     SecurityPolicyTest()
346         : m_manager(webkit_web_context_get_security_manager(webkit_web_context_get_default()))
347     {
348     }
349
350     void verifyThatSchemeMatchesPolicy(const char* scheme, unsigned policy)
351     {
352         if (policy & Local)
353             g_assert(webkit_security_manager_uri_scheme_is_local(m_manager, scheme));
354         else
355             g_assert(!webkit_security_manager_uri_scheme_is_local(m_manager, scheme));
356         if (policy & NoAccess)
357             g_assert(webkit_security_manager_uri_scheme_is_no_access(m_manager, scheme));
358         else
359             g_assert(!webkit_security_manager_uri_scheme_is_no_access(m_manager, scheme));
360         if (policy & DisplayIsolated)
361             g_assert(webkit_security_manager_uri_scheme_is_display_isolated(m_manager, scheme));
362         else
363             g_assert(!webkit_security_manager_uri_scheme_is_display_isolated(m_manager, scheme));
364         if (policy & Secure)
365             g_assert(webkit_security_manager_uri_scheme_is_secure(m_manager, scheme));
366         else
367             g_assert(!webkit_security_manager_uri_scheme_is_secure(m_manager, scheme));
368         if (policy & CORSEnabled)
369             g_assert(webkit_security_manager_uri_scheme_is_cors_enabled(m_manager, scheme));
370         else
371             g_assert(!webkit_security_manager_uri_scheme_is_cors_enabled(m_manager, scheme));
372         if (policy & EmptyDocument)
373             g_assert(webkit_security_manager_uri_scheme_is_empty_document(m_manager, scheme));
374         else
375             g_assert(!webkit_security_manager_uri_scheme_is_empty_document(m_manager, scheme));
376     }
377
378     WebKitSecurityManager* m_manager;
379 };
380
381 static void testWebContextSecurityPolicy(SecurityPolicyTest* test, gconstpointer)
382 {
383     // VerifyThatSchemeMatchesPolicy default policy for well known schemes.
384     test->verifyThatSchemeMatchesPolicy("http", SecurityPolicyTest::CORSEnabled);
385     test->verifyThatSchemeMatchesPolicy("https", SecurityPolicyTest::CORSEnabled | SecurityPolicyTest::Secure);
386     test->verifyThatSchemeMatchesPolicy("file", SecurityPolicyTest::Local);
387     test->verifyThatSchemeMatchesPolicy("data", SecurityPolicyTest::NoAccess | SecurityPolicyTest::Secure);
388     test->verifyThatSchemeMatchesPolicy("about", SecurityPolicyTest::NoAccess | SecurityPolicyTest::Secure | SecurityPolicyTest::EmptyDocument);
389
390     // Custom scheme.
391     test->verifyThatSchemeMatchesPolicy("foo", 0);
392
393     webkit_security_manager_register_uri_scheme_as_local(test->m_manager, "foo");
394     test->verifyThatSchemeMatchesPolicy("foo", SecurityPolicyTest::Local);
395     webkit_security_manager_register_uri_scheme_as_no_access(test->m_manager, "foo");
396     test->verifyThatSchemeMatchesPolicy("foo", SecurityPolicyTest::Local | SecurityPolicyTest::NoAccess);
397     webkit_security_manager_register_uri_scheme_as_display_isolated(test->m_manager, "foo");
398     test->verifyThatSchemeMatchesPolicy("foo", SecurityPolicyTest::Local | SecurityPolicyTest::NoAccess | SecurityPolicyTest::DisplayIsolated);
399     webkit_security_manager_register_uri_scheme_as_secure(test->m_manager, "foo");
400     test->verifyThatSchemeMatchesPolicy("foo", SecurityPolicyTest::Local | SecurityPolicyTest::NoAccess | SecurityPolicyTest::DisplayIsolated | SecurityPolicyTest::Secure);
401     webkit_security_manager_register_uri_scheme_as_cors_enabled(test->m_manager, "foo");
402     test->verifyThatSchemeMatchesPolicy("foo", SecurityPolicyTest::Local | SecurityPolicyTest::NoAccess | SecurityPolicyTest::DisplayIsolated | SecurityPolicyTest::Secure
403         | SecurityPolicyTest::CORSEnabled);
404     webkit_security_manager_register_uri_scheme_as_empty_document(test->m_manager, "foo");
405     test->verifyThatSchemeMatchesPolicy("foo", SecurityPolicyTest::Local | SecurityPolicyTest::NoAccess | SecurityPolicyTest::DisplayIsolated | SecurityPolicyTest::Secure
406         | SecurityPolicyTest::CORSEnabled | SecurityPolicyTest::EmptyDocument);
407 }
408
409 void beforeAll()
410 {
411     kServer = new WebKitTestServer();
412     kServer->run(serverCallback);
413
414     Test::add("WebKitWebContext", "default-context", testWebContextDefault);
415     PluginsTest::add("WebKitWebContext", "get-plugins", testWebContextGetPlugins);
416     URISchemeTest::add("WebKitWebContext", "uri-scheme", testWebContextURIScheme);
417     Test::add("WebKitWebContext", "spell-checker", testWebContextSpellChecker);
418     WebViewTest::add("WebKitWebContext", "languages", testWebContextLanguages);
419     SecurityPolicyTest::add("WebKitSecurityManager", "security-policy", testWebContextSecurityPolicy);
420 }
421
422 void afterAll()
423 {
424     delete kServer;
425 }