test_lock.py 58 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712
  1. import logging
  2. from typing import Any
  3. from unittest.mock import AsyncMock, Mock, call, patch
  4. import pytest
  5. from switchbot import SwitchbotLockUltra, SwitchbotModel
  6. from switchbot.const.lock import LockStatus, QuickKeyFunction
  7. from switchbot.devices import lock
  8. from switchbot.devices.device import SwitchbotOperationError
  9. from switchbot.models import SwitchBotAdvertisement
  10. from .test_adv_parser import generate_ble_device
  11. @pytest.mark.asyncio
  12. @pytest.mark.parametrize(
  13. ("replies", "valid"),
  14. [
  15. (
  16. [bytes.fromhex("01 88 00 00 00 00 00"), bytes.fromhex("01 85 28 21 14")],
  17. True,
  18. ),
  19. ([None], False),
  20. ([bytes.fromhex("01 88 00 00 00 00 00"), None], False),
  21. ],
  22. )
  23. async def test_uwb_lock_key_verification(replies, valid):
  24. device = generate_ble_device("aa:bb:cc:dd:ee:ff", "UWB Lock")
  25. with patch.object(SwitchbotLockUltra, "_send_command", side_effect=replies) as send:
  26. assert (
  27. await SwitchbotLockUltra.verify_encryption_key(
  28. device, "ff", "ff" * 16, SwitchbotModel.UWB_LOCK
  29. )
  30. is valid
  31. )
  32. assert [args.kwargs["key"] for args in send.await_args_list] == [
  33. "570f4f8107",
  34. "5702",
  35. ][: len(replies)]
  36. @pytest.mark.asyncio
  37. async def test_nano_update_reads_lock_and_basic_info():
  38. device = create_device_for_command_testing(SwitchbotModel.LOCK_NANO)
  39. device.update_from_advertisement(
  40. SwitchBotAdvertisement(
  41. device._device.address, {"data": {"battery": 95}}, device._device, -60
  42. )
  43. )
  44. replies = [bytes.fromhex("01 90 08 5f 00 00 40"), bytes.fromhex("01 4b 21 14")]
  45. with patch.object(device, "_send_command", side_effect=replies) as send:
  46. await device.update()
  47. assert send.await_args_list == [
  48. call(key="570f4f810c", retry=device._retry_count),
  49. call(key="5702", retry=device._retry_count),
  50. ]
  51. assert device.get_lock_status() is LockStatus.LOCKING
  52. assert device.is_calibrated()
  53. assert device.is_auto_lock_paused()
  54. assert device.is_unlocked_alarm_on()
  55. assert device.get_battery_percent() == 75
  56. assert device.parsed_data["firmware"] == 3.3
  57. @pytest.mark.asyncio
  58. async def test_nano_key_verification_without_response():
  59. device = generate_ble_device("aa:bb:cc:dd:ee:ff", "Lock Nano")
  60. with patch.object(lock.SwitchbotLock, "_send_command", return_value=None):
  61. assert not await lock.SwitchbotLock.verify_encryption_key(
  62. device, "ff", "ff" * 16, SwitchbotModel.LOCK_NANO
  63. )
  64. @pytest.mark.asyncio
  65. async def test_nano_lock_info_command():
  66. device = create_device_for_command_testing(SwitchbotModel.LOCK_NANO)
  67. with patch.object(device, "_send_command", return_value=b"\x01\x00") as send:
  68. assert await device._get_lock_info() == b"\x01\x00"
  69. send.assert_awaited_once_with(key="570f4f810c", retry=device._retry_count)
  70. @pytest.mark.asyncio
  71. async def test_nano_notification_command():
  72. device = create_device_for_command_testing(SwitchbotModel.LOCK_NANO)
  73. with patch.object(device, "_send_command", return_value=b"\x01\x00") as send:
  74. assert await device._enable_notifications()
  75. send.assert_awaited_once_with("570e01001e0000810c")
  76. def create_device_for_command_testing(model: str, cls=lock.SwitchbotLock):
  77. ble_device = generate_ble_device("aa:bb:cc:dd:ee:ff", "any")
  78. return cls(ble_device, "ff", "ffffffffffffffffffffffffffffffff", model=model)
  79. def test_nano_status_notification_updates_device():
  80. device = create_device_for_command_testing(SwitchbotModel.LOCK_NANO)
  81. advertisement = SwitchBotAdvertisement(
  82. device._device.address,
  83. {"data": {"status": LockStatus.UNLOCKED}},
  84. device._device,
  85. -60,
  86. )
  87. device.update_from_advertisement(advertisement)
  88. received = []
  89. device.subscribe(lambda: received.append(device.get_lock_status()))
  90. payload = bytes.fromhex("90 00 00 00 00 00")
  91. with (
  92. patch.object(device, "_decrypt", return_value=payload) as decrypt,
  93. patch.object(device, "_reset_disconnect_timer"),
  94. ):
  95. frame = bytearray.fromhex("0f 00 00 00 12 34 56 78 9a bc")
  96. device._notification_handler(0, frame)
  97. decrypt.assert_called_once_with(frame[4:])
  98. assert received == [LockStatus.LOCKING]
  99. assert device.get_lock_status() is LockStatus.LOCKING
  100. @pytest.mark.parametrize(
  101. "model",
  102. [
  103. SwitchbotModel.LOCK,
  104. SwitchbotModel.LOCK_LITE,
  105. SwitchbotModel.LOCK_PRO,
  106. SwitchbotModel.LOCK_ULTRA,
  107. SwitchbotModel.LOCK_ULTRA_MAX,
  108. SwitchbotModel.UWB_LOCK,
  109. SwitchbotModel.LOCK_NANO,
  110. SwitchbotModel.LOCK_VISION,
  111. SwitchbotModel.LOCK_VISION_PRO,
  112. SwitchbotModel.LOCK_PRO_WIFI,
  113. ],
  114. )
  115. def test_lock_init(model: str):
  116. """Test the initialization of the lock device."""
  117. device = create_device_for_command_testing(model)
  118. assert device._model == model
  119. @pytest.mark.parametrize(
  120. "model",
  121. [
  122. SwitchbotModel.AIR_PURIFIER_JP,
  123. ],
  124. )
  125. def test_lock_init_with_invalid_model(model: str):
  126. """Test that initializing with an invalid model raises ValueError."""
  127. with pytest.raises(
  128. ValueError, match="initializing SwitchbotLock with a non-lock model"
  129. ):
  130. create_device_for_command_testing(model)
  131. def test_ultra_direct_construction():
  132. device = generate_ble_device("aa:bb:cc:dd:ee:ff", "lock")
  133. assert (
  134. SwitchbotLockUltra(device, "ff", "ff" * 16)._model is SwitchbotModel.LOCK_ULTRA
  135. )
  136. def test_default_model_classvar():
  137. """The classvar default is SwitchbotModel.LOCK."""
  138. ble_device = generate_ble_device("aa:bb:cc:dd:ee:ff", "any")
  139. device = lock.SwitchbotLock(ble_device, "ff", "ffffffffffffffffffffffffffffffff")
  140. assert device._model == SwitchbotModel.LOCK
  141. @pytest.mark.asyncio
  142. @pytest.mark.parametrize(
  143. ("model", "command"),
  144. [
  145. (SwitchbotModel.LOCK, b"W\x0fN\x01\x01\x10\x80"),
  146. (SwitchbotModel.LOCK_LITE, b"W\x0fN\x01\x01\x10\x81"),
  147. (SwitchbotModel.LOCK_PRO, b"W\x0fN\x01\x01\x10\x85"),
  148. (SwitchbotModel.LOCK_ULTRA, b"W\x0fN\x01\x01\x10\x86"),
  149. (SwitchbotModel.LOCK_ULTRA_MAX, b"W\x0fN\x01\x01\x00\x00"),
  150. (SwitchbotModel.UWB_LOCK, b"W\x0fN\x01\x01\x00\x00"),
  151. (SwitchbotModel.LOCK_NANO, b"W\x0fN\x01\x01\x00\x00"),
  152. (SwitchbotModel.LOCK_VISION, b"W\x0fN\x01\x01\x00\x80"),
  153. (SwitchbotModel.LOCK_VISION_PRO, b"W\x0fN\x01\x01\x00\x80"),
  154. (SwitchbotModel.LOCK_PRO_WIFI, b"W\x0fN\x01\x01\x10\x82"),
  155. ],
  156. )
  157. async def test_lock(model: str, command: bytes):
  158. """Test lock method."""
  159. device = create_device_for_command_testing(model)
  160. device._get_adv_value = Mock(return_value=LockStatus.UNLOCKED)
  161. with (
  162. patch.object(
  163. device, "_send_command", return_value=b"\x01\x00"
  164. ) as mock_send_command,
  165. patch.object(device, "_enable_notifications", return_value=True),
  166. patch.object(device, "_get_basic_info", return_value=b"\x00\x64\x01"),
  167. ):
  168. result = await device.lock()
  169. assert result is True
  170. mock_send_command.assert_any_call(lock.COMMAND_LOCK[model])
  171. @pytest.mark.asyncio
  172. @pytest.mark.parametrize(
  173. ("model", "command"),
  174. [
  175. (SwitchbotModel.LOCK, b"W\x0fN\x01\x01\x10\x80"),
  176. (SwitchbotModel.LOCK_LITE, b"W\x0fN\x01\x01\x10\x81"),
  177. (SwitchbotModel.LOCK_PRO, b"W\x0fN\x01\x01\x10\x84"),
  178. (SwitchbotModel.LOCK_ULTRA, b"W\x0fN\x01\x01\x10\x83"),
  179. (SwitchbotModel.LOCK_ULTRA_MAX, b"W\x0fN\x01\x01\x00\x80"),
  180. (SwitchbotModel.UWB_LOCK, b"W\x0fN\x01\x01\x00\x80"),
  181. (SwitchbotModel.LOCK_NANO, b"W\x0fN\x01\x01\x00\x80"),
  182. (SwitchbotModel.LOCK_VISION, b"W\x0fN\x01\x01\x00\x80"),
  183. (SwitchbotModel.LOCK_VISION_PRO, b"W\x0fN\x01\x01\x00\x80"),
  184. (SwitchbotModel.LOCK_PRO_WIFI, b"W\x0fN\x01\x01\x10\x81"),
  185. ],
  186. )
  187. async def test_unlock(model: str, command: bytes):
  188. """Test unlock method."""
  189. device = create_device_for_command_testing(model)
  190. device._get_adv_value = Mock(return_value=LockStatus.LOCKED)
  191. with (
  192. patch.object(
  193. device, "_send_command", return_value=b"\x01\x00"
  194. ) as mock_send_command,
  195. patch.object(device, "_enable_notifications", return_value=True),
  196. patch.object(device, "_get_basic_info", return_value=b"\x00\x64\x01"),
  197. ):
  198. result = await device.unlock()
  199. assert result is True
  200. mock_send_command.assert_any_call(lock.COMMAND_UNLOCK[model])
  201. @pytest.mark.asyncio
  202. @pytest.mark.parametrize(
  203. "model",
  204. [
  205. SwitchbotModel.LOCK,
  206. SwitchbotModel.LOCK_LITE,
  207. SwitchbotModel.LOCK_PRO,
  208. SwitchbotModel.LOCK_ULTRA,
  209. SwitchbotModel.LOCK_ULTRA_MAX,
  210. SwitchbotModel.UWB_LOCK,
  211. SwitchbotModel.LOCK_NANO,
  212. SwitchbotModel.LOCK_VISION,
  213. SwitchbotModel.LOCK_VISION_PRO,
  214. SwitchbotModel.LOCK_PRO_WIFI,
  215. ],
  216. )
  217. async def test_unlock_without_unlatch(model: str):
  218. """Test unlock_without_unlatch method."""
  219. device = create_device_for_command_testing(model)
  220. device._get_adv_value = Mock(return_value=LockStatus.LOCKED)
  221. with (
  222. patch.object(device, "_send_command", return_value=b"\x01\x00"),
  223. patch.object(device, "_enable_notifications", return_value=True),
  224. patch.object(device, "_get_basic_info", return_value=b"\x00\x64\x01"),
  225. ):
  226. result = await device.unlock_without_unlatch()
  227. assert result is True
  228. @pytest.mark.asyncio
  229. @pytest.mark.parametrize(
  230. "model",
  231. [
  232. SwitchbotModel.LOCK,
  233. SwitchbotModel.LOCK_LITE,
  234. SwitchbotModel.LOCK_NANO,
  235. SwitchbotModel.LOCK_PRO,
  236. SwitchbotModel.LOCK_ULTRA,
  237. SwitchbotModel.LOCK_ULTRA_MAX,
  238. SwitchbotModel.LOCK_VISION,
  239. SwitchbotModel.LOCK_VISION_PRO,
  240. SwitchbotModel.LOCK_PRO_WIFI,
  241. ],
  242. )
  243. async def test_get_basic_info(model: str):
  244. """Test get_basic_info method."""
  245. device = create_device_for_command_testing(model)
  246. lock_data = b"\x00\x80\x00\x00\x00\x00\x00\x00"
  247. basic_data = bytes.fromhex("01 64 01 21 14")
  248. with (
  249. patch.object(device, "_get_lock_info", return_value=lock_data),
  250. patch.object(device, "_get_basic_info", return_value=basic_data),
  251. patch.object(device, "_get_battery_bays", return_value=None),
  252. ):
  253. result = await device.get_basic_info()
  254. assert result is not None
  255. assert "battery" in result
  256. assert "firmware" in result
  257. assert "calibration" in result
  258. assert "status" in result
  259. assert "left_battery" not in result
  260. @pytest.mark.asyncio
  261. @pytest.mark.parametrize(
  262. "model",
  263. [
  264. SwitchbotModel.LOCK,
  265. SwitchbotModel.LOCK_LITE,
  266. SwitchbotModel.LOCK_NANO,
  267. SwitchbotModel.LOCK_PRO,
  268. SwitchbotModel.LOCK_ULTRA,
  269. SwitchbotModel.LOCK_VISION,
  270. SwitchbotModel.LOCK_VISION_PRO,
  271. SwitchbotModel.LOCK_PRO_WIFI,
  272. ],
  273. )
  274. async def test_get_basic_info_no_lock_data(model: str):
  275. """Test get_basic_info when no lock data is returned."""
  276. device = create_device_for_command_testing(model)
  277. with patch.object(device, "_get_lock_info", return_value=None):
  278. result = await device.get_basic_info()
  279. assert result is None
  280. @pytest.mark.asyncio
  281. @pytest.mark.parametrize(
  282. "model",
  283. [
  284. SwitchbotModel.LOCK,
  285. SwitchbotModel.LOCK_LITE,
  286. SwitchbotModel.LOCK_NANO,
  287. SwitchbotModel.LOCK_PRO,
  288. SwitchbotModel.LOCK_ULTRA,
  289. SwitchbotModel.LOCK_VISION,
  290. SwitchbotModel.LOCK_VISION_PRO,
  291. SwitchbotModel.LOCK_PRO_WIFI,
  292. ],
  293. )
  294. async def test_get_basic_info_no_basic_data(model: str):
  295. """Test get_basic_info when no basic data is returned."""
  296. device = create_device_for_command_testing(model)
  297. lock_data = b"\x00\x80\x00\x00\x00\x00\x00\x00"
  298. with (
  299. patch.object(device, "_get_lock_info", return_value=lock_data),
  300. patch.object(device, "_get_basic_info", return_value=None),
  301. ):
  302. result = await device.get_basic_info()
  303. assert result is None
  304. @pytest.mark.asyncio
  305. async def test_get_basic_info_lock_pro_battery_bays():
  306. """Test get_basic_info reads both battery bays on the Lock Pro."""
  307. device = create_device_for_command_testing(SwitchbotModel.LOCK_PRO)
  308. with (
  309. patch.object(
  310. device, "_get_lock_info", return_value=b"\x00\x80\x00\x00\x00\x00\x00\x00"
  311. ),
  312. patch.object(device, "_get_basic_info", return_value=b"\x00\x64\x01"),
  313. patch.object(
  314. device, "_send_command", return_value=bytes.fromhex("01e4cd0000")
  315. ) as mock_send,
  316. ):
  317. result = await device.get_basic_info()
  318. mock_send.assert_awaited_once_with(key="570f4f0409", retry=device._retry_count)
  319. assert result["left_battery"] == 100
  320. assert result["right_battery"] == 77
  321. @pytest.mark.asyncio
  322. @pytest.mark.parametrize("reply", [b"\x00", b"\x01\xe4"])
  323. async def test_get_battery_bays_bad_reply(reply: bytes):
  324. """Test _get_battery_bays rejects failed and short replies."""
  325. device = create_device_for_command_testing(SwitchbotModel.LOCK_PRO)
  326. with patch.object(device, "_send_command", return_value=reply):
  327. assert await device._get_battery_bays() is None
  328. @pytest.mark.asyncio
  329. async def test_get_basic_info_lock_pro_without_battery_bays():
  330. """Test get_basic_info still succeeds when the bays read is refused."""
  331. device = create_device_for_command_testing(SwitchbotModel.LOCK_PRO)
  332. with (
  333. patch.object(
  334. device, "_get_lock_info", return_value=b"\x00\x80\x00\x00\x00\x00\x00\x00"
  335. ),
  336. patch.object(device, "_get_basic_info", return_value=b"\x00\x64\x01"),
  337. patch.object(device, "_send_command", return_value=b"\x00"),
  338. ):
  339. result = await device.get_basic_info()
  340. assert result is not None
  341. assert result["battery"] == 100
  342. assert "left_battery" not in result
  343. @pytest.mark.parametrize(
  344. ("data", "expected"),
  345. [
  346. (bytes.fromhex("01e4cd0000"), {"left_battery": 100, "right_battery": 77}),
  347. (bytes.fromhex("01e4000000"), {"left_battery": 100, "right_battery": None}),
  348. (bytes.fromhex("0100b20000"), {"left_battery": None, "right_battery": 50}),
  349. ],
  350. )
  351. def test_parse_battery_bays(data: bytes, expected: dict[str, int | None]):
  352. """Test _parse_battery_bays reports None for an empty bay."""
  353. assert lock.SwitchbotLock._parse_battery_bays(data) == expected
  354. @pytest.mark.asyncio
  355. @pytest.mark.parametrize(
  356. "model",
  357. [
  358. SwitchbotModel.LOCK_PRO,
  359. SwitchbotModel.LOCK_ULTRA,
  360. SwitchbotModel.LOCK_ULTRA_MAX,
  361. SwitchbotModel.LOCK_PRO_WIFI,
  362. SwitchbotModel.LOCK_NANO,
  363. SwitchbotModel.UWB_LOCK,
  364. ],
  365. )
  366. @pytest.mark.parametrize("status", range(8, 16))
  367. async def test_get_basic_info_unknown_lock_status(
  368. model: SwitchbotModel, status: int, caplog: pytest.LogCaptureFixture
  369. ):
  370. """Ignore an unknown status in a lock info response."""
  371. device = create_device_for_command_testing(model)
  372. lock_data = bytes([1, 0x80 | status << 3, 0, 0, 0, 0, 0])
  373. with (
  374. patch.object(device, "_get_lock_info", return_value=lock_data),
  375. patch.object(device, "_get_basic_info", return_value=b"\x01\x64\x28\x21\x14"),
  376. caplog.at_level(logging.DEBUG),
  377. ):
  378. assert await device.get_basic_info() is None
  379. assert f"Unknown lock status {status}" in caplog.text
  380. assert lock_data[1:].hex() in caplog.text
  381. @pytest.mark.parametrize("battery", [100, 255])
  382. def test_parse_basic_data(battery):
  383. """Test _parse_basic_data method."""
  384. device = create_device_for_command_testing(SwitchbotModel.LOCK)
  385. basic_data = bytes([0, battery, 1])
  386. result = device._parse_basic_data(basic_data)
  387. assert result["battery"] == battery
  388. assert result["firmware"] == 0.1
  389. @pytest.mark.asyncio
  390. @pytest.mark.parametrize(
  391. "model",
  392. [SwitchbotModel.LOCK_ULTRA, SwitchbotModel.LOCK_ULTRA_MAX, SwitchbotModel.UWB_LOCK],
  393. )
  394. @pytest.mark.parametrize(
  395. ("basic_info", "battery", "firmware"),
  396. [
  397. ("01 4b 28 21 14", 75, 3.3), # Main battery in use.
  398. ("01 85 28 21 14", 40, 3.3), # Backup battery in use.
  399. ("01 f3 28 21 14", 40, 3.3), # Byte 1 must never appear as 243%.
  400. ("01 80 ff 21 14", 255, 3.3), # Report the backup battery byte as received.
  401. ("01 4b 28", 60, 2.1), # Truncated reply: keep the last readings.
  402. ],
  403. )
  404. async def test_lock2_basic_info(model, basic_info, battery, firmware):
  405. device = create_device_for_command_testing(model, SwitchbotLockUltra)
  406. device.update_from_advertisement(
  407. SwitchBotAdvertisement(
  408. device._device.address,
  409. {"data": {"battery": 60, "firmware": 2.1}},
  410. device._device,
  411. -60,
  412. )
  413. )
  414. with (
  415. patch.object(
  416. device, "_get_lock_info", return_value=bytes.fromhex("01 80 00 00 00 00 00")
  417. ),
  418. patch.object(device, "_get_basic_info", return_value=bytes.fromhex(basic_info)),
  419. ):
  420. await device.update()
  421. assert device.get_battery_percent() == battery
  422. assert device.parsed_data["firmware"] == firmware
  423. assert device.get_lock_status() is LockStatus.LOCKED
  424. @pytest.mark.asyncio
  425. @pytest.mark.parametrize(
  426. "model",
  427. [SwitchbotModel.LOCK_ULTRA, SwitchbotModel.LOCK_ULTRA_MAX, SwitchbotModel.UWB_LOCK],
  428. )
  429. async def test_lock2_battery_after_lock(model):
  430. device = create_device_for_command_testing(model, SwitchbotLockUltra)
  431. device.update_from_advertisement(
  432. SwitchBotAdvertisement(
  433. device._device.address,
  434. {"data": {"status": LockStatus.UNLOCKED}},
  435. device._device,
  436. -60,
  437. )
  438. )
  439. with (
  440. patch.object(device, "_enable_notifications", return_value=True),
  441. patch.object(device, "_send_command", return_value=bytes.fromhex("01")),
  442. patch.object(
  443. device, "_get_basic_info", return_value=bytes.fromhex("01 f3 28 21 14")
  444. ),
  445. ):
  446. assert await device.lock()
  447. assert device.get_battery_percent() == 40
  448. assert device.parsed_data["firmware"] == 3.3
  449. @pytest.mark.asyncio
  450. async def test_lock_ultra_max_verifies_encryption_key():
  451. """Lock Ultra Max verifies a valid encryption key."""
  452. lock_data = b"\x00\x80\x00\x00\x00\x00\x00\x00"
  453. basic_data = bytes.fromhex("01 64 01 21 14")
  454. ble_device = generate_ble_device("aa:bb:cc:dd:ee:ff", "any")
  455. with (
  456. patch.object(lock.SwitchbotLock, "_get_lock_info", return_value=lock_data),
  457. patch.object(lock.SwitchbotLock, "_get_basic_info", return_value=basic_data),
  458. ):
  459. assert await SwitchbotLockUltra.verify_encryption_key(
  460. ble_device,
  461. "ff",
  462. "ffffffffffffffffffffffffffffffff",
  463. SwitchbotModel.LOCK_ULTRA_MAX,
  464. )
  465. @pytest.mark.parametrize(
  466. "model",
  467. [
  468. SwitchbotModel.LOCK,
  469. SwitchbotModel.LOCK_LITE,
  470. SwitchbotModel.LOCK_PRO,
  471. SwitchbotModel.LOCK_ULTRA,
  472. SwitchbotModel.LOCK_VISION,
  473. SwitchbotModel.LOCK_VISION_PRO,
  474. SwitchbotModel.LOCK_PRO_WIFI,
  475. ],
  476. )
  477. def test_is_calibrated(model: str):
  478. """Test is_calibrated method."""
  479. device = create_device_for_command_testing(model)
  480. device._get_adv_value = Mock(return_value=True)
  481. assert device.is_calibrated() is True
  482. @pytest.mark.parametrize(
  483. "model",
  484. [
  485. SwitchbotModel.LOCK,
  486. SwitchbotModel.LOCK_LITE,
  487. SwitchbotModel.LOCK_PRO,
  488. SwitchbotModel.LOCK_ULTRA,
  489. SwitchbotModel.LOCK_VISION,
  490. SwitchbotModel.LOCK_VISION_PRO,
  491. SwitchbotModel.LOCK_PRO_WIFI,
  492. ],
  493. )
  494. def test_get_lock_status(model: str):
  495. """Test get_lock_status method."""
  496. device = create_device_for_command_testing(model)
  497. device._get_adv_value = Mock(return_value=LockStatus.LOCKED)
  498. assert device.get_lock_status() == LockStatus.LOCKED
  499. @pytest.mark.parametrize(
  500. "model",
  501. [
  502. SwitchbotModel.LOCK,
  503. SwitchbotModel.LOCK_PRO,
  504. SwitchbotModel.LOCK_ULTRA,
  505. SwitchbotModel.LOCK_VISION_PRO,
  506. SwitchbotModel.LOCK_PRO_WIFI,
  507. ],
  508. )
  509. def test_is_door_open(model: str):
  510. """Test is_door_open method."""
  511. device = create_device_for_command_testing(model)
  512. device._get_adv_value = Mock(return_value=True)
  513. assert device.is_door_open() is True
  514. @pytest.mark.parametrize(
  515. "model",
  516. [
  517. SwitchbotModel.LOCK,
  518. SwitchbotModel.LOCK_PRO,
  519. SwitchbotModel.LOCK_ULTRA,
  520. SwitchbotModel.LOCK_VISION_PRO,
  521. SwitchbotModel.LOCK_PRO_WIFI,
  522. ],
  523. )
  524. def test_is_unclosed_alarm_on(model: str):
  525. """Test is_unclosed_alarm_on method."""
  526. device = create_device_for_command_testing(model)
  527. device._get_adv_value = Mock(return_value=True)
  528. assert device.is_unclosed_alarm_on() is True
  529. @pytest.mark.parametrize(
  530. "model",
  531. [
  532. SwitchbotModel.LOCK,
  533. SwitchbotModel.LOCK_LITE,
  534. SwitchbotModel.LOCK_PRO,
  535. SwitchbotModel.LOCK_ULTRA,
  536. SwitchbotModel.LOCK_VISION,
  537. SwitchbotModel.LOCK_VISION_PRO,
  538. SwitchbotModel.LOCK_PRO_WIFI,
  539. ],
  540. )
  541. def test_is_unlocked_alarm_on(model: str):
  542. """Test is_unlocked_alarm_on method."""
  543. device = create_device_for_command_testing(model)
  544. device._get_adv_value = Mock(return_value=True)
  545. assert device.is_unlocked_alarm_on() is True
  546. @pytest.mark.parametrize(
  547. "model",
  548. [
  549. SwitchbotModel.LOCK,
  550. ],
  551. )
  552. def test_is_auto_lock_paused(model: str):
  553. """Test is_auto_lock_paused method."""
  554. device = create_device_for_command_testing(model)
  555. device._get_adv_value = Mock(return_value=True)
  556. assert device.is_auto_lock_paused() is True
  557. @pytest.mark.parametrize(
  558. "model",
  559. [
  560. SwitchbotModel.LOCK,
  561. SwitchbotModel.LOCK_LITE,
  562. SwitchbotModel.LOCK_PRO,
  563. SwitchbotModel.LOCK_ULTRA,
  564. SwitchbotModel.LOCK_VISION,
  565. SwitchbotModel.LOCK_VISION_PRO,
  566. SwitchbotModel.LOCK_PRO_WIFI,
  567. ],
  568. )
  569. def test_is_night_latch_enabled(model: str):
  570. """Test is_night_latch_enabled method."""
  571. device = create_device_for_command_testing(model)
  572. device._get_adv_value = Mock(return_value=True)
  573. assert device.is_night_latch_enabled() is True
  574. @pytest.mark.asyncio
  575. @pytest.mark.parametrize(
  576. "model",
  577. [
  578. SwitchbotModel.LOCK,
  579. SwitchbotModel.LOCK_LITE,
  580. SwitchbotModel.LOCK_PRO,
  581. SwitchbotModel.LOCK_ULTRA,
  582. SwitchbotModel.LOCK_VISION,
  583. SwitchbotModel.LOCK_VISION_PRO,
  584. SwitchbotModel.LOCK_PRO_WIFI,
  585. ],
  586. )
  587. async def test_get_lock_info(model: str):
  588. """Test _get_lock_info method."""
  589. device = create_device_for_command_testing(model)
  590. expected_data = b"\x01\x00\x80\x00\x00\x00\x00\x00"
  591. with patch.object(device, "_send_command", return_value=expected_data):
  592. result = await device._get_lock_info()
  593. assert result == expected_data
  594. @pytest.mark.asyncio
  595. @pytest.mark.parametrize(
  596. "model",
  597. [
  598. SwitchbotModel.LOCK,
  599. SwitchbotModel.LOCK_LITE,
  600. SwitchbotModel.LOCK_PRO,
  601. SwitchbotModel.LOCK_ULTRA,
  602. SwitchbotModel.LOCK_VISION,
  603. SwitchbotModel.LOCK_VISION_PRO,
  604. SwitchbotModel.LOCK_PRO_WIFI,
  605. ],
  606. )
  607. async def test_get_lock_info_failure(model: str):
  608. """Test _get_lock_info method when command fails."""
  609. device = create_device_for_command_testing(model)
  610. with patch.object(device, "_send_command", return_value=b"\x00\x00"):
  611. result = await device._get_lock_info()
  612. assert result is None
  613. @pytest.mark.asyncio
  614. @pytest.mark.parametrize(
  615. "model",
  616. [
  617. SwitchbotModel.LOCK,
  618. SwitchbotModel.LOCK_LITE,
  619. SwitchbotModel.LOCK_PRO,
  620. SwitchbotModel.LOCK_ULTRA,
  621. SwitchbotModel.LOCK_VISION,
  622. SwitchbotModel.LOCK_VISION_PRO,
  623. SwitchbotModel.LOCK_PRO_WIFI,
  624. ],
  625. )
  626. async def test_enable_notifications(model: str):
  627. """Test _enable_notifications method."""
  628. device = create_device_for_command_testing(model)
  629. with patch.object(device, "_send_command", return_value=b"\x01\x00"):
  630. result = await device._enable_notifications()
  631. assert result is True
  632. @pytest.mark.asyncio
  633. @pytest.mark.parametrize(
  634. "model",
  635. [
  636. SwitchbotModel.LOCK,
  637. SwitchbotModel.LOCK_LITE,
  638. SwitchbotModel.LOCK_PRO,
  639. SwitchbotModel.LOCK_ULTRA,
  640. SwitchbotModel.LOCK_VISION,
  641. SwitchbotModel.LOCK_VISION_PRO,
  642. SwitchbotModel.LOCK_PRO_WIFI,
  643. ],
  644. )
  645. async def test_disable_notifications(model: str):
  646. """Test _disable_notifications method."""
  647. device = create_device_for_command_testing(model)
  648. device._notifications_enabled = True
  649. with patch.object(device, "_send_command", return_value=b"\x01\x00"):
  650. result = await device._disable_notifications()
  651. assert result is True
  652. assert device._notifications_enabled is False
  653. @pytest.mark.asyncio
  654. @pytest.mark.parametrize(
  655. "model",
  656. [
  657. SwitchbotModel.LOCK,
  658. SwitchbotModel.LOCK_LITE,
  659. SwitchbotModel.LOCK_PRO,
  660. SwitchbotModel.LOCK_ULTRA,
  661. SwitchbotModel.LOCK_VISION,
  662. SwitchbotModel.LOCK_VISION_PRO,
  663. SwitchbotModel.LOCK_PRO_WIFI,
  664. ],
  665. )
  666. async def test_disable_notifications_already_disabled(model: str):
  667. """Test _disable_notifications when already disabled."""
  668. device = create_device_for_command_testing(model)
  669. device._notifications_enabled = False
  670. with patch.object(device, "_send_command") as mock_send:
  671. result = await device._disable_notifications()
  672. assert result is True
  673. mock_send.assert_not_called()
  674. @pytest.mark.parametrize(
  675. "model",
  676. [
  677. SwitchbotModel.LOCK,
  678. SwitchbotModel.LOCK_LITE,
  679. SwitchbotModel.LOCK_PRO,
  680. SwitchbotModel.LOCK_ULTRA,
  681. SwitchbotModel.LOCK_VISION,
  682. SwitchbotModel.LOCK_VISION_PRO,
  683. SwitchbotModel.LOCK_PRO_WIFI,
  684. ],
  685. )
  686. def test_notification_handler(model: str):
  687. """Test _notification_handler method."""
  688. device = create_device_for_command_testing(model)
  689. device._notifications_enabled = True
  690. data = bytearray(b"\x0f\x00\x00\x00\x80\x00\x00\x00\x00\x00")
  691. with patch.object(device, "_update_lock_status") as mock_update:
  692. device._notification_handler(0, data)
  693. mock_update.assert_called_once_with(data)
  694. @pytest.mark.parametrize(
  695. "model",
  696. [
  697. SwitchbotModel.LOCK,
  698. SwitchbotModel.LOCK_LITE,
  699. SwitchbotModel.LOCK_PRO,
  700. SwitchbotModel.LOCK_ULTRA,
  701. SwitchbotModel.LOCK_VISION,
  702. SwitchbotModel.LOCK_VISION_PRO,
  703. SwitchbotModel.LOCK_PRO_WIFI,
  704. ],
  705. )
  706. def test_notification_handler_not_enabled(model: str):
  707. """Test _notification_handler when notifications not enabled."""
  708. device = create_device_for_command_testing(model)
  709. device._notifications_enabled = False
  710. data = bytearray(b"\x01\x00\x00\x00\x80\x00\x00\x00\x00\x00")
  711. with (
  712. patch.object(device, "_update_lock_status") as mock_update,
  713. patch.object(
  714. lock.SwitchbotSequenceDevice, "_notification_handler"
  715. ) as mock_super,
  716. ):
  717. device._notification_handler(0, data)
  718. mock_update.assert_not_called()
  719. mock_super.assert_called_once()
  720. @pytest.mark.parametrize(
  721. "model",
  722. [
  723. SwitchbotModel.LOCK,
  724. SwitchbotModel.LOCK_LITE,
  725. SwitchbotModel.LOCK_PRO,
  726. SwitchbotModel.LOCK_ULTRA,
  727. SwitchbotModel.LOCK_VISION,
  728. SwitchbotModel.LOCK_VISION_PRO,
  729. SwitchbotModel.LOCK_PRO_WIFI,
  730. ],
  731. )
  732. def test_notification_handler_during_disconnect(
  733. model: str, caplog: pytest.LogCaptureFixture
  734. ) -> None:
  735. """Test _notification_handler during expected disconnect."""
  736. device = create_device_for_command_testing(model)
  737. device._notifications_enabled = True
  738. device._expected_disconnect = True
  739. data = bytearray(b"\x0f\x00\x00\x00\x80\x00\x00\x00\x00\x00")
  740. with (
  741. patch.object(device, "_update_lock_status") as mock_update,
  742. caplog.at_level(logging.DEBUG),
  743. ):
  744. device._notification_handler(0, data)
  745. # Should not update lock status during disconnect
  746. mock_update.assert_not_called()
  747. # Should log debug message
  748. assert "Ignoring lock notification during expected disconnect" in caplog.text
  749. @pytest.mark.parametrize(
  750. "model",
  751. [
  752. SwitchbotModel.LOCK,
  753. SwitchbotModel.LOCK_LITE,
  754. SwitchbotModel.LOCK_PRO,
  755. SwitchbotModel.LOCK_ULTRA,
  756. SwitchbotModel.LOCK_VISION,
  757. SwitchbotModel.LOCK_VISION_PRO,
  758. SwitchbotModel.LOCK_PRO_WIFI,
  759. ],
  760. )
  761. def test_update_lock_status(model: str):
  762. """Test _update_lock_status method."""
  763. device = create_device_for_command_testing(model)
  764. data = bytearray(b"\x0f\x00\x00\x00\x80\x00\x00\x00\x00\x00")
  765. with (
  766. patch.object(device, "_decrypt", return_value=b"\x80\x00\x00\x00\x00\x00"),
  767. patch.object(device, "_update_parsed_data", return_value=True),
  768. patch.object(device, "_reset_disconnect_timer"),
  769. patch.object(device, "_fire_callbacks"),
  770. ):
  771. device._update_lock_status(data)
  772. @pytest.mark.parametrize(
  773. "model",
  774. [
  775. SwitchbotModel.LOCK_PRO,
  776. SwitchbotModel.LOCK_ULTRA,
  777. SwitchbotModel.LOCK_ULTRA_MAX,
  778. SwitchbotModel.LOCK_PRO_WIFI,
  779. SwitchbotModel.LOCK_NANO,
  780. SwitchbotModel.UWB_LOCK,
  781. ],
  782. )
  783. @pytest.mark.parametrize("status", range(8, 16))
  784. def test_notification_handler_unknown_lock_status(
  785. model: SwitchbotModel, status: int, caplog: pytest.LogCaptureFixture
  786. ) -> None:
  787. """Ignore unknown statuses without updating data or firing callbacks."""
  788. device = create_device_for_command_testing(model)
  789. previous_data = {"status": LockStatus.UNLOCKED, "battery": 95}
  790. device.update_from_advertisement(
  791. SwitchBotAdvertisement(
  792. device._device.address, {"data": previous_data}, device._device, -60
  793. )
  794. )
  795. notification = bytearray(b"\x0f\x00\x00\x00\x01\x02\x03\x04\x05\x06")
  796. decrypted = bytes([0x80 | status << 3, 0, 0, 0, 0, 0])
  797. with (
  798. patch.object(
  799. device, "_decrypt", side_effect=[decrypted, b"\x80\x00\x00\x00\x00\x00"]
  800. ),
  801. patch.object(
  802. device, "_update_parsed_data", wraps=device._update_parsed_data
  803. ) as update,
  804. patch.object(device, "_reset_disconnect_timer") as reset_timer,
  805. patch.object(device, "_fire_callbacks") as fire_callbacks,
  806. caplog.at_level(logging.DEBUG),
  807. ):
  808. device._notification_handler(0, notification)
  809. update.assert_not_called()
  810. reset_timer.assert_not_called()
  811. fire_callbacks.assert_not_called()
  812. assert device.parsed_data == previous_data
  813. assert f"Unknown lock status {status}" in caplog.text
  814. assert decrypted.hex() in caplog.text
  815. assert notification.hex() in caplog.text
  816. device._notification_handler(0, notification)
  817. update.assert_called_once()
  818. assert update.call_args.args[0]["status"] is LockStatus.LOCKED
  819. assert device.get_lock_status() is LockStatus.LOCKED
  820. assert device.get_battery_percent() == 95
  821. reset_timer.assert_called_once()
  822. fire_callbacks.assert_called_once()
  823. @pytest.mark.parametrize(
  824. ("model", "data", "expected"),
  825. [
  826. (
  827. SwitchbotModel.LOCK,
  828. b"\x80\x00\x00\x00\x00\x00",
  829. {
  830. "calibration": True,
  831. "status": LockStatus.LOCKED, # (0x80 & 0b01110000) >> 4 = 0 = LOCKED
  832. "door_open": False,
  833. "unclosed_alarm": False,
  834. "unlocked_alarm": False,
  835. },
  836. ),
  837. (
  838. SwitchbotModel.LOCK_LITE,
  839. b"\x80\x00\x00\x00\x00\x00",
  840. {
  841. "calibration": True,
  842. "status": LockStatus.LOCKED, # (0x80 & 0b01110000) >> 4 = 0 = LOCKED
  843. "unlocked_alarm": False,
  844. },
  845. ),
  846. (
  847. SwitchbotModel.LOCK_PRO,
  848. b"\x80\x00\x00\x00\x00\x00",
  849. {
  850. "calibration": True,
  851. "status": LockStatus.LOCKED, # (0x80 & 0b01111000) >> 3 = 0 = LOCKED
  852. "door_open": False,
  853. "unclosed_alarm": False,
  854. "unlocked_alarm": False,
  855. },
  856. ),
  857. (
  858. SwitchbotModel.LOCK_ULTRA,
  859. b"\x88\x10\x00\x00\x00\xc0",
  860. {
  861. "calibration": True,
  862. "status": LockStatus.UNLOCKED, # (0x88 & 0b01111000) >> 3 = 0x08 >> 3 = 1 = UNLOCKED
  863. "door_open": True,
  864. "unclosed_alarm": True,
  865. "unlocked_alarm": True,
  866. "half_lock_calibration": False,
  867. },
  868. ),
  869. (
  870. SwitchbotModel.LOCK_VISION,
  871. b"\x80\x00\x00\x00\x00\x00",
  872. {
  873. "calibration": True,
  874. "status": LockStatus.LOCKED, # (0x80 & 0b01110000) >> 4 = 0 = LOCKED
  875. "unlocked_alarm": False,
  876. },
  877. ),
  878. (
  879. SwitchbotModel.LOCK_VISION_PRO,
  880. b"\x80\x00\x00\x00\x00\x00",
  881. {
  882. "calibration": True,
  883. "status": LockStatus.LOCKED, # (0x80 & 0b01111000) >> 3 = 0 = LOCKED
  884. "door_open": False,
  885. "unclosed_alarm": False,
  886. "unlocked_alarm": False,
  887. },
  888. ),
  889. (
  890. SwitchbotModel.LOCK_PRO_WIFI,
  891. b"\x80\x00\x00\x00\x00\x00",
  892. {
  893. "calibration": True,
  894. "status": LockStatus.LOCKED, # (0x80 & 0b01111000) >> 3 = 0 = LOCKED
  895. "door_open": False,
  896. "unclosed_alarm": False,
  897. "unlocked_alarm": False,
  898. },
  899. ),
  900. ],
  901. )
  902. def test_parse_lock_data(model: str, data: bytes, expected: dict):
  903. """Test _parse_lock_data static method."""
  904. result = lock.SwitchbotLock._parse_lock_data(data, model)
  905. assert result == expected
  906. @pytest.mark.parametrize(
  907. ("model", "data", "expected"),
  908. [
  909. # Test LOCK with different status bits and flags
  910. (
  911. SwitchbotModel.LOCK,
  912. b"\x94\x00\x00\x00\x00\x00", # Unlocked status (0x10 >> 4 = 1) with door open
  913. {
  914. "calibration": True,
  915. "status": LockStatus.UNLOCKED,
  916. "door_open": True,
  917. "unclosed_alarm": False,
  918. "unlocked_alarm": False,
  919. },
  920. ),
  921. # Test LOCK_LITE without door_open field
  922. (
  923. SwitchbotModel.LOCK_LITE,
  924. b"\x90\x10\x00\x00\x00\x00", # Unlocked with unlocked alarm
  925. {
  926. "calibration": True,
  927. "status": LockStatus.UNLOCKED,
  928. "unlocked_alarm": True,
  929. },
  930. ),
  931. # Test LOCK_PRO with new bit positions
  932. (
  933. SwitchbotModel.LOCK_PRO,
  934. b"\x90\x10\x00\x00\x00\xc0", # New format: status bits 3-6, door open bit 4 of byte 1
  935. {
  936. "calibration": True,
  937. "status": LockStatus.LOCKING, # (0x90 & 0b01111000) >> 3 = 0x10 >> 3 = 2 (LOCKING)
  938. "door_open": True, # bit 4 of byte 1 (0x10)
  939. "unclosed_alarm": True, # bit 7 of byte 5 (0xc0)
  940. "unlocked_alarm": True, # bit 6 of byte 5 (0xc0)
  941. },
  942. ),
  943. # Test LOCK_ULTRA with same format as PRO
  944. (
  945. SwitchbotModel.LOCK_ULTRA,
  946. b"\x88\x00\x00\x00\x00\x40", # Unlocked with unlocked alarm only
  947. {
  948. "calibration": True,
  949. "status": LockStatus.UNLOCKED, # (0x88 & 0b01111000) >> 3 = 0x08 >> 3 = 1
  950. "door_open": False,
  951. "unclosed_alarm": False,
  952. "unlocked_alarm": True, # bit 6 of byte 5
  953. "half_lock_calibration": False,
  954. },
  955. ),
  956. (
  957. SwitchbotModel.LOCK_PRO_WIFI,
  958. b"\x90\x10\x00\x00\x00\xc0", # New format: status bits 3-6, door open bit 4 of byte 1
  959. {
  960. "calibration": True,
  961. "status": LockStatus.LOCKING, # (0x90 & 0b01111000) >> 3 = 0x10 >> 3 = 2 (LOCKING)
  962. "door_open": True, # bit 4 of byte 1 (0x10)
  963. "unclosed_alarm": True, # bit 7 of byte 5 (0xc0)
  964. "unlocked_alarm": True, # bit 6 of byte 5 (0xc0)
  965. },
  966. ),
  967. ],
  968. )
  969. def test_parse_lock_data_new_formats(model: str, data: bytes, expected: dict):
  970. """Test _parse_lock_data with new format changes."""
  971. result = lock.SwitchbotLock._parse_lock_data(data, model)
  972. assert result == expected
  973. @pytest.mark.asyncio
  974. @pytest.mark.parametrize(
  975. "model",
  976. [
  977. SwitchbotModel.LOCK,
  978. SwitchbotModel.LOCK_LITE,
  979. SwitchbotModel.LOCK_PRO,
  980. SwitchbotModel.LOCK_ULTRA,
  981. SwitchbotModel.LOCK_VISION,
  982. SwitchbotModel.LOCK_VISION_PRO,
  983. SwitchbotModel.LOCK_PRO_WIFI,
  984. ],
  985. )
  986. async def test_lock_with_update(model: str):
  987. """Test lock method with status update."""
  988. device = create_device_for_command_testing(model)
  989. device._get_adv_value = Mock(side_effect=[None, LockStatus.UNLOCKED])
  990. with (
  991. patch.object(device, "update", new_callable=AsyncMock),
  992. patch.object(device, "_send_command", return_value=b"\x01\x00"),
  993. patch.object(device, "_enable_notifications", return_value=True),
  994. patch.object(device, "_get_basic_info", return_value=b"\x00\x64\x01"),
  995. ):
  996. result = await device.lock()
  997. assert result is True
  998. def test_is_half_lock_calibrated():
  999. """Test is_half_lock_calibrated method."""
  1000. device = create_device_for_command_testing(SwitchbotModel.LOCK_ULTRA)
  1001. device._get_adv_value = Mock(return_value=True)
  1002. assert device.is_half_lock_calibrated() is True
  1003. device._get_adv_value = Mock(return_value=False)
  1004. assert device.is_half_lock_calibrated() is False
  1005. @pytest.mark.asyncio
  1006. async def test_half_lock_calibrated():
  1007. """Test half_lock succeeds when calibrated."""
  1008. device = create_device_for_command_testing(SwitchbotModel.LOCK_ULTRA)
  1009. device._get_adv_value = Mock(side_effect=[True, LockStatus.LOCKED])
  1010. with (
  1011. patch.object(device, "_send_command", return_value=b"\x01\x00"),
  1012. patch.object(device, "_enable_notifications", return_value=True),
  1013. patch.object(device, "_get_basic_info", return_value=b"\x01\x64\x01"),
  1014. ):
  1015. result = await device.half_lock()
  1016. assert result is True
  1017. @pytest.mark.asyncio
  1018. async def test_half_lock_not_calibrated():
  1019. """Test half_lock raises SwitchbotOperationError when not calibrated."""
  1020. device = create_device_for_command_testing(SwitchbotModel.LOCK_ULTRA)
  1021. device._get_adv_value = Mock(return_value=False)
  1022. with pytest.raises(SwitchbotOperationError, match="not calibrated"):
  1023. await device.half_lock()
  1024. @pytest.mark.asyncio
  1025. @pytest.mark.parametrize(
  1026. "model",
  1027. [
  1028. SwitchbotModel.LOCK,
  1029. SwitchbotModel.LOCK_LITE,
  1030. SwitchbotModel.LOCK_PRO,
  1031. SwitchbotModel.LOCK_ULTRA_MAX,
  1032. SwitchbotModel.UWB_LOCK,
  1033. SwitchbotModel.LOCK_NANO,
  1034. SwitchbotModel.LOCK_VISION,
  1035. SwitchbotModel.LOCK_VISION_PRO,
  1036. SwitchbotModel.LOCK_PRO_WIFI,
  1037. ],
  1038. )
  1039. async def test_half_lock_unsupported_model(model: str):
  1040. """Test half_lock raises SwitchbotOperationError on unsupported models."""
  1041. device = create_device_for_command_testing(model)
  1042. with pytest.raises(SwitchbotOperationError, match="not supported"):
  1043. await device.half_lock()
  1044. @pytest.mark.asyncio
  1045. async def test_half_lock():
  1046. """Test half_lock method."""
  1047. device = create_device_for_command_testing(SwitchbotModel.LOCK_ULTRA)
  1048. device._get_adv_value = Mock(side_effect=[True, LockStatus.LOCKED])
  1049. with (
  1050. patch.object(device, "_send_command", return_value=b"\x01\x00") as mock_send,
  1051. patch.object(device, "_enable_notifications", return_value=True),
  1052. patch.object(device, "_get_basic_info", return_value=b"\x01\x64\x01"),
  1053. ):
  1054. result = await device.half_lock()
  1055. assert result is True
  1056. mock_send.assert_awaited_once_with(
  1057. lock.COMMAND_HALF_LOCK[SwitchbotModel.LOCK_ULTRA]
  1058. )
  1059. @pytest.mark.asyncio
  1060. @pytest.mark.parametrize(
  1061. ("model", "status"),
  1062. [
  1063. (SwitchbotModel.LOCK, LockStatus.LOCKED),
  1064. (SwitchbotModel.LOCK_LITE, LockStatus.LOCKING),
  1065. (SwitchbotModel.LOCK_PRO, LockStatus.LOCKED),
  1066. (SwitchbotModel.LOCK_ULTRA, LockStatus.LOCKING),
  1067. (SwitchbotModel.LOCK_VISION, LockStatus.LOCKED),
  1068. (SwitchbotModel.LOCK_VISION_PRO, LockStatus.LOCKED),
  1069. (SwitchbotModel.LOCK_PRO_WIFI, LockStatus.LOCKED),
  1070. ],
  1071. )
  1072. async def test_lock_already_locked(model: str, status: LockStatus):
  1073. """Test lock method when already locked."""
  1074. device = create_device_for_command_testing(model)
  1075. device._get_adv_value = Mock(return_value=status)
  1076. with patch.object(device, "_send_command") as mock_send:
  1077. result = await device.lock()
  1078. assert result is True
  1079. mock_send.assert_not_called()
  1080. @pytest.mark.asyncio
  1081. @pytest.mark.parametrize(
  1082. "model",
  1083. [
  1084. SwitchbotModel.LOCK,
  1085. SwitchbotModel.LOCK_LITE,
  1086. SwitchbotModel.LOCK_PRO,
  1087. SwitchbotModel.LOCK_ULTRA,
  1088. SwitchbotModel.LOCK_VISION,
  1089. SwitchbotModel.LOCK_VISION_PRO,
  1090. SwitchbotModel.LOCK_PRO_WIFI,
  1091. ],
  1092. )
  1093. async def test_lock_with_invalid_basic_data(model: str):
  1094. """Test lock method with invalid basic data."""
  1095. device = create_device_for_command_testing(model)
  1096. device._get_adv_value = Mock(return_value=LockStatus.UNLOCKED)
  1097. with (
  1098. patch.object(device, "_send_command", return_value=b"\x01\x00"),
  1099. patch.object(device, "_enable_notifications", return_value=True),
  1100. patch.object(device, "_get_basic_info", return_value=b"\x00"),
  1101. ):
  1102. result = await device.lock()
  1103. assert result is True
  1104. @pytest.mark.asyncio
  1105. async def test_get_quick_key():
  1106. """Reading the Quick Key parses the config byte (Lock Ultra)."""
  1107. device = create_device_for_command_testing(SwitchbotModel.LOCK_ULTRA)
  1108. # 0xca = enabled, single press, Lock & Unlock
  1109. with patch.object(
  1110. device, "_send_command", return_value=b"\x01\xca\x00\x00\x00\x80"
  1111. ) as mock_send_command:
  1112. result = await device.get_quick_key()
  1113. mock_send_command.assert_any_call(
  1114. key="570f4f0401",
  1115. retry=device._retry_count,
  1116. )
  1117. assert result == {
  1118. "raw": 0xCA,
  1119. "light": True,
  1120. "sound": True,
  1121. "manual_unlock_linkage": False,
  1122. "enabled": True,
  1123. "double_press": False,
  1124. "function": QuickKeyFunction.LOCK_AND_UNLOCK,
  1125. "motor_speed": 0,
  1126. }
  1127. @pytest.mark.asyncio
  1128. async def test_get_quick_key_failure():
  1129. """A non-success status returns None."""
  1130. device = create_device_for_command_testing(SwitchbotModel.LOCK_ULTRA)
  1131. with patch.object(device, "_send_command", return_value=b"\x00"):
  1132. assert await device.get_quick_key() is None
  1133. @pytest.mark.asyncio
  1134. async def test_get_quick_key_zero_properties():
  1135. """A zero property byte means disabled, single press, and lock only."""
  1136. device = create_device_for_command_testing(SwitchbotModel.LOCK_ULTRA)
  1137. with patch.object(device, "_send_command", return_value=b"\x01\x00"):
  1138. assert await device.get_quick_key() == {
  1139. "raw": 0,
  1140. "light": False,
  1141. "sound": False,
  1142. "manual_unlock_linkage": False,
  1143. "enabled": False,
  1144. "double_press": False,
  1145. "function": QuickKeyFunction.LOCK_ONLY,
  1146. "motor_speed": None,
  1147. }
  1148. @pytest.mark.asyncio
  1149. async def test_set_quick_key_function_update_flag():
  1150. """Bit 1 selects the entire two-bit function field for writing."""
  1151. device = create_device_for_command_testing(SwitchbotModel.LOCK_ULTRA)
  1152. with patch.object(
  1153. device,
  1154. "_send_command",
  1155. return_value=b"\x01\xc9", # echo 0xc9 = Unlock Only
  1156. ) as mock_send_command:
  1157. result = await device.set_quick_key(function=QuickKeyFunction.UNLOCK_ONLY)
  1158. mock_send_command.assert_awaited_once_with(
  1159. key="570f4e0401000201ff", retry=device._retry_count
  1160. )
  1161. assert result is True
  1162. @pytest.mark.asyncio
  1163. async def test_set_quick_key_multiple_fields():
  1164. """Update all Quick Key fields while keeping the default target and speed."""
  1165. device = create_device_for_command_testing(SwitchbotModel.LOCK_ULTRA)
  1166. with patch.object(
  1167. device, "_send_command", return_value=b"\x01\xce"
  1168. ) as mock_send_command:
  1169. result = await device.set_quick_key(
  1170. enabled=True, double_press=True, function=QuickKeyFunction.LOCK_AND_UNLOCK
  1171. )
  1172. mock_send_command.assert_awaited_once_with(
  1173. key="570f4e0401000e0eff", retry=device._retry_count
  1174. )
  1175. assert result is True
  1176. @pytest.mark.asyncio
  1177. @pytest.mark.parametrize(
  1178. ("kwargs", "flags_and_value"),
  1179. [
  1180. ({"enabled": False}, "0800"),
  1181. ({"double_press": False}, "0400"),
  1182. ({"function": QuickKeyFunction.LOCK_ONLY}, "0200"),
  1183. (
  1184. {
  1185. "enabled": False,
  1186. "double_press": False,
  1187. "function": QuickKeyFunction.LOCK_ONLY,
  1188. },
  1189. "0e00",
  1190. ),
  1191. ],
  1192. )
  1193. async def test_set_quick_key_false_and_zero_values(
  1194. kwargs: dict[str, Any], flags_and_value: str
  1195. ):
  1196. """Explicit false and zero values still select their fields for writing."""
  1197. device = create_device_for_command_testing(SwitchbotModel.LOCK_ULTRA)
  1198. with patch.object(
  1199. device, "_send_command", return_value=b"\x01\xc0"
  1200. ) as mock_send_command:
  1201. result = await device.set_quick_key(**kwargs)
  1202. mock_send_command.assert_awaited_once_with(
  1203. key=f"570f4e040100{flags_and_value}ff", retry=device._retry_count
  1204. )
  1205. assert result is True
  1206. @pytest.mark.asyncio
  1207. async def test_set_quick_key_requires_a_field():
  1208. """Calling with nothing to change raises ValueError."""
  1209. device = create_device_for_command_testing(SwitchbotModel.LOCK_ULTRA)
  1210. with pytest.raises(ValueError, match="at least one setting"):
  1211. await device.set_quick_key()
  1212. @pytest.mark.asyncio
  1213. async def test_quick_key_unsupported_model():
  1214. """Quick Key is Lock Ultra only; other models raise."""
  1215. device = create_device_for_command_testing(SwitchbotModel.LOCK)
  1216. with pytest.raises(SwitchbotOperationError):
  1217. await device.get_quick_key()
  1218. with pytest.raises(SwitchbotOperationError):
  1219. await device.set_quick_key(enabled=True)
  1220. @pytest.mark.asyncio
  1221. async def test_get_quick_key_short_response():
  1222. """A success status but a truncated payload returns None."""
  1223. device = create_device_for_command_testing(SwitchbotModel.LOCK_ULTRA)
  1224. with patch.object(device, "_send_command", return_value=b"\x01"):
  1225. assert await device.get_quick_key() is None
  1226. @pytest.mark.asyncio
  1227. async def test_get_quick_key_unknown_function():
  1228. """An undefined 2-bit function value keeps the bits that are unambiguous."""
  1229. device = create_device_for_command_testing(SwitchbotModel.LOCK_ULTRA)
  1230. # 0xcb = enabled, single press, function bits 0b11 (undefined)
  1231. with patch.object(device, "_send_command", return_value=b"\x01\xcb"):
  1232. assert await device.get_quick_key() == {
  1233. "raw": 0xCB,
  1234. "light": True,
  1235. "sound": True,
  1236. "manual_unlock_linkage": False,
  1237. "enabled": True,
  1238. "double_press": False,
  1239. "function": None,
  1240. "motor_speed": None,
  1241. }
  1242. @pytest.mark.asyncio
  1243. @pytest.mark.parametrize(
  1244. ("properties", "light", "sound"),
  1245. [
  1246. (0x0A, False, False),
  1247. (0x4A, False, True),
  1248. (0x8A, True, False),
  1249. (0xCA, True, True),
  1250. ],
  1251. )
  1252. async def test_get_quick_key_light_and_sound_settings(
  1253. properties: int, light: bool, sound: bool
  1254. ):
  1255. """Read light and sound independently of the original Quick Key fields."""
  1256. device = create_device_for_command_testing(SwitchbotModel.LOCK_ULTRA)
  1257. with patch.object(
  1258. device, "_send_command", return_value=bytes([1, properties, 0, 0, 0, 0])
  1259. ):
  1260. assert await device.get_quick_key() == {
  1261. "raw": properties,
  1262. "light": light,
  1263. "sound": sound,
  1264. "manual_unlock_linkage": False,
  1265. "enabled": True,
  1266. "double_press": False,
  1267. "function": QuickKeyFunction.LOCK_AND_UNLOCK,
  1268. "motor_speed": 0,
  1269. }
  1270. @pytest.mark.asyncio
  1271. @pytest.mark.parametrize(
  1272. ("response", "expected"),
  1273. [
  1274. (b"\x01", False),
  1275. (b"\x06", False),
  1276. (b"\x01\x08", True),
  1277. (b"\x06\x08", True),
  1278. (b"\x01\x00", False),
  1279. (b"\x06\x00", False),
  1280. (b"\x00", False),
  1281. (b"\x02", False),
  1282. (b"\x03", False),
  1283. (b"\x05", False),
  1284. ],
  1285. )
  1286. async def test_set_quick_key_command_status(response: bytes, expected: bool):
  1287. """Require a successful status and matching config without another read."""
  1288. device = create_device_for_command_testing(SwitchbotModel.LOCK_ULTRA)
  1289. with patch.object(
  1290. device, "_send_command", return_value=response
  1291. ) as mock_send_command:
  1292. assert await device.set_quick_key(enabled=True) is expected
  1293. mock_send_command.assert_awaited_once_with(
  1294. key="570f4e0401000808ff", retry=device._retry_count
  1295. )
  1296. @pytest.mark.asyncio
  1297. async def test_get_quick_key_manual_unlock_linkage_and_motor_speed():
  1298. """Read primary properties and speed without using the secondary values."""
  1299. device = create_device_for_command_testing(SwitchbotModel.LOCK_ULTRA)
  1300. with patch.object(
  1301. device, "_send_command", return_value=bytes([1, 0xD9, 0xFF, 2, 0, 0])
  1302. ):
  1303. assert await device.get_quick_key() == {
  1304. "raw": 0xD9,
  1305. "light": True,
  1306. "sound": True,
  1307. "manual_unlock_linkage": True,
  1308. "enabled": True,
  1309. "double_press": False,
  1310. "function": QuickKeyFunction.UNLOCK_ONLY,
  1311. "motor_speed": 2,
  1312. }
  1313. @pytest.mark.asyncio
  1314. @pytest.mark.parametrize(
  1315. ("kwargs", "command", "config"),
  1316. [
  1317. ({"light": True}, "570f4e0401008080ff", 0xCA),
  1318. ({"light": False}, "570f4e0401008000ff", 0x4A),
  1319. ({"sound": True}, "570f4e0401004040ff", 0xCA),
  1320. ({"sound": False}, "570f4e0401004000ff", 0x8A),
  1321. ({"manual_unlock_linkage": True}, "570f4e0401001010ff", 0xDA),
  1322. ({"manual_unlock_linkage": False}, "570f4e0401001000ff", 0xCA),
  1323. ],
  1324. )
  1325. async def test_set_quick_key_independent_properties(
  1326. kwargs: dict[str, bool], command: str, config: int
  1327. ):
  1328. """Each basic property can be changed while retaining the Quick Key fields."""
  1329. device = create_device_for_command_testing(SwitchbotModel.LOCK_ULTRA)
  1330. with patch.object(
  1331. device, "_send_command", return_value=bytes([1, config])
  1332. ) as mock_send_command:
  1333. assert await device.set_quick_key(**kwargs) is True
  1334. mock_send_command.assert_awaited_once_with(key=command, retry=device._retry_count)
  1335. @pytest.mark.asyncio
  1336. @pytest.mark.parametrize(
  1337. ("kwargs", "command", "config"),
  1338. [
  1339. (
  1340. {
  1341. "light": True,
  1342. "sound": False,
  1343. "manual_unlock_linkage": True,
  1344. "enabled": False,
  1345. "double_press": True,
  1346. "function": QuickKeyFunction.UNLOCK_ONLY,
  1347. },
  1348. "570f4e040100de95ff",
  1349. 0x95,
  1350. ),
  1351. (
  1352. {
  1353. "light": False,
  1354. "sound": False,
  1355. "manual_unlock_linkage": False,
  1356. "enabled": False,
  1357. "double_press": False,
  1358. "function": QuickKeyFunction.LOCK_ONLY,
  1359. },
  1360. "570f4e040100de00ff",
  1361. 0x20,
  1362. ),
  1363. ],
  1364. )
  1365. async def test_set_quick_key_combines_all_properties(
  1366. kwargs: dict[str, Any], command: str, config: int
  1367. ):
  1368. """Combine all writable config fields without selecting reserved bits."""
  1369. device = create_device_for_command_testing(SwitchbotModel.LOCK_ULTRA)
  1370. with patch.object(
  1371. device, "_send_command", return_value=bytes([1, config])
  1372. ) as mock_send_command:
  1373. assert await device.set_quick_key(**kwargs) is True
  1374. mock_send_command.assert_awaited_once_with(key=command, retry=device._retry_count)
  1375. @pytest.mark.asyncio
  1376. @pytest.mark.parametrize("motor_speed", [0, 1, 2])
  1377. async def test_set_quick_key_motor_speed(motor_speed: int):
  1378. """Change speed alone with a single write command."""
  1379. device = create_device_for_command_testing(SwitchbotModel.LOCK_ULTRA)
  1380. with patch.object(
  1381. device,
  1382. "_send_command",
  1383. return_value=b"\x01\xca",
  1384. ) as mock_send_command:
  1385. assert await device.set_quick_key(motor_speed=motor_speed) is True
  1386. mock_send_command.assert_awaited_once_with(
  1387. key=f"570f4e0401000000{motor_speed:02x}", retry=device._retry_count
  1388. )
  1389. @pytest.mark.asyncio
  1390. async def test_set_quick_key_motor_speed_with_other_properties():
  1391. """Write speed and properties together without an additional read."""
  1392. device = create_device_for_command_testing(SwitchbotModel.LOCK_ULTRA)
  1393. with patch.object(
  1394. device,
  1395. "_send_command",
  1396. return_value=b"\x01\x5d",
  1397. ) as mock_send_command:
  1398. assert (
  1399. await device.set_quick_key(
  1400. light=False,
  1401. sound=True,
  1402. manual_unlock_linkage=True,
  1403. enabled=True,
  1404. double_press=True,
  1405. function=QuickKeyFunction.UNLOCK_ONLY,
  1406. motor_speed=2,
  1407. )
  1408. is True
  1409. )
  1410. mock_send_command.assert_awaited_once_with(
  1411. key="570f4e040100de5d02", retry=device._retry_count
  1412. )
  1413. @pytest.mark.asyncio
  1414. @pytest.mark.parametrize("motor_speed", [-1, 3, 0x100])
  1415. async def test_set_quick_key_invalid_motor_speed(motor_speed: int):
  1416. """Invalid speeds fail before Bluetooth commands are sent."""
  1417. device = create_device_for_command_testing(SwitchbotModel.LOCK_ULTRA)
  1418. with (
  1419. patch.object(device, "_send_command") as mock_send_command,
  1420. pytest.raises(ValueError, match="motor_speed must be"),
  1421. ):
  1422. await device.set_quick_key(motor_speed=motor_speed)
  1423. mock_send_command.assert_not_called()
  1424. @pytest.mark.asyncio
  1425. async def test_set_quick_key_motor_speed_keep():
  1426. """Explicit 0xFF preserves speed without an additional read."""
  1427. device = create_device_for_command_testing(SwitchbotModel.LOCK_ULTRA)
  1428. with patch.object(
  1429. device, "_send_command", return_value=b"\x01\xca"
  1430. ) as mock_send_command:
  1431. assert await device.set_quick_key(light=True, motor_speed=0xFF) is True
  1432. mock_send_command.assert_awaited_once_with(
  1433. key="570f4e0401008080ff", retry=device._retry_count
  1434. )
  1435. @pytest.mark.asyncio
  1436. @pytest.mark.parametrize(
  1437. ("kwargs", "config", "reported"),
  1438. [
  1439. ({"light": True}, 0x00, False),
  1440. ({"light": False}, 0x80, True),
  1441. ({"sound": True}, 0x00, False),
  1442. ({"manual_unlock_linkage": True}, 0x00, False),
  1443. ({"enabled": False}, 0x08, True),
  1444. ({"double_press": True}, 0x00, False),
  1445. ({"function": QuickKeyFunction.LOCK_ONLY}, 0x01, QuickKeyFunction.UNLOCK_ONLY),
  1446. ({"function": QuickKeyFunction.UNLOCK_ONLY}, 0x00, QuickKeyFunction.LOCK_ONLY),
  1447. ({"function": QuickKeyFunction.LOCK_AND_UNLOCK}, 0x03, None),
  1448. ],
  1449. )
  1450. async def test_set_quick_key_config_mismatch(
  1451. kwargs: dict[str, Any],
  1452. config: int,
  1453. reported: bool | QuickKeyFunction | None,
  1454. caplog: pytest.LogCaptureFixture,
  1455. ):
  1456. """Identify the rejected field, requested value, and reported value."""
  1457. device = create_device_for_command_testing(SwitchbotModel.LOCK_ULTRA)
  1458. with patch.object(
  1459. device, "_send_command", return_value=bytes([1, config])
  1460. ) as mock_send_command:
  1461. assert await device.set_quick_key(**kwargs) is False
  1462. mock_send_command.assert_awaited_once()
  1463. setting, expected = next(iter(kwargs.items()))
  1464. assert (
  1465. f"Quick Key {setting} was not applied "
  1466. f"(requested={expected}, reported={reported}, config={config:#04x})"
  1467. ) in caplog.text
  1468. @pytest.mark.asyncio
  1469. async def test_set_quick_key_multiple_config_mismatches(
  1470. caplog: pytest.LogCaptureFixture,
  1471. ):
  1472. """Report every mismatching field in a combined write."""
  1473. device = create_device_for_command_testing(SwitchbotModel.LOCK_ULTRA)
  1474. with patch.object(device, "_send_command", return_value=b"\x01\x00"):
  1475. assert (
  1476. await device.set_quick_key(
  1477. light=True,
  1478. sound=True,
  1479. manual_unlock_linkage=True,
  1480. enabled=True,
  1481. double_press=True,
  1482. function=QuickKeyFunction.UNLOCK_ONLY,
  1483. )
  1484. is False
  1485. )
  1486. messages = [
  1487. record.message
  1488. for record in caplog.records
  1489. if "was not applied" in record.message
  1490. ]
  1491. assert len(messages) == 6
  1492. for setting in (
  1493. "light",
  1494. "sound",
  1495. "manual_unlock_linkage",
  1496. "enabled",
  1497. "double_press",
  1498. "function",
  1499. ):
  1500. assert any(
  1501. f"Quick Key {setting} was not applied" in message for message in messages
  1502. )
  1503. @pytest.mark.asyncio
  1504. @pytest.mark.parametrize("status", [0x00, 0x02, 0x03, 0x04, 0x05, 0x09, 0x0E])
  1505. async def test_set_quick_key_failed_status_logs_code(
  1506. status: int, caplog: pytest.LogCaptureFixture
  1507. ):
  1508. """Keep the device status code in diagnostics for rejected commands."""
  1509. device = create_device_for_command_testing(SwitchbotModel.LOCK_ULTRA)
  1510. with patch.object(device, "_send_command", return_value=bytes([status])):
  1511. assert await device.set_quick_key(enabled=True) is False
  1512. assert (
  1513. f"Quick Key command failed (status={status:#04x}, response={status:02x})"
  1514. in caplog.text
  1515. )
  1516. @pytest.mark.asyncio
  1517. @pytest.mark.parametrize("status", [0x01, 0x06])
  1518. async def test_set_quick_key_missing_config_logs_status(
  1519. status: int, caplog: pytest.LogCaptureFixture
  1520. ):
  1521. """Distinguish a missing config from a rejected command."""
  1522. device = create_device_for_command_testing(SwitchbotModel.LOCK_ULTRA)
  1523. with patch.object(device, "_send_command", return_value=bytes([status])):
  1524. assert await device.set_quick_key(enabled=True) is False
  1525. assert (
  1526. f"Quick Key write response is missing config (status={status:#04x}, response={status:02x})"
  1527. ) in caplog.text
  1528. @pytest.mark.asyncio
  1529. @pytest.mark.parametrize("response", [None, b""])
  1530. async def test_set_quick_key_absent_response_raises(response: bytes | None):
  1531. """Preserve the existing operation error for an absent response."""
  1532. device = create_device_for_command_testing(SwitchbotModel.LOCK_ULTRA)
  1533. with (
  1534. patch.object(device, "_send_command", return_value=response),
  1535. pytest.raises(SwitchbotOperationError, match="Sending command failed"),
  1536. ):
  1537. await device.set_quick_key(enabled=True)