Issue
I'm using Bleak to discover & connect to the nearest Bluetooth Low Energy (BLE) device, and I'm currently writing unit tests (using pytest).
I am new to Python tests and I don't know what to do with these patch/mock to make it work on async
functions.
I do not know if I should use the actual function, or apply patches to the default functions to make the test executable without the BLE dongle.
Here is a sample of code (improvement of discover.py) :
def list(op_sys: str) -> list:
"""list BLE devices
Returns:
list: status & list or error message
"""
import asyncio, platform
from bleak import discover
async def run() -> list:
"""discover BLE devices
Returns:
list: status & list or error message
"""
BLElist = []
try:
devices = await discover()
for d in devices:
print("'%s'" % d.name) # list devices
BLElist.append(d.name)
return 'success', BLElist
except:
return 'error', 'You don\'t have any BLE dongle.'
# linux = 3.6, windows = 3.7, need a new loop to work
if op_sys == "Windows":
asyncio.set_event_loop(asyncio.new_event_loop())
loop = asyncio.get_event_loop()
return loop.run_until_complete(run())
I'm wondering if I should rewrite the function to move the run()
part outside, and mock it.
Solution
The outer function list(op_sys) -> list
is not async because it does a call to loop.run_until_complete
.
So that one can be unit tested like any synchronous python function.
If you want to unit test async functions like the inner function run() -> list
, take a look over here: https://pypi.org/project/asynctest/.
Answered By - Freek Wiekmeijer
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.