File: test_camera_functions.py

package info (click to toggle)
blinkpy 0.25.3-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 600 kB
  • sloc: python: 6,179; sh: 25; makefile: 2
file content (384 lines) | stat: -rw-r--r-- 15,576 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
"""
Test all camera attributes.

Tests the camera initialization and attributes of
individual BlinkCamera instantiations once the
Blink system is set up.
"""

import datetime
from unittest import mock
from unittest import IsolatedAsyncioTestCase
from blinkpy.blinkpy import Blink
from blinkpy.helpers.util import BlinkURLHandler
from blinkpy.sync_module import BlinkSyncModule
from blinkpy.camera import BlinkCamera, BlinkCameraMini, BlinkDoorbell
import tests.mock_responses as mresp

CONFIG = {
    "name": "new",
    "id": 1234,
    "network_id": 5678,
    "serial": "12345678",
    "enabled": False,
    "battery_state": "ok",
    "battery_voltage": 163,
    "wifi_strength": -38,
    "signals": {"lfr": 5, "wifi": 4, "battery": 3, "temp": 68},
    "thumbnail": "/thumb",
}


@mock.patch("blinkpy.auth.Auth.query", return_value={})
class TestBlinkCameraSetup(IsolatedAsyncioTestCase):
    """Test the Blink class in blinkpy."""

    def setUp(self):
        """Set up Blink module."""
        self.blink = Blink(session=mock.AsyncMock())
        self.blink.urls = BlinkURLHandler("test")
        self.blink.sync["test"] = BlinkSyncModule(self.blink, "test", 1234, [])
        self.camera = BlinkCamera(self.blink.sync["test"])
        self.camera.name = "foobar"
        self.blink.sync["test"].cameras["foobar"] = self.camera

    def tearDown(self):
        """Clean up after test."""
        self.blink = None
        self.camera = None

    async def test_camera_update(self, mock_resp):
        """Test that we can properly update camera properties."""
        self.camera.last_record = ["1"]
        self.camera.sync.last_records = {
            "new": [{"clip": "/test.mp4", "time": "1970-01-01T00:00:00"}]
        }
        mock_resp.side_effect = [
            {"temp": 71},
            mresp.MockResponse({"test": 200}, 200, raw_data="test"),
            mresp.MockResponse({"foobar": 200}, 200, raw_data="foobar"),
        ]
        self.assertIsNone(self.camera.image_from_cache)

        await self.camera.update(CONFIG, expire_clips=False)
        self.assertEqual(self.camera.name, "new")
        self.assertEqual(self.camera.camera_id, "1234")
        self.assertEqual(self.camera.network_id, "5678")
        self.assertEqual(self.camera.serial, "12345678")
        self.assertEqual(self.camera.motion_enabled, False)
        self.assertEqual(self.camera.battery, "ok")
        self.assertEqual(self.camera.temperature, 68)
        self.assertEqual(self.camera.temperature_c, 20)
        self.assertEqual(self.camera.temperature_calibrated, 71)
        self.assertEqual(self.camera.battery_voltage, 163)
        self.assertEqual(self.camera.wifi_strength, -38)
        self.assertEqual(
            self.camera.thumbnail, "https://rest-test.immedia-semi.com/thumb.jpg"
        )
        self.assertEqual(
            self.camera.clip, "https://rest-test.immedia-semi.com/test.mp4"
        )
        self.assertEqual(self.camera.image_from_cache, "test")
        self.assertEqual(self.camera.video_from_cache, "foobar")

        # Check that thumbnail without slash processed properly
        mock_resp.side_effect = [
            mresp.MockResponse({"test": 200}, 200, raw_data="thumb_no_slash")
        ]
        await self.camera.update_images(
            {"thumbnail": "thumb_no_slash"}, expire_clips=False
        )
        self.assertEqual(
            self.camera.thumbnail,
            "https://rest-test.immedia-semi.com/thumb_no_slash.jpg",
        )

    async def test_no_thumbnails(self, mock_resp):
        """Tests that thumbnail is 'None' if none found."""
        mock_resp.return_value = "foobar"
        self.camera.last_record = ["1"]
        config = {
            **CONFIG,
            **{
                "thumbnail": "",
            },
        }

        self.camera.sync.homescreen = {"devices": []}
        self.assertEqual(self.camera.temperature_calibrated, None)
        with self.assertLogs() as logrecord:
            await self.camera.update(config, force=True, expire_clips=False)
        self.assertEqual(self.camera.thumbnail, None)
        self.assertEqual(self.camera.last_record, ["1"])
        self.assertEqual(self.camera.temperature_calibrated, 68)
        self.assertEqual(
            logrecord.output,
            [
                (
                    "WARNING:blinkpy.camera:Could not retrieve calibrated "
                    f"temperature response {mock_resp.return_value}."
                ),
                (
                    f"WARNING:blinkpy.camera:for network_id ({config['network_id']}) "
                    f"and camera_id ({self.camera.camera_id})"
                ),
                ("WARNING:blinkpy.camera:Could not find thumbnail for camera new."),
            ],
        )

    async def test_no_video_clips(self, mock_resp):
        """Tests that we still proceed with camera setup with no videos."""
        mock_resp.return_value = "foobar"
        config = {
            **CONFIG,
            **{
                "thumbnail": "/foobar",
            },
        }
        mock_resp.return_value = mresp.MockResponse({"test": 200}, 200, raw_data="")
        self.camera.sync.homescreen = {"devices": []}
        await self.camera.update(config, force_cache=True, expire_clips=False)
        self.assertEqual(self.camera.clip, None)
        self.assertEqual(self.camera.video_from_cache, None)

    async def test_recent_video_clips(self, mock_resp):
        """Test recent video clips.

        Tests that the last records in the sync module are added
        to the camera recent clips list.
        """
        self.camera.sync.last_records["foobar"] = []
        record2 = {"clip": "/clip2", "time": "2022-12-01 00:00:10+00:00"}
        self.camera.sync.last_records["foobar"].append(record2)
        record1 = {"clip": "/clip1", "time": "2022-12-01 00:00:00+00:00"}
        self.camera.sync.last_records["foobar"].append(record1)
        self.camera.sync.motion["foobar"] = True
        await self.camera.update_images(CONFIG, expire_clips=False)
        record1["clip"] = self.blink.urls.base_url + "/clip1"
        record2["clip"] = self.blink.urls.base_url + "/clip2"
        self.assertEqual(self.camera.recent_clips[0], record1)
        self.assertEqual(self.camera.recent_clips[1], record2)

    async def test_recent_video_clips_missing_key(self, mock_resp):
        """Tests that the missing key failst."""
        self.camera.sync.last_records["foobar"] = []
        record2 = {"clip": "/clip2"}
        self.camera.sync.last_records["foobar"].append(record2)
        self.camera.sync.motion["foobar"] = True

        with self.assertLogs(level="ERROR") as dl_log:
            await self.camera.update_images(CONFIG, expire_clips=False)

        self.assertIsNotNone(dl_log.output)

    async def test_expire_recent_clips(self, mock_resp):
        """Test expiration of recent clips."""
        self.camera.recent_clips = []
        now = datetime.datetime.now()
        self.camera.recent_clips.append(
            {
                "time": (now - datetime.timedelta(minutes=20)).isoformat(),
                "clip": "/clip1",
            },
        )
        self.camera.recent_clips.append(
            {
                "time": (now - datetime.timedelta(minutes=1)).isoformat(),
                "clip": "local_storage/clip2",
            },
        )
        await self.camera.expire_recent_clips(delta=datetime.timedelta(minutes=5))
        self.assertEqual(len(self.camera.recent_clips), 1)

    @mock.patch(
        "blinkpy.api.request_motion_detection_enable",
        mock.AsyncMock(return_value="enable"),
    )
    @mock.patch(
        "blinkpy.api.request_motion_detection_disable",
        mock.AsyncMock(return_value="disable"),
    )
    async def test_motion_detection_enable_disable(self, mock_rep):
        """Test setting motion detection enable properly."""
        self.assertEqual(await self.camera.set_motion_detect(True), "enable")
        self.assertEqual(await self.camera.set_motion_detect(False), "disable")

    async def test_night_vision(self, mock_resp):
        """Test Night Vision Camera functions."""
        # MJK - I don't know what the "real" response is supposed to look like
        # Need to confirm and adjust this test to match reality?
        mock_resp.return_value = "blah"
        self.assertIsNone(await self.camera.night_vision)

        self.camera.product_type = "catalina"
        mock_resp.return_value = {"camera": [{"name": "123", "illuminator_enable": 1}]}
        self.assertIsNotNone(await self.camera.night_vision)

        self.assertIsNone(await self.camera.async_set_night_vision("0"))

        mock_resp.return_value = mresp.MockResponse({"code": 200}, 200)
        self.assertIsNotNone(await self.camera.async_set_night_vision("on"))

        mock_resp.return_value = mresp.MockResponse({"code": 400}, 400)
        self.assertIsNone(await self.camera.async_set_night_vision("on"))

    async def test_record(self, mock_resp):
        """Test camera record function."""
        with mock.patch(
            "blinkpy.api.request_new_video", mock.AsyncMock(return_value=True)
        ):
            self.assertTrue(await self.camera.record())

        with mock.patch(
            "blinkpy.api.request_new_video", mock.AsyncMock(return_value=False)
        ):
            self.assertFalse(await self.camera.record())

    async def test_get_thumbnail(self, mock_resp):
        """Test get thumbnail without URL."""
        self.assertIsNone(await self.camera.get_thumbnail())

    async def test_get_video(self, mock_resp):
        """Test get video clip without URL."""
        self.assertIsNone(await self.camera.get_video_clip())

    @mock.patch(
        "blinkpy.api.request_new_image", mock.AsyncMock(return_value={"json": "Data"})
    )
    async def test_snap_picture(self, mock_resp):
        """Test camera snap picture function."""
        self.assertIsNotNone(await self.camera.snap_picture())

    @mock.patch("blinkpy.api.http_post", mock.AsyncMock(return_value={"json": "Data"}))
    async def test_snap_picture_blinkmini(self, mock_resp):
        """Test camera snap picture function."""
        self.camera = BlinkCameraMini(self.blink.sync["test"])
        self.assertIsNotNone(await self.camera.snap_picture())

    @mock.patch("blinkpy.api.http_post", mock.AsyncMock(return_value={"json": "Data"}))
    async def test_snap_picture_blinkdoorbell(self, mock_resp):
        """Test camera snap picture function."""
        self.camera = BlinkDoorbell(self.blink.sync["test"])
        self.assertIsNotNone(await self.camera.snap_picture())

    @mock.patch("blinkpy.camera.open", create=True)
    async def test_image_to_file(self, mock_open, mock_resp):
        """Test camera image to file."""
        mock_resp.return_value = mresp.MockResponse({}, 200, raw_data="raw data")
        self.camera.thumbnail = "/thumbnail"
        await self.camera.image_to_file("my_path")

    @mock.patch("blinkpy.camera.open", create=True)
    async def test_image_to_file_error(self, mock_open, mock_resp):
        """Test camera image to file with error."""
        mock_resp.return_value = mresp.MockResponse({}, 400, raw_data="raw data")
        self.camera.thumbnail = "/thumbnail"
        with self.assertLogs(level="DEBUG") as dl_log:
            await self.camera.image_to_file("my_path")
        self.assertEqual(
            dl_log.output[2],
            "ERROR:blinkpy.camera:Cannot write image to file, response 400",
        )

    @mock.patch("blinkpy.camera.open", create=True)
    async def test_video_to_file_none_response(self, mock_open, mock_resp):
        """Test camera video to file."""
        mock_resp.return_value = mresp.MockResponse({}, 200, raw_data="raw data")
        with self.assertLogs(level="DEBUG") as dl_log:
            await self.camera.video_to_file("my_path")
        self.assertEqual(
            dl_log.output[2],
            f"ERROR:blinkpy.camera:No saved video exists for {self.camera.name}.",
        )

    @mock.patch("blinkpy.camera.open", create=True)
    async def test_video_to_file(self, mock_open, mock_resp):
        """Test camera vido to file with error."""
        mock_resp.return_value = mresp.MockResponse({}, 400, raw_data="raw data")
        self.camera.clip = "my_clip"
        await self.camera.video_to_file("my_path")
        mock_open.assert_called_once()

    @mock.patch("blinkpy.camera.open", create=True)
    @mock.patch("blinkpy.camera.BlinkCamera.get_video_clip")
    async def test_save_recent_clips(self, mock_clip, mock_open, mock_resp):
        """Test camera save recent clips."""
        with self.assertLogs(level="DEBUG") as dl_log:
            await self.camera.save_recent_clips()
        self.assertEqual(
            dl_log.output[0],
            f"INFO:blinkpy.camera:No recent clips to save for '{self.camera.name}'.",
        )
        assert mock_open.call_count == 0

        self.camera.recent_clips = []
        now = datetime.datetime.now()
        self.camera.recent_clips.append(
            {
                "time": (now - datetime.timedelta(minutes=20)).isoformat(),
                "clip": "/clip1",
            },
        )
        self.camera.recent_clips.append(
            {
                "time": (now - datetime.timedelta(minutes=1)).isoformat(),
                "clip": "local_storage/clip2",
            },
        )
        mock_clip.return_value = mresp.MockResponse({}, 200, raw_data="raw data")
        with self.assertLogs(level="DEBUG") as dl_log:
            await self.camera.save_recent_clips()
        self.assertEqual(
            dl_log.output[4],
            "INFO:blinkpy.camera:Saved 2 of 2 recent clips from "
            f"'{self.camera.name}' to directory /tmp/",
        )
        assert mock_open.call_count == 2

    def remove_clip(self):
        """Remove all clips to raise an exception on second removal."""
        self[0] *= 0
        return mresp.MockResponse({}, 200, raw_data="raw data")

    @mock.patch("blinkpy.camera.open", create=True)
    @mock.patch(
        "blinkpy.camera.BlinkCamera.get_video_clip",
        create=True,
        side_effect=remove_clip,
    )
    async def test_save_recent_clips_exception(self, mock_clip, mock_open, mock_resp):
        """Test corruption in recent clip list."""
        self.camera.recent_clips = []
        now = datetime.datetime.now()
        self.camera.recent_clips.append(
            {
                "time": (now - datetime.timedelta(minutes=20)).isoformat(),
                "clip": [self.camera.recent_clips],
            },
        )
        with self.assertLogs(level="ERROR") as dl_log:
            await self.camera.save_recent_clips()
        print(f"Output = {dl_log.output}")
        self.assertTrue(
            "ERROR:blinkpy.camera:Error removing clip from list:"
            in "\t".join(dl_log.output)
        )
        assert mock_open.call_count == 1

    async def test_missing_keys(self, mock_resp):
        """Tests missing signal keys."""
        config = {
            **CONFIG,
            **{
                "signals": {"junk": 1},
                "thumbnail": "",
            },
        }
        self.camera.sync.homescreen = {"devices": []}
        mock_resp.side_effect = [
            {"temp": 71},
            mresp.MockResponse({"test": 200}, 200, raw_data="test"),
            mresp.MockResponse({"foobar": 200}, 200, raw_data="foobar"),
        ]
        await self.camera.update(config, expire_clips=False, force=True)
        self.assertEqual(self.camera.battery_level, None)