Browse Source

[db][tests] variables

Maxime Alves LIRMM@home 3 years ago
parent
commit
6aa3cc37ae

+ 13
- 0
db/test_variable_values.sql View File

@@ -0,0 +1,13 @@
1
+INSERT INTO var_value (type, address, value) VALUES
2
+('A', 10, 42),
3
+('A', 11, 24),
4
+('A', 10, 20),
5
+('A', 10, 0),
6
+('I', 5010, 42),
7
+('I', 5011, 24),
8
+('I', 5010, 20),
9
+('I', 5010, 0),
10
+('D', 10, 1),
11
+('D', 11, 1),
12
+('D', 10, 1),
13
+('D', 10, 0);

+ 13
- 0
db/test_variables.sql View File

@@ -0,0 +1,13 @@
1
+INSERT INTO variable (type, address, unit) VALUES
2
+('A', 10, 'deg'),
3
+('A', 11, 'deg'),
4
+('A', 12, 'deg'),
5
+('A', 13, 'deg'),
6
+('I', 5010, 'deg'),
7
+('I', 5011, 'deg'),
8
+('I', 5012, 'deg'),
9
+('I', 5013, 'deg'),
10
+('D', 10, 'bit'),
11
+('D', 11, 'bit'),
12
+('D', 12, 'bit'),
13
+('D', 13, 'bit');

+ 16
- 7
pyheatpump/models/variable.py View File

@@ -1,12 +1,14 @@
1 1
 from pyheatpump.db import RowClass
2 2
 from pyheatpump.db import sql
3
+from datetime import date
3 4
 
4
-class VariableType(RowClass):
5
-    slabel: str = None
6
-    label: str = None
5
+from .variable_type import VariableType
6
+
7
+class Variable(RowClass):
8
+    address: int = None
9
+    unit: str = None
10
+    last_update: date = None
7 11
     type: str = None
8
-    start_address: int = None
9
-    end_address: int = None
10 12
  
11 13
     def __init__(self, **kwargs):
12 14
         super().__init__(**kwargs)
@@ -14,5 +16,12 @@ class VariableType(RowClass):
14 16
     @staticmethod
15 17
     def getall():
16 18
         return dict([
17
-            (row['label'], VariableType(**dict(row)))
18
-            for row in sql('SELECT * FROM var_type') ])
19
+            (row.slabel, Variable.getall_of_type(row.slabel))
20
+            for row in VariableType.getall().values()
21
+        ])
22
+
23
+    def getall_of_type(type: str):
24
+        return [
25
+            row['address'] for row in
26
+            sql(f"SELECT address FROM variable WHERE type LIKE '{type}'")
27
+        ]

+ 2
- 2
pyheatpump/variable_types.py View File

@@ -12,8 +12,6 @@ import json
12 12
 from pyheatpump.db import sql
13 13
 from pyheatpump.models.variable_type import VariableType
14 14
 
15
-def variable_types():
16
-    assert type(VariableType.getall()) == list
17 15
 
18 16
 async def get_variable_types(request):
19 17
     return JSONResponse(dict([
@@ -21,6 +19,7 @@ async def get_variable_types(request):
21 19
         for key, val in VariableType.getall().items()
22 20
     ]))
23 21
 
22
+
24 23
 async def set_variable_types(request):
25 24
 
26 25
     body = json.loads(await request.json())
@@ -35,6 +34,7 @@ async def set_variable_types(request):
35 34
 
36 35
     return PlainTextResponse('OK')
37 36
 
37
+
38 38
 async def variable_types_routes(request, *args, **kwargs):
39 39
     if request['method'] == 'GET':
40 40
         return await get_variable_types(request)

+ 53
- 0
pyheatpump/variables.py View File

@@ -0,0 +1,53 @@
1
+#!/usr/bin/env python3
2
+import os
3
+from datetime import datetime
4
+from configparser import ConfigParser
5
+from starlette.routing import Route, Router
6
+from starlette.responses import PlainTextResponse, JSONResponse
7
+from pprint import pprint
8
+import uvicorn
9
+import json
10
+
11
+# pyHeatpump modules
12
+from pyheatpump.db import sql
13
+from pyheatpump.models.variable import Variable
14
+
15
+
16
+async def get_variables(request):
17
+    return JSONResponse(Variable.getall())
18
+
19
+
20
+async def set_variables(request):
21
+
22
+    body = json.loads(await request.json())
23
+
24
+    """
25
+    for var_type_label, var_type_values in body.items():
26
+        vt = VariableType(label=var_type_label)
27
+        for key, val in var_type_values.items():
28
+            if key in [ 'start_address', 'end_address' ]:
29
+                setattr(vt, key, val)
30
+
31
+        vt.save()
32
+
33
+    """
34
+    return PlainTextResponse('OK')
35
+
36
+
37
+async def variables_routes(request, *args, **kwargs):
38
+    if request['method'] == 'GET':
39
+        return await get_variables(request)
40
+    elif request['method'] == 'POST':
41
+        return await set_variables(request)
42
+
43
+
44
+ROUTES=[
45
+    Route('/', variables_routes, methods=['GET', 'POST'])
46
+]
47
+
48
+app = Router(routes=ROUTES)
49
+
50
+if __name__ == '__main__':
51
+    uvicorn.run('pyHeatpump:conf.app',
52
+        host='127.0.0.1',
53
+        port=8000)

+ 50
- 0
tests/test_variable.py View File

@@ -0,0 +1,50 @@
1
+#!/usr/bin/env python3
2
+import pytest
3
+from starlette.authentication import UnauthenticatedUser
4
+from starlette.testclient import TestClient
5
+from unittest.mock import patch, MagicMock
6
+from pprint import pprint
7
+import json
8
+from tempfile import mkstemp
9
+from configparser import ConfigParser
10
+import os
11
+import sys
12
+
13
+from pyheatpump.conf import config
14
+from pyheatpump.db import initialize, connect
15
+from pyheatpump.variables import app, get_variables, set_variables, ROUTES
16
+
17
+@pytest.fixture(scope='module')
18
+def set_test_db():
19
+    _, tmpdb = mkstemp(suffix='.db', dir=os.getcwd(), )
20
+    print(f'Will store database in {tmpdb}')
21
+    config['heatpump']['database'] = tmpdb
22
+    if not initialize(os.path.join(os.getcwd(), 'db/pyheatpump.sql')):
23
+        sys.exit(-1)
24
+
25
+    if not initialize(os.path.join(os.getcwd(), 'db/test_variables.sql')):
26
+        sys.exit(-1)
27
+
28
+    yield
29
+
30
+    os.unlink(tmpdb)
31
+
32
+
33
+def test_get_(set_test_db):
34
+    c = TestClient(app)
35
+    r = c.get('/')
36
+    assert r.status_code == 200
37
+
38
+    d_resp = json.loads(r.content.decode())
39
+    assert 'A' in d_resp.keys()
40
+    assert 10 in d_resp['A']
41
+    assert len(d_resp['A']) == 4
42
+    assert len(d_resp['I']) == 4
43
+    assert len(d_resp['D']) == 4
44
+
45
+
46
+@pytest.mark.skip
47
+def test_set_(set_test_db):
48
+    c = TestClient(app)
49
+    r = c.post('/')
50
+    assert r.status_code == 200

+ 1
- 1
tests/test_variable_types.py View File

@@ -19,7 +19,7 @@ from pyheatpump.variable_types import app, get_variable_types, set_variable_type
19 19
 def set_test_db():
20 20
     _, tmpdb = mkstemp(suffix='.db', dir=os.getcwd(), )
21 21
     print(f'Will store database in {tmpdb}')
22
-    config['heatpump']['database'] = tmpdb 
22
+    config['heatpump']['database'] = tmpdb
23 23
     if not initialize(os.path.join(os.getcwd(), 'db/pyheatpump.sql')):
24 24
         sys.exit(-1)
25 25
 

+ 50
- 0
tests/test_variable_values.py View File

@@ -0,0 +1,50 @@
1
+#!/usr/bin/env python3
2
+import pytest
3
+from starlette.authentication import UnauthenticatedUser
4
+from starlette.testclient import TestClient
5
+from unittest.mock import patch, MagicMock
6
+from pprint import pprint
7
+import json
8
+from tempfile import mkstemp
9
+from configparser import ConfigParser
10
+import os
11
+import sys
12
+
13
+from pyheatpump.conf import config
14
+from pyheatpump.db import initialize, connect
15
+from pyheatpump.variables import app, get_variables, set_variables, ROUTES
16
+
17
+@pytest.fixture(scope='module')
18
+def set_test_db():
19
+    _, tmpdb = mkstemp(suffix='.db', dir=os.getcwd(), )
20
+    print(f'Will store database in {tmpdb}')
21
+    config['heatpump']['database'] = tmpdb
22
+    if not initialize(os.path.join(os.getcwd(), 'db/pyheatpump.sql')):
23
+        sys.exit(-1)
24
+
25
+    if not initialize(os.path.join(os.getcwd(), 'db/test_variables.sql')):
26
+        sys.exit(-1)
27
+
28
+    yield
29
+
30
+    os.unlink(tmpdb)
31
+
32
+
33
+def test_get_(set_test_db):
34
+    c = TestClient(app)
35
+    r = c.get('/')
36
+    assert r.status_code == 200
37
+
38
+    d_resp = json.loads(r.content.decode())
39
+    assert 'A' in d_resp.keys()
40
+    assert 10 in d_resp['A']
41
+    assert len(d_resp['A']) == 4
42
+    assert len(d_resp['I']) == 4
43
+    assert len(d_resp['D']) == 4
44
+
45
+
46
+@pytest.mark.skip
47
+def test_set_(set_test_db):
48
+    c = TestClient(app)
49
+    r = c.post('/')
50
+    assert r.status_code == 200

Loading…
Cancel
Save