common_test_methods.py 2.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. # SPDX-FileCopyrightText: 2022 Espressif Systems (Shanghai) CO LTD
  2. # SPDX-License-Identifier: Apache-2.0
  3. import logging
  4. import os
  5. import socket
  6. from typing import Any
  7. import netifaces
  8. import yaml
  9. ENV_CONFIG_FILE_SEARCH = [
  10. os.path.join(os.environ['IDF_PATH'], 'EnvConfig.yml'),
  11. os.path.join(os.environ['IDF_PATH'], 'ci-test-runner-configs', os.environ.get('CI_RUNNER_DESCRIPTION', ''), 'EnvConfig.yml'),
  12. ]
  13. ENV_CONFIG_TEMPLATE = '''
  14. $IDF_PATH/EnvConfig.yml:
  15. ```yaml
  16. <env_name>:
  17. key: var
  18. key2: var2
  19. <another_env>:
  20. key: var
  21. ```
  22. '''
  23. def get_host_ip_by_interface(interface_name: str, ip_type: int = netifaces.AF_INET) -> str:
  24. for _addr in netifaces.ifaddresses(interface_name)[ip_type]:
  25. host_ip = _addr['addr'].replace('%{}'.format(interface_name), '')
  26. assert isinstance(host_ip, str)
  27. return host_ip
  28. return ''
  29. def get_host_ip4_by_dest_ip(dest_ip: str = '') -> str:
  30. if not dest_ip:
  31. dest_ip = '8.8.8.8'
  32. s1 = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
  33. s1.connect((dest_ip, 80))
  34. host_ip = s1.getsockname()[0]
  35. s1.close()
  36. assert isinstance(host_ip, str)
  37. print(f'Using host ip: {host_ip}')
  38. return host_ip
  39. def get_my_interface_by_dest_ip(dest_ip: str = '') -> str:
  40. my_ip = get_host_ip4_by_dest_ip(dest_ip)
  41. interfaces = netifaces.interfaces()
  42. for interface in interfaces:
  43. try:
  44. addresses = netifaces.ifaddresses(interface)[netifaces.AF_INET]
  45. except KeyError:
  46. continue
  47. if my_ip in [a['addr'] for a in addresses]:
  48. assert isinstance(interface, str)
  49. return interface
  50. logging.error('Can not get interface, dest ip is {}'.format(dest_ip))
  51. return ''
  52. def get_env_config_variable(env_name: str, key: str, default: Any = None) -> Any:
  53. """
  54. Get test environment related variable
  55. config file format: $IDF_PATH/EnvConfig.yml
  56. ```
  57. <env_name>:
  58. key: var
  59. key2: var2
  60. <env_name2>:
  61. key: var
  62. ```
  63. """
  64. config = dict()
  65. for _file in ENV_CONFIG_FILE_SEARCH:
  66. try:
  67. with open(_file, 'r') as f:
  68. data = yaml.load(f.read(), Loader=yaml.SafeLoader)
  69. config = data[env_name]
  70. break
  71. except (FileNotFoundError, KeyError):
  72. pass
  73. else:
  74. pass
  75. var = config.get(key, default)
  76. if var is None:
  77. logging.warning(f'Failed to get env variable {env_name}/{key}.')
  78. logging.info(f'Env config file template: {ENV_CONFIG_TEMPLATE}')
  79. if not os.environ.get('CI_JOB_ID'):
  80. # Try to get variable from stdin
  81. var = input(f'You can input the variable now:')
  82. else:
  83. raise ValueError(f'Env variable not found: {env_name}/{key}')
  84. logging.debug(f'Got env variable {env_name}/{key}: {var}')
  85. return var