40f0a538e522839d2689a487175cd4c27506d49a
[AGL/documentation.git] / docs / 5_Component_Documentation / 7_pyagl.md
1 ---
2 title: PyAGL
3 ---
4
5 # 0. Intro
6 ## Main purpose 
7 PyAGL was written to be used as a testing framework replacing the Lua afb-test one,
8 however the modules are written in a way that could be used as standalone utilities to query
9 and evaluate apis and verbs from the App Framework Binder services in AGL.
10
11 ## High level overview
12 Python compatibility: **Python 3.8 preferred**, **should** be compatible with **3.6**
13
14 Initial development PyAGL was done with Python **3.6** in mind, heavily using f-strings and a few typings. As of writing this 
15 documentation(June 3rd 2021), current stable AGL version is Koi 11.0.2 which has Python 3.8, and further development is 
16 done using 3.8 and 3.9 runtimes although **no** version-specific features are used from later versions; 
17 features **used** are kept within features offered by Python **3.8**.
18
19 The test suite is written in a relatively standard way of extending **pytest** with a couple tweaks 
20 tailored to Jenkins CI and LAVA for AGL with regards to output and timings/timeouts, and these tweaks 
21 are enabled by running `pytest -L` in order to enable LAVA logging behavior.
22
23 The way PyAGL works could be summarized in several bullets below:
24
25 * `websockets` package is used to communicate to the services, `x-afb-ws-json1` is used as a subprotocol, 
26 * base.py provides AGLBaseService to be extended for each service
27 * AGLBaseService has a `portfinder()` routine which will use `asyncssh` if used remotely, 
28 to figure out the port of the service's websocket that is listening on. When this was implemented services had a hardcoded listening port,
29 and was often changed when a new service was introduced. If you specify port, pyagl will connect to it directly. If no port is specified and
30 portfinder() cannot find the process or listening port should throw an exception and exit.
31 * main() implementations in most PyAGL services' bindings are intended to be used as a convenient standalone utility to query verbs, although
32 not necessarily available.
33 * PyAGL bindings are organized in classes, method names and respective parameters mostly adhere to service verbs/apis described 
34 per service in https://git.automotivelinux.org/apps/agl-service-*/about
35 For example, in https://git.automotivelinux.org/apps/agl-service-audiomixer/about/ the docs for the service describe 5 verbs -
36 subscribe, unsubscribe, list_controls, volume, mute - and their respective methods in audiomixer.py.
37 * as mentioned above `pytest` package is required for unit tests. 
38 * `pytest-async` is needed by pytest to cooperate with asyncio
39 * `pytest-dependency` is used in cases where specific testing order is needed and used via decorators
40
41 # 1. Using PyAGL
42 Command line execution is intended for debugging and quick evaluation.
43 There are few prerequisites to start using it. First, your AGL image **must** be bitbaked with **agl-devel** feature when sourcing __aglsetup.sh__;
44 if not - the running AGL instance won't have websocket services exposed to listening TCP ports and PyAGL will fail to connect.
45
46 ```bash
47 git clone "https://gerrit.automotivelinux.org/gerrit/src/pyagl"
48 ```
49 Preferably create a virtualenv and install the packages in the env
50 ```bash
51 user@debian:~$ python3 -mvenv ~/.virtualenvs/aglenv
52 user@debian:~$ source ~/.virtualenvs/aglenv/bin/activate
53 (aglenv) user@debian:~$ pip install -r requirements.txt
54 ```
55 Hard requirements are asyncssh, websockets, pytest, pytest-dependency, pytest-async; the others in the file are dependencies of the mentioned packages.
56
57 If you have installed PyAGL as python package or current working directory is in the project root:
58 ```
59 (aglenv) user@debian:~/pyagl$ python3 -m pyagl.services.audiomixer 192.168.234.34 --list_controls
60 ```
61 should produce the following or similar result depending on how many controls are exposed and which AGL version you are running:
62 ```
63 matching services: ['afm-service-agl-service-audiomixer--0.1--main@1001.service']
64 Requesting list_controls with id 359450446
65 [RESPONSE][Status: success][359450446][Info: None][Data: [{'control': 'Master Playback', 'volume': 1.0, 'mute': 0}, 
66 {'control': 'Playback: Speech-Low', 'volume': 1.0, 'mute': 0}, {'control': 'Playback: Emergency', 'volume': 1.0, 'mute': 0}, 
67 {'control': 'Playback: Speech-High', 'volume': 1.0, 'mute': 0}, {'control': 'Playback: Navigation', 'volume': 1.0, 'mute': 0}, 
68 {'control': 'Playback: Multimedia', 'volume': 1.0, 'mute': 0}, {'control': 'Playback: Custom-Low', 'volume': 1.0, 'mute': 0}, 
69 {'control': 'Playback: Communication', 'volume': 1.0, 'mute': 0}, {'control': 'Playback: Custom-High', 'volume': 1.0, 'mute': 0}]]
70 ```
71
72 # 2. Running the tests
73
74 ## Markers
75 Before running the tests it must be noted that __Markers__ are metavariables applied to the tests which play important part 
76 in the behavior of pyagl and add great flexibility when deciding which tests to run.  
77 Each test suite usually have unambiguous marker and description in `pytest.ini` for the reason above.  
78 The default markers are applied in the list variable `pytestmark` in the beginning of each test file.  
79 Each test suite has at least 2 default markers.
80
81 `pytest.mark.asyncio` is a special marker needed because we are running pytest in async mode,
82 and the other marker is the name of the testsuite - for example `pytest.mark.geoclue` is for `geoclue` tests.
83
84 `pytest.mark.dependency` is another special marker used by the pytest-dependency library helping for 
85 running tests in a particular order when a more complicated setup other than a fixture is needed for 
86 a test or the setup itself is a test or sequence of tests.
87
88 `pytest.mark.hwrequired` is a marker signifying that additional hardware is required for tests to be successful - e.g. bluetooth phonebook tests need a phone with a pbap profile connected
89
90 `pytest.mark.internet` is a marker for tests which require internet connection
91
92 As mentioned above, behavior of pytest is altered by the markers because pytest does expression matching by marker and test names for which suite to be run.  
93 In the example below we select all internet requiring and subscription tests but skip those that require additional hardware.  
94 If we have a match with `internet or subscribe` the test will be selected, but if the test has `hwrequired` will be skipped, otherwise deselected overall.
95 ```
96 h3ulcb:~# pyagl -vk "internet or subscribe and not hwrequired"
97 ============================ test session starts ============================
98 platform linux -- Python 3.8.2, pytest-5.3.5, py-1.8.1, pluggy-0.13.1 -- /usr/bin/python3
99 cachedir: .pytest_cache
100 rootdir: /usr/lib/python3.8/site-packages/pyagl, inifile: pytest.ini
101 plugins: asyncio-0.10.0, dependency-0.5.1, reverse-1.0.1
102 collected 218 items / 163 deselected / 55 selected                          
103
104 test_bluetooth.py::test_subscribe_device_changes PASSED               [  1%]
105 ...
106 test_radio.py::test_unsubscribe_all PASSED                            [ 90%]
107 test_signal_composer.py::test_subscribe SKIPPED                       [ 92%]
108 test_signal_composer.py::test_unsubscribe SKIPPED                     [ 94%]
109 test_weather.py::test_current_weather FAILED                          [ 96%]
110 test_weather.py::test_subscribe_weather PASSED                        [ 98%]
111 test_weather.py::test_unsubscribe_weather PASSED                      [100%]
112 ==== 1 failed, 37 passed, 17 skipped, 163 deselected, 1 warning in 3.23s ====
113
114 ```
115
116 ## Locally - On the board itself
117 There is the /usr/bin/pyagl convenience wrapper script which invokes pytest  
118 with the tests residing in `/usr/lib/python3.8/site-packages/pyagl/tests` which  
119 also will pass all commandline arguments down to pytest
120
121 ```console
122 qemux86-64:~# pyagl
123 =================== test session starts =============================
124 platform linux -- Python 3.8.2, pytest-5.3.5, py-1.8.1, pluggy-0.13.1
125 rootdir: /usr/lib/python3.8/site-packages/pyagl, inifile: pytest.ini
126 plugins: dependency-0.5.1, asyncio-0.10.0, reverse-1.0.1
127 collected 213 items
128
129 test_audiomixer.py .......                                    [  3%]
130 test_bluetooth.py ............xxxsxx                          [ 11%]
131 test_bluetooth_map.py .x.xs.                                  [ 12%]
132 ...
133 ```
134
135 ## Remotely
136 You must export `AGL_TGT_IP` environment variable first, containing a string with a reachable IP address 
137 configured(either DHCP or static) on one of the interfeces on the AGL instance(board or vm) on your network.
138 `AGL_TGT_PORT` is not required, however can be exported to skip over connecting to the board via ssh first 
139 in order to figure out the listening port of service. 
140
141 ```console
142 user@debian:~$ source ~/.virtualenvs/aglenv/bin/activate
143 (pyagl) user@debian:~$ export AGL_TGT_IP=192.168.234.34
144 (pyagl) user@debian:~$ cd pydev/pyagl/pyagl/tests
145 (pyagl) user@debian:~/pydev/pyagl/pyagl/tests$ pytest test_geoclue.py
146 ========================= test session starts =========================
147 platform linux -- Python 3.9.2, pytest-5.4.1, py-1.8.1, pluggy-0.13.1
148 rootdir: /home/user/pydev/pyagl/pyagl, inifile: pytest.ini
149 plugins: dependency-0.5.1, asyncio-0.11.0
150 collected 3 items
151
152 test_geoclue.py ...                                              [100%]
153 ```
154 # 3. Writing bindings and/or tests for new services
155 This assumes you have already went through ["3. Developer Guides > Creating a new service"](../3_Developer_Guides/2_Creating_a_New_Service.md).
156
157 Templates directory contains barebone _cookiecutter_ templates to create your project.
158 If you do not intend to use cookiecutter, you need a simple service file in which you inherit AGLBaseService
159 from base.py. 
160 You can take a look at pyagl/services/geoclue.py and pyagl/tests/test_geoclue.py which is probably the
161 simplest binding in PyAGL for a reference and example. All basic methods like 
162 [send|receive|un/subscribe|portfinder] are implemented in the base class. 
163 You would need to do minimal work to create new service binding from scratch and by example of the geoclue service you need to do the following:  
164
165 * do the basic imports 
166 ```python3
167 from pyagl.services.base import AGLBaseService, AFBResponse
168 import asyncio
169 ```
170
171 * inherit AGLBaseService and type in the service class member the service name presuming you are following the AGL naming convention:
172 (if your new service does not follow the convention, the portfider routine wont work and you'll have to specify service port manually)
173 ```python3
174 class GeoClueService(AGLBaseService):
175     service = 'agl-service-geoclue'
176 ```
177
178 * if you intend to run the new service binding as a standalone utility, you might want to add your new options to the argparser
179 ```python3
180     parser = AGLBaseService.getparser()
181     parser.add_argument('--location', help='Get current location', action='store_true')
182 ```
183
184 * override the __init__ method with the respective parameters as api(used in the binding) and systemd service slug
185 ```
186     def __init__(self, ip, port=None, api='geoclue'):
187         super().__init__(ip=ip, port=port, api=api, service='agl-service-geoclue')
188 ```
189
190 * define your methods and send requests with .request() which prepares the data in a JSON format, request returns message id
191 ```
192     async def location(self):
193         return await self.request('location')
194 ```
195
196 * get the raw response with data = await .response() or use .afbresponse() to get structured data
197
198 PyAGL is written with asyncio so you'd need an event loop to get your code running.  
199 Most modules have standalone CLI functionality, which is done via ArgumentParser and each module that  
200 is CLI usable inherits static base parser and extends its arguments as shown in the example below:
201
202 ```python3
203 async def main(loop):
204     args = GeoClueService.parser.parse_args()
205     gcs = await GeoClueService(args.ipaddr)
206
207     if args.location:
208         msgid = await gcs.location()
209         print(f'Sent location request with messageid {msgid}')
210         print(await gcs.afbresponse())
211
212 if __name__ == '__main__':
213     loop = asyncio.get_event_loop()
214     loop.run_until_complete(main(loop))
215 ```
216 `GeoClueService` will try to return an instance with connection to the service. It will throw an exception if it fails to do so.  
217 `AGLBaseService.afbresponse()` method is a wrapper on top of .response() which will prepare, validate and format data for a convenient usage intended for CLI usage.  
218 `AFBResponse.__str__`  is also a convenience method to be able to print all relevant data in regarding state of the response.  
219
220 ```console
221 (aglenv) user@debian:~$ python3 -m pyagl.services.geoclue 192.168.234.251 --location
222 matching services: ['afm-service-agl-service-geoclue--1.0--main.service']
223 Sent location request with messageid 29188435
224 [RESPONSE][Status: success][29188435][Info: GeoClue location data][Data: {'latitude': 42.6898421, 'longitude': 23.3099069, 'accuracy': 107.4702045}]
225 ```
226
227
228 # 4. Environment variables
229 The following environment variables are used in the PyAGL project:
230
231 Variable | Description
232 --- | ---
233 **AGL_TGT_IP** | **required**
234 **AGL_TGT_PORT** | **optional**, when this is used portfinder() routine is skipped, attempts direct websocket connection to this port.
235 **AGL_TEST_TIMEOUT** | **optional**, over-ride the default 5 second timeout value for binding responses. This is useful in many cases where a long-standing request has taken place - e.g. importing few thousand entries from a phonebook
236 **AGL_AVAILABLE_INTERFACES** | **optional**, specify which of ethernet, wifi, and bluetooth interfaces are available.  The value is a comma separated list, with a default value of "ethernet,wifi,bluetooth".
237 **AGL_BTMAP_RECIPIENT** | **optional**, when running Bluetooth MAP tests, this would be used as phone number to write text messages to.
238 **AGL_BTMAP_TEXT** | **optional**, when running Bluetooth MAP tests, messages will be composed with this text.
239 **AGL_CAN_INTERFACE** | **optional**, specify the CAN interface to use for CAN testing, default value is "can0".
240 **AGL_PBAP_PHONENUM** | **optional**, when running Bluetooth PBAP tests, this phone number will be used to .search().
241 **AGL_PBAP_VCF** | **optional**, for the Bluetooh PBAP tests query a contact entry out of the phonebook.
242 **AGL_BT_TEST_ADDR** | **optional**, for the Bluetooth tests pair/connect/disconnect with an actual Bluetooth device(phone)'s address .  The address should have the DBus address style as "dev_00_01_02_03_04_05" instead of a regular colon-separated MAC address.
243
244 # 5. Debugging
245 PyAGL uses pythons logger library so you can rise the logging level and see the output from most of the modules, 
246 but was disabled by default because of the massive amount of output produced. When the default logger is enabled 
247 all other libraries will show their output with pyagl - e.g. websockets, asyncssh etc.
248
249 README.md in the root directory of the project also contains useful information.
250