1 /*
2 * Copyright (c) 2002-2025 Gargoyle Software Inc.
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 * https://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15 package org.htmlunit.doc;
16
17 import java.net.URL;
18 import java.util.Map;
19
20 import org.htmlunit.MockWebConnection;
21 import org.htmlunit.WebClient;
22 import org.htmlunit.WebServerTestCase;
23 import org.junit.jupiter.api.Test;
24
25 /**
26 * Tests for the sample code from the documentation to make sure
27 * we adapt the docu or do not break the samples.
28 *
29 * @author Ronald Brill
30 */
31 public class StorageHolderTest extends WebServerTestCase {
32
33 /**
34 * @throws Exception if an error occurs
35 */
36 @Test
37 public void sessionStorage() throws Exception {
38 final MockWebConnection conn = getMockWebConnection();
39 conn.setDefaultResponse("<script>sessionStorage.setItem('myNewKey', 'myNewData');</script>");
40
41 startWebServer(conn);
42 final URL url = URL_FIRST;
43
44 try (WebClient webClient = new WebClient()) {
45
46 // get the session storage for the current window
47 final Map<String, String> sessionStorage =
48 webClient.getStorageHolder().getSessionStorage(webClient.getCurrentWindow());
49
50 // place some data in the session storage
51 sessionStorage.put("myKey", "myData");
52
53 // load the page that consumes the session storage data
54 webClient.getPage(url);
55
56 // make sure the new data are in
57 assertEquals("myNewData", sessionStorage.get("myNewKey"));
58 }
59 }
60
61 /**
62 * @throws Exception if an error occurs
63 */
64 @Test
65 public void localStorage() throws Exception {
66 final MockWebConnection conn = getMockWebConnection();
67 conn.setDefaultResponse("<script>localStorage.setItem('myNewKey', 'myNewData');</script>");
68
69 startWebServer(conn);
70 final URL url = URL_FIRST;
71
72 try (WebClient webClient = new WebClient()) {
73
74 // get the local storage for the url
75 // the url has to match the page url you will load later
76 final Map<String, String> localStorage = webClient.getStorageHolder().getLocalStorage(url);
77
78 // place some data in the session storage
79 localStorage.put("myKey", "myData");
80
81 // load the page that consumes the session storage data
82 webClient.getPage(url);
83
84 // make sure the new data are in
85 assertEquals("myNewData", localStorage.get("myNewKey"));
86 }
87 }
88 }