• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1#!/usr/bin/env python3
2# coding=utf-8
3
4#
5# Copyright (c) 2020-2021 Huawei Device Co., Ltd.
6# Licensed under the Apache License, Version 2.0 (the "License");
7# you may not use this file except in compliance with the License.
8# You may obtain a copy of the License at
9#
10#     http://www.apache.org/licenses/LICENSE-2.0
11#
12# Unless required by applicable law or agreed to in writing, software
13# distributed under the License is distributed on an "AS IS" BASIS,
14# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15# See the License for the specific language governing permissions and
16# limitations under the License.
17#
18
19import json
20import os
21import stat
22from _core.exception import ParamError
23from _core.logger import platform_logger
24from _core.plugin import Config
25
26__all__ = ["JsonParser"]
27LOG = platform_logger("JsonParser")
28
29
30class JsonParser:
31    """
32    This class parses json files or string, sample:
33    {
34        "description": "Config for lite cpp test cases",
35        "environment": [
36            {
37                "type": "device",
38                "label": "ipcamera"
39            }
40        ],
41        "kits": [
42            {
43                "type": "MountKit",
44                "nfs": "NfsServer",
45                "bin_file": "CppTestLite/KvStoreTest.bin"
46            }
47        ],
48        "driver": {
49            "type": "CppTestLite",
50            "xml-output": false,
51            "rerun": false
52        }
53    }
54    """
55
56    def __init__(self, path_or_content):
57        """Instantiate the class using the manifest file denoted by path or
58        content
59        """
60        self.config = Config()
61        self._do_parse(path_or_content)
62
63    def _do_parse(self, path_or_content):
64        try:
65            if path_or_content.find("{") != -1:
66                json_content = json.loads(
67                    path_or_content, encoding="utf-8")
68            else:
69                if not os.path.exists(path_or_content):
70                    raise ParamError("The json file {} does not exist".format(
71                        path_or_content), error_no="00110")
72
73                flags = os.O_RDONLY
74                modes = stat.S_IWUSR | stat.S_IRUSR
75                with os.fdopen(os.open(path_or_content, flags, modes),
76                               "r") as file_content:
77                    json_content = json.load(file_content)
78        except (TypeError, ValueError, AttributeError) as error:
79            raise ParamError("json file error: %s %s" % (
80                path_or_content, error), error_no="00111")
81        self._check_config(json_content)
82
83        # set self.config
84        self.config = Config()
85        self.config.description = json_content.get("description", "")
86        self.config.kits = json_content.get("kits", [])
87        self.config.environment = json_content.get("environment", [])
88        self.config.driver = json_content.get("driver", {})
89
90    def _check_config(self, json_content):
91        for kit in json_content.get("kits", []):
92            self._check_type_key_exist("kits", kit)
93        for device in json_content.get("environment", []):
94            self._check_type_key_exist("environment", device)
95        if json_content.get("driver", {}):
96            self._check_type_key_exist("driver", json_content.get("driver"))
97
98    @classmethod
99    def _check_type_key_exist(cls, key, value):
100        if not isinstance(value, dict):
101            raise ParamError("%s under %s should be dict" % (value, key))
102        if "type" not in value.keys():
103            raise ParamError("'type' key not exists in %s under %s" % (
104                value, key))
105
106    def get_config(self):
107        return self.config
108
109    def get_description(self):
110        return getattr(self.config, "description", "")
111
112    def get_kits(self):
113        return getattr(self.config, "kits", [])
114
115    def get_environment(self):
116        return getattr(self.config, "environment", [])
117
118    def get_driver(self):
119        return getattr(self.config, "driver", {})
120
121    def get_driver_type(self):
122        driver = getattr(self.config, "driver", {})
123        return driver.get("type", "") if driver else ""
124