2 # Copyright 2020 The Pigweed Authors
4 # Licensed under the Apache License, Version 2.0 (the "License"); you may not
5 # use this file except in compliance with the License. You may obtain a copy of
8 # https://www.apache.org/licenses/LICENSE-2.0
10 # Unless required by applicable law or agreed to in writing, software
11 # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12 # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 # License for the specific language governing permissions and limitations under
15 """Launch a pw_test_server server to use for multi-device testing."""
21 from typing import IO, List, Optional
25 import pw_arduino_build.log
26 from pw_arduino_build import teensy_detector
27 from pw_arduino_build.file_operations import decode_file_json
28 from pw_arduino_build.unit_test_runner import ArduinoCoreNotSupported
30 _LOG = logging.getLogger('unit_test_server')
32 _TEST_RUNNER_COMMAND = 'arduino_unit_test_runner'
34 _TEST_SERVER_COMMAND = 'pw_target_runner_server'
37 class UnknownArduinoCore(Exception):
38 """Exception raised when no Arduino core can be found."""
42 """Parses command-line arguments."""
44 parser = argparse.ArgumentParser(description=__doc__)
45 parser.add_argument('--server-port',
48 help='Port to launch the pw_target_runner_server on')
49 parser.add_argument('--server-config',
50 type=argparse.FileType('r'),
51 help='Path to server config file')
52 parser.add_argument('--verbose',
56 help='Output additional logs as the script runs')
57 parser.add_argument("-c",
60 help="Path to an arduino_builder config file.")
61 # TODO(tonymd): Explicitly split args using "--". See example in:
62 # //pw_unit_test/py/pw_unit_test/test_runner.py:326
63 parser.add_argument('runner_args',
64 nargs=argparse.REMAINDER,
65 help='Arguments to forward to the test runner')
67 return parser.parse_args()
70 def generate_runner(command: str, arguments: List[str]) -> str:
71 """Generates a text-proto style pw_target_runner_server configuration."""
72 # TODO(amontanez): Use a real proto library to generate this when we have
74 for i, arg in enumerate(arguments):
75 arguments[i] = f' args: "{arg}"'
76 runner = ['runner {', f' command:"{command}"']
77 runner.extend(arguments)
79 return '\n'.join(runner)
82 def generate_server_config(runner_args: Optional[List[str]],
83 arduino_package_path: str) -> IO[bytes]:
84 """Returns a temporary generated file for use as the server config."""
86 if "teensy" not in arduino_package_path:
87 raise ArduinoCoreNotSupported(arduino_package_path)
89 boards = teensy_detector.detect_boards(arduino_package_path)
91 _LOG.critical('No attached boards detected')
93 config_file = tempfile.NamedTemporaryFile()
94 _LOG.debug('Generating test server config at %s', config_file.name)
95 _LOG.debug('Found %d attached devices', len(boards))
99 test_runner_args += runner_args
100 test_runner_args += ["-v"] + board.test_runner_args()
101 test_runner_args += ["--port", board.dev_name]
102 test_runner_args += ["--upload-tool", board.arduino_upload_tool_name]
104 generate_runner(_TEST_RUNNER_COMMAND,
105 test_runner_args).encode('utf-8'))
110 def launch_server(server_config: Optional[IO[bytes]],
111 server_port: Optional[int], runner_args: Optional[List[str]],
112 arduino_package_path: str) -> int:
113 """Launch a device test server with the provided arguments."""
114 if server_config is None:
115 # Auto-detect attached boards if no config is provided.
116 server_config = generate_server_config(runner_args,
117 arduino_package_path)
119 cmd = [_TEST_SERVER_COMMAND, '-config', server_config.name]
121 if server_port is not None:
122 cmd.extend(['-port', str(server_port)])
124 return pw_cli.process.run(*cmd, log_output=True).returncode
128 """Launch a device test server with the provided arguments."""
131 if "--" in args.runner_args:
132 args.runner_args.remove("--")
134 log_level = logging.DEBUG if args.verbose else logging.INFO
135 pw_arduino_build.log.install(log_level)
137 # Get arduino_package_path from either the config file or command line args.
138 arduino_package_path = None
140 json_file_options, unused_config_path = decode_file_json(
142 arduino_package_path = json_file_options.get("arduino_package_path",
144 # Must pass --config-file option in the runner_args.
145 if "--config-file" not in args.runner_args:
146 args.runner_args.append("--config-file")
147 args.runner_args.append(args.config_file)
149 # Check for arduino_package_path in the runner_args
151 arduino_package_path = args.runner_args[
152 args.runner_args.index("--arduino-package-path") + 1]
153 except (ValueError, IndexError):
154 # Only raise an error if arduino_package_path not set from the json.
155 if arduino_package_path is None:
156 raise UnknownArduinoCore("Test runner arguments: '{}'".format(
157 " ".join(args.runner_args)))
159 exit_code = launch_server(args.server_config, args.server_port,
160 args.runner_args, arduino_package_path)
164 if __name__ == '__main__':