author Ziran Sun <zsun@igalia.com>
Mon, 17 Feb 2020 17:03:37 +0000
changeset 514510 06705ec6ae73173f1eede4bc59f5311cad6a9a89
parent 423755 b9f5d65674842ca120cf63bfc538f3180006ba9b
child 563366 dbf0eabb4395b0b8fc876012d056fb38a664e7ad
permissions -rw-r--r--
Bug 1615898 [wpt PR 21822] - Iterating over dictionary's items with six library for PY2 & PY3 comp…, a=testonly Automatic update from web-platform-tests Iterating over dictionary's items with six library for PY2 & PY3 compatibility. -- wpt-commits: ef72cc2212e324334032148aea9169edf2562ef5 wpt-pr: 21822

import json

import webdriver

from six import iteritems

"""WebDriver wire protocol codecs."""

class Encoder(json.JSONEncoder):
    def __init__(self, *args, **kwargs):
        super(Encoder, self).__init__(*args, **kwargs)

    def default(self, obj):
        if isinstance(obj, (list, tuple)):
            return [self.default(x) for x in obj]
        elif isinstance(obj, webdriver.Element):
            return {webdriver.Element.identifier: obj.id}
        elif isinstance(obj, webdriver.Frame):
            return {webdriver.Frame.identifier: obj.id}
        elif isinstance(obj, webdriver.Window):
            return {webdriver.Frame.identifier: obj.id}
        return super(Encoder, self).default(obj)

class Decoder(json.JSONDecoder):
    def __init__(self, *args, **kwargs):
        self.session = kwargs.pop("session")
        super(Decoder, self).__init__(
            object_hook=self.object_hook, *args, **kwargs)

    def object_hook(self, payload):
        if isinstance(payload, (list, tuple)):
            return [self.object_hook(x) for x in payload]
        elif isinstance(payload, dict) and webdriver.Element.identifier in payload:
            return webdriver.Element.from_json(payload, self.session)
        elif isinstance(payload, dict) and webdriver.Frame.identifier in payload:
            return webdriver.Frame.from_json(payload, self.session)
        elif isinstance(payload, dict) and webdriver.Window.identifier in payload:
            return webdriver.Window.from_json(payload, self.session)
        elif isinstance(payload, dict):
            return {k: self.object_hook(v) for k, v in iteritems(payload)}
        return payload