Browse Source

[get/post] /config/last_update | [get/post] /config/mac_address

Maxime Alves LIRMM@home 3 years ago
parent
commit
5d677464d9
2 changed files with 55 additions and 47 deletions
  1. 19
    18
      pyheatpump/config.py
  2. 36
    29
      tests/test_config.py

+ 19
- 18
pyheatpump/config.py View File

@@ -3,6 +3,7 @@ import os
3 3
 import re
4 4
 from datetime import datetime
5 5
 from configparser import ConfigParser
6
+from starlette.requests import Request
6 7
 from starlette.routing import Route, Router
7 8
 from starlette.responses import PlainTextResponse, JSONResponse
8 9
 from pprint import pprint
@@ -52,19 +53,16 @@ API_HOST=config.get('api', 'host')
52 53
 API_PORT=config.get('api', 'port')
53 54
 
54 55
 def save_config():
55
-    print(get_config_dict())
56
-    with open(CONFIG_FILES[1], 'w') as conf_file:
56
+    with open(CONFIG_FILES[-1], 'w') as conf_file:
57 57
         config.write(conf_file)
58 58
 
59 59
 
60 60
 def get_mac():
61
-    config.read(filenames=CONFIG_FILES)
62
-    return config.get('heatpump', 'mac_address')
61
+    return get_config_dict()['heatpump', 'mac_address']
63 62
 
64 63
 
65 64
 def mac_address_init():
66 65
     from netifaces import gateways, ifaddresses, AF_INET, AF_LINK
67
-    global config
68 66
 
69 67
     interface = gateways()['default'][AF_INET][1]
70 68
     if len(ifaddresses(interface)) == 0:
@@ -78,7 +76,6 @@ def mac_address_init():
78 76
     addr = ifaddresses(interface)[AF_LINK][0]['addr']
79 77
     config.set('heatpump', 'mac_address', addr)
80 78
     save_config()
81
-
82 79
     return addr
83 80
 
84 81
 
@@ -92,18 +89,18 @@ async def get_config(request):
92 89
 
93 90
 
94 91
 async def set_config(request):
95
-    global config
96 92
     body = await request.json()
93
+    d_body = json.loads(body)
97 94
     #return PlainTextResponse(body)
98 95
 
99
-    for sect in body.keys():
100
-        if type(body[sect]) is not dict:
96
+    for sect in d_body.keys():
97
+        if type(d_body[sect]) is not dict:
101 98
             continue
102
-        for item in body[sect].keys():
99
+        for item in d_body[sect].keys():
103 100
             if not config.has_option(sect, item):
104 101
                 raise HTTPException(404, f'The option {sect}.{item} does not exists')
105 102
             else:
106
-                config.set(sect, item, value=body[sect][item])
103
+                config.set(sect, item, value=d_body[sect][item])
107 104
 
108 105
     save_config()
109 106
     return PlainTextResponse('OK')
@@ -116,7 +113,6 @@ async def config_route(request, *args, **kwargs):
116 113
 
117 114
 
118 115
 async def mac_route(request, *args, **kwargs):
119
-    global config
120 116
     if request['method'] == 'GET':
121 117
         return PlainTextResponse(get_mac())
122 118
     elif request['method'] == 'POST':
@@ -130,6 +126,8 @@ async def mac_route(request, *args, **kwargs):
130 126
 
131 127
             config.set('heatpump','mac_address',mac_address)
132 128
             save_config()
129
+        else:
130
+            print(f'Wrong mac format : {mac_address}')
133 131
 
134 132
         return PlainTextResponse(' '.join((
135 133
             'Current ->',
@@ -142,8 +140,7 @@ def get_last_update():
142 140
 
143 141
 
144 142
 def set_last_update(last_update: int=0):
145
-    global config
146
-    config.set('supervisor', 'last_update', last_update)
143
+    config.set('supervisor', 'last_update', str(last_update))
147 144
     save_config()
148 145
     return get_last_update()
149 146
 
@@ -155,18 +152,21 @@ async def last_update_route(request, *args, **kwargs):
155 152
         < 0 : since current_date + last_update - interval
156 153
         > 0 : since current_data - last_update - interval (same behaviour as < 0) 
157 154
     """
158
-    global config
159
-    if request['method'] == 'GET':
155
+    if type(request) != Request or request['method'] == 'GET':
160 156
         return PlainTextResponse(get_last_update())
161 157
 
162 158
     elif request['method'] == 'POST':
163 159
         body = await request.body()
164 160
         last_update = int(body.decode() or 0)
165
-        if int(body.decode() or 0):
161
+        print(f'Last update set : {last_update}')
162
+        if last_update == 0:
163
+            print('Reset last update to current time')
166 164
             last_update = int(datetime.now().strftime('%s'))
167 165
         elif last_update <= 0:
166
+            print('Forward of {last_update} seconds')
168 167
             last_update = int(datetime.now().strftime('%s')) + last_update
169 168
         else:
169
+            print('Rewind of {last_update} seconds')
170 170
             last_update = int(datetime.now().strftime('%s')) - last_update
171 171
 
172 172
 
@@ -175,7 +175,8 @@ async def last_update_route(request, *args, **kwargs):
175 175
 
176 176
 ROUTES=[
177 177
     Route('/', config_route, methods=['GET', 'POST']),
178
-    Route('/mac', mac_route, methods=['GET', 'POST'])
178
+    Route('/mac', mac_route, methods=['GET', 'POST']),
179
+    Route('/last_update', last_update_route, methods=['GET', 'POST'])
179 180
 ]
180 181
 
181 182
 app = Router(routes=ROUTES)

+ 36
- 29
tests/test_config.py View File

@@ -3,7 +3,7 @@ import pytest
3 3
 from starlette.authentication import UnauthenticatedUser
4 4
 from starlette.testclient import TestClient
5 5
 from pyheatpump.config import app, config, default_config, \
6
-    CONFIG_FILES, get_config, set_config, config_route, ROUTES, \
6
+    CONFIG_FILES, get_config, get_config_dict, set_config, config_route, ROUTES, \
7 7
     mac_address_init, save_config, get_last_update, set_last_update, \
8 8
     last_update_route
9 9
 from unittest.mock import patch, MagicMock
@@ -13,6 +13,8 @@ from tempfile import mkstemp
13 13
 from configparser import ConfigParser
14 14
 import os
15 15
 from requests import Request
16
+from uuid import uuid4
17
+from datetime import datetime
16 18
 
17 19
 @pytest.fixture
18 20
 def tmpconf(testdir):
@@ -24,12 +26,12 @@ def tmpconf(testdir):
24 26
 
25 27
     with open(tmp_conf_filepath, 'w') as f:
26 28
         f.write("[heatpump]\nmac_address = 'None'")
27
-        CONFIG_FILES = [tmp_conf_filepath]
29
+        #CONFIG_FILES = [tmp_conf_filepath]
28 30
         config.read(filenames=CONFIG_FILES)
29 31
 
30 32
     return config
31 33
 
32
-def test_get_():
34
+def test_get_(tmpconf):
33 35
     c = TestClient(app)
34 36
     r = c.get('/')
35 37
     assert r.status_code == 200
@@ -41,24 +43,26 @@ class RequestMock(MagicMock):
41 43
             return 'GET'
42 44
 
43 45
 
44
-@pytest.mark.asyncio
45
-async def test_get_config():
46
-    resp = await get_config(RequestMock())
46
+def test_get_config(tmpconf):
47
+    c = TestClient(app)
48
+    resp = c.get('/') 
47 49
     assert resp.status_code  == 200
48
-    d_resp = json.loads(resp.body.decode())
50
+    d_resp = resp.json()
51
+    assert type(d_resp) == dict
49 52
     for sect in default_config.keys():
50 53
         assert sect in d_resp.keys()
51 54
         for item in default_config[sect].keys():
52 55
             assert item in d_resp[sect].keys()
53 56
 
54 57
 
55
-def test_set_config():
58
+def test_set_config(tmpconf):
56 59
     c = TestClient(app)
57 60
     _, tmpconf = mkstemp()
58
-    CONFIG_FILES.insert(0, tmpconf)
61
+    CONFIG_FILES.append(tmpconf)
62
+    rand = str(uuid4())
59 63
     r = c.post('/', json=json.dumps({
60 64
         'supervisor': {
61
-            'scheme':'test'
65
+            'scheme':rand
62 66
         }
63 67
     }))
64 68
 
@@ -66,28 +70,31 @@ def test_set_config():
66 70
     config.read(filenames=[tmpconf])
67 71
 
68 72
     assert r.status_code == 200
69
-    assert config.get('supervisor', 'scheme') == 'test'
73
+    assert config.get('supervisor', 'scheme') == rand
74
+    assert type(get_config_dict()) == dict
75
+    d_config =get_config_dict()
76
+    assert 'supervisor' in d_config.keys()
77
+    assert 'scheme' in d_config['supervisor'].keys()
78
+    assert d_config['supervisor']['scheme'] == rand
70 79
 
71 80
     os.unlink(tmpconf)
72 81
 
73 82
 
74 83
 def test_mac_address(testdir, tmpconf):
75
-    try:
76
-        assert tmpconf.get('heatpump', 'mac_address') is 'None'
77
-        mac_address = mac_address_init()
78
-        config_mac_address = tmpconf.get('heatpump', 'mac_address')
79
-        assert config_mac_address == mac_address
80
-    except Exception as e:
81
-        raise e
82
-
83
-
84
-@pytest.mark.asyncio
85
-async def test_last_update(testdir, tmpconf):
86
-    req = Request()
87
-    req.method = 'POST'
88
-    res = await last_update_route(req)
89
-    last_update_0 = int(res.body)
90
-
91
-    res = await get_last_update(req)
92
-    last_update_1 = int(res.body)
84
+    mac_address = mac_address_init()
85
+    assert type(get_config_dict()) == dict
86
+    d_config =get_config_dict()
87
+
88
+    assert d_config['heatpump']['mac_address'] == mac_address
89
+
90
+
91
+def test_last_update(testdir, tmpconf):
92
+    c = TestClient(app)
93
+    resp = c.get('/last_update')
94
+    last_update_0 = int(resp.content.decode())
95
+    print(f'update0 {last_update_0}')
96
+
97
+    resp = c.post('/last_update', str(datetime.now().strftime('%s')))
98
+    last_update_1 = int(resp.content.decode())
99
+    print(f'update1 {last_update_1}')
93 100
     assert last_update_0 == last_update_1

Loading…
Cancel
Save