EnvConfig.py 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. # SPDX-FileCopyrightText: 2015-2022 Espressif Systems (Shanghai) CO LTD
  2. # SPDX-License-Identifier: Apache-2.0
  3. """
  4. The test env could change when we running test from different computers.
  5. Test env config provide ``get_variable`` method to allow user get test environment related variables.
  6. It will first try to get variable from config file.
  7. If failed, then it will try to auto detect (Not supported yet).
  8. Config file format is yaml. it's a set of key-value pair. The following is an example of config file::
  9. Example_WIFI:
  10. ap_ssid: "myssid"
  11. ap_password: "mypassword"
  12. Example_ShieldBox:
  13. attenuator_port: "/dev/ttyUSB2"
  14. ap_ssid: "myssid"
  15. ap_password: "mypassword"
  16. It will first define the env tag for each environment, then add its key-value pairs.
  17. This will prevent test cases from getting configs from other env when there're configs for multiple env in one file.
  18. """
  19. import yaml
  20. from yaml import Loader as Loader
  21. class Config(object):
  22. """ Test Env Config """
  23. def __init__(self, config_file, env_tag):
  24. self.configs = self.load_config_file(config_file, env_tag)
  25. @staticmethod
  26. def load_config_file(config_file, env_name):
  27. """
  28. load configs from config file.
  29. :param config_file: config file path
  30. :param env_name: env tag name
  31. :return: configs for the test env
  32. """
  33. try:
  34. with open(config_file) as f:
  35. configs = yaml.load(f, Loader=Loader)[env_name]
  36. except (OSError, TypeError, IOError, KeyError):
  37. configs = dict()
  38. return configs
  39. def get_variable(self, variable_name):
  40. """
  41. first try to get from config file. if not found, try to auto detect the variable.
  42. :param variable_name: name of variable
  43. :return: value or None
  44. """
  45. try:
  46. value = self.configs[variable_name]
  47. except KeyError:
  48. # TODO: to support auto get variable here
  49. value = None
  50. if value is None:
  51. raise ValueError('Failed to get variable')
  52. return value