File: test_api.py

package info (click to toggle)
tesla-powerwall 0.5.2-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 264 kB
  • sloc: python: 1,458; makefile: 8
file content (208 lines) | stat: -rw-r--r-- 7,398 bytes parent folder | download
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
import json
import unittest

import aiohttp
import aresponses

from tesla_powerwall import API, AccessDeniedError, ApiError
from tesla_powerwall.const import User
from tests.unit import ENDPOINT, ENDPOINT_HOST, ENDPOINT_PATH


class TestAPI(unittest.IsolatedAsyncioTestCase):
    async def asyncSetUp(self):
        self.aresponses = aresponses.ResponsesMockServer()
        await self.aresponses.__aenter__()

        self.session = aiohttp.ClientSession()
        self.api = API(ENDPOINT, http_session=self.session)

    async def asyncTearDown(self):
        await self.api.close()
        await self.session.close()
        await self.aresponses.__aexit__(None, None, None)

    def test_parse_endpoint(self):
        test_endpoints = [
            "1.1.1.1",
            "http://1.1.1.1",
            "https://1.1.1.1/api/",
            "https://1.1.1.1/api",
            "https://1.1.1.1/",
        ]
        for test_endpoint in test_endpoints:
            self.assertEqual(self.api._parse_endpoint(test_endpoint), ENDPOINT)

    async def test_process_response(self):
        status = 0
        text = None

        def response_handler(request):
            return self.aresponses.Response(status=status, text=text)

        self.aresponses.add(
            ENDPOINT_HOST,
            f"{ENDPOINT_PATH}test",
            "GET",
            response_handler,
            repeat=self.aresponses.INFINITY,
        )

        status = 401
        async with self.session.get(f"{ENDPOINT}test") as response:
            with self.assertRaises(AccessDeniedError):
                await self.api._process_response(response)

        status = 404
        async with self.session.get(f"{ENDPOINT}test") as response:
            with self.assertRaises(ApiError):
                await self.api._process_response(response)

        status = 502
        async with self.session.get(f"{ENDPOINT}test") as response:
            with self.assertRaises(ApiError):
                await self.api._process_response(response)

        status = 200
        text = '{"error": "test_error"}'
        async with self.session.get(f"{ENDPOINT}test") as response:
            with self.assertRaises(ApiError):
                await self.api._process_response(response)

        status = 200
        text = '{invalid_json"'
        async with self.session.get(f"{ENDPOINT}test") as response:
            with self.assertRaises(ApiError):
                await self.api._process_response(response)

        status = 200
        text = "{}"
        async with self.session.get(f"{ENDPOINT}test") as response:
            self.assertEqual(await self.api._process_response(response), {})

        status = 200
        text = '{"response": "ok"}'
        async with self.session.get(f"{ENDPOINT}test") as response:
            self.assertEqual(
                await self.api._process_response(response), {"response": "ok"}
            )

    async def test_get(self):
        self.aresponses.add(
            ENDPOINT_HOST,
            f"{ENDPOINT_PATH}test_get",
            "GET",
            self.aresponses.Response(text='{"test_get": true}'),
        )

        self.assertEqual(await self.api.get("test_get"), {"test_get": True})

        self.aresponses.assert_plan_strictly_followed()

    async def test_post(self):
        self.aresponses.add(
            ENDPOINT_HOST,
            f"{ENDPOINT_PATH}test_post",
            "POST",
            self.aresponses.Response(
                text='{"test_post": true}', headers={"Content-Type": "application/json"}
            ),
        )

        resp = await self.api.post("test_post", {"test": True})
        self.assertIsInstance(resp, dict)
        self.assertEqual(resp, {"test_post": True})

        self.aresponses.assert_plan_strictly_followed()

    async def test_is_authenticated(self):
        self.assertEqual(self.api.is_authenticated(), False)

        self.session.cookie_jar.update_cookies(cookies={"AuthCookie": "foo"})
        self.assertEqual(self.api.is_authenticated(), True)

    def test_url(self):
        self.assertEqual(self.api.url("test"), ENDPOINT + "test")

    async def test_login(self):
        jar = aiohttp.CookieJar(unsafe=True)
        async with aiohttp.ClientSession(cookie_jar=jar) as http_session:
            async with API(ENDPOINT, http_session=http_session) as api:
                username = User.CUSTOMER.value
                password = "password"
                email = "email@email.com"

                async def response_handler(request) -> aresponses.Response:
                    request_json = await request.json()

                    self.assertEqual(request_json["username"], username)
                    self.assertEqual(request_json["password"], password)
                    self.assertEqual(request_json["email"], email)

                    login_response = self.aresponses.Response(
                        text=json.dumps(
                            {
                                "email": request_json["email"],
                                "firstname": "Tesla",
                                "lastname": "Energy",
                                "roles": ["Home_Owner"],
                                "token": "x4jbH...XMP8w==",
                                "provider": "Basic",
                                "loginTime": "2023-03-25T13:10:48.9029581+01:00",
                            }
                        ),
                        headers={"Content-Type": "application/json"},
                    )
                    login_response.set_cookie("AuthCookie", "foo")
                    return login_response

                self.aresponses.add(
                    ENDPOINT_HOST,
                    f"{ENDPOINT_PATH}login/Basic",
                    "POST",
                    response_handler,
                )

                await api.login(username=username, email=email, password=password)

                self.aresponses.add(
                    ENDPOINT_HOST,
                    f"{ENDPOINT_PATH}logout",
                    "GET",
                    self.aresponses.Response(
                        text="", headers={"Content-Type": "application/json"}
                    ),
                )

                await api.logout()

                self.aresponses.assert_plan_strictly_followed()

    async def test_close(self):
        api_session = None
        async with API(ENDPOINT) as api:
            api_session = api._http_session
            self.assertFalse(api_session.closed)
        self.assertTrue(api_session.closed)

        async with aiohttp.ClientSession() as session:
            async with API(ENDPOINT, http_session=session) as api:
                api_session = api._http_session
                self.assertFalse(api_session.closed)

            self.assertFalse(api_session.closed)
        self.assertTrue(api_session.closed)

        api = API(ENDPOINT)
        api_session = api._http_session
        self.assertFalse(api_session.closed)
        await api.close()
        self.assertTrue(api_session.closed)

        async with aiohttp.ClientSession() as session:
            api_session = session
            api = API(ENDPOINT, http_session=session)
            self.assertFalse(api_session.closed)
            await api.close()
            self.assertFalse(api_session.closed)
        self.assertTrue(api_session.closed)