# Copyright (c) Microsoft Corporation.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import pytest


def test_should_capture_local_storage(context, is_webkit, is_win):
    if is_webkit and is_win:
        pytest.skip()
    page1 = context.newPage()
    page1.route("**/*", lambda route: route.fulfill(body="<html></html>"))
    page1.goto("https://www.example.com")
    page1.evaluate("localStorage['name1'] = 'value1'")
    page1.goto("https://www.domain.com")
    page1.evaluate("localStorage['name2'] = 'value2'")

    state = context.storageState()
    origins = state["origins"]
    assert len(origins) == 2
    assert origins[0] == {
        "origin": "https://www.example.com",
        "localStorage": [{"name": "name1", "value": "value1"}],
    }
    assert origins[1] == {
        "origin": "https://www.domain.com",
        "localStorage": [{"name": "name2", "value": "value2"}],
    }


def test_should_set_local_storage(browser, is_webkit, is_win):
    if is_webkit and is_win:
        pytest.skip()
    context = browser.newContext(
        storageState={
            "origins": [
                {
                    "origin": "https://www.example.com",
                    "localStorage": [{"name": "name1", "value": "value1"}],
                }
            ]
        }
    )

    page = context.newPage()
    page.route("**/*", lambda route: route.fulfill(body="<html></html>"))
    page.goto("https://www.example.com")
    local_storage = page.evaluate("window.localStorage")
    assert local_storage == {"name1": "value1"}
    context.close()
