Browse Source

[tests] update tests

Maxime Alves LIRMM@home 4 years ago
parent
commit
e45a344428

+ 55
- 0
tests/models/test_variable_value.py View File

@@ -0,0 +1,55 @@
1
+#!/usr/bin/env python3
2
+import pytest
3
+from starlette.authentication import UnauthenticatedUser
4
+from starlette.testclient import TestClient
5
+#from pyheatpump.conf import app, config, default_config, CONFIG_FILES, get_config, set_config, config_route, ROUTES
6
+from unittest.mock import patch, MagicMock
7
+from pprint import pprint
8
+import json
9
+from tempfile import mkstemp
10
+from configparser import ConfigParser
11
+import os
12
+import sys
13
+from datetime import datetime
14
+
15
+from pyheatpump.conf import config
16
+from pyheatpump.db import initialize, connect
17
+from pyheatpump.variable_types import app, get_variable_types, set_variable_types, ROUTES
18
+from pyheatpump.models import *
19
+
20
+
21
+@pytest.fixture()
22
+def set_test_db():
23
+    _, tmpdb = mkstemp(suffix='.db', dir=os.getcwd(), )
24
+    print(f'Will store database in {tmpdb}')
25
+    config['heatpump']['database'] = tmpdb
26
+    if not initialize(os.path.join(os.getcwd(), 'db/pyheatpump.sql')):
27
+        sys.exit(-1)
28
+
29
+    if not initialize(os.path.join(os.getcwd(), 'db/test_variables.sql')):
30
+        sys.exit(-1)
31
+
32
+    if not initialize(os.path.join(os.getcwd(), 'db/test_variable_values.sql')):
33
+        sys.exit(-1)
34
+
35
+    yield
36
+
37
+
38
+    os.unlink(tmpdb)
39
+
40
+
41
+def test_last_update(set_test_db):
42
+    for _, var_type in VariableType.getall().items():
43
+        for _, variable in var_type.get_variables().items():
44
+            try:
45
+                if not variable.last_update:
46
+                    continue
47
+                time = datetime.fromtimestamp(variable.last_update)
48
+                
49
+                val = VariableValue.get(variable.type,
50
+                    variable.address,
51
+                    time)
52
+                assert val is not None
53
+                assert variable.last_update == val.time
54
+            except StopIteration:
55
+                assert False

+ 39
- 0
tests/test_heatpump.py View File

@@ -0,0 +1,39 @@
1
+#!/usr/bin/env python3
2
+import pytest
3
+from starlette.authentication import UnauthenticatedUser
4
+from starlette.testclient import TestClient
5
+from pyheatpump.conf import app, config, default_config, CONFIG_FILES, get_config, set_config, config_route, ROUTES
6
+from pyheatpump.db import initialize, connect
7
+from unittest.mock import patch, MagicMock
8
+from pprint import pprint
9
+import json
10
+from tempfile import mkstemp
11
+from configparser import ConfigParser
12
+import os
13
+
14
+@pytest.fixture(scope='module')
15
+def set_test_db():
16
+    _, tmpdb = mkstemp(suffix='.db', dir=os.getcwd(), )
17
+    print(f'Will store database in {tmpdb}')
18
+    config['heatpump']['database'] = tmpdb
19
+    if not initialize(os.path.join(os.getcwd(), 'db/pyheatpump.sql')):
20
+        sys.exit(-1)
21
+
22
+    if not initialize(os.path.join(os.getcwd(), 'db/test_variables.sql')):
23
+        sys.exit(-1)
24
+
25
+    if not initialize(os.path.join(os.getcwd(), 'db/test_variable_values.sql')):
26
+        sys.exit(-1)
27
+
28
+    yield
29
+
30
+def test_get_(set_test_db):
31
+    c = TestClient(app)
32
+    r = c.get('/')
33
+    assert r.status_code == 200
34
+
35
+    resp = r.content.decode()
36
+    assert type(resp) == str
37
+
38
+    d_resp = json.loads(resp)
39
+    assert type(d_resp) == dict

+ 94
- 0
tests/test_modbus.py View File

@@ -0,0 +1,94 @@
1
+#!/usr/bin/env python3
2
+import pytest
3
+from unittest.mock import patch, MagicMock
4
+
5
+from starlette.authentication import UnauthenticatedUser
6
+from starlette.testclient import TestClient
7
+from pprint import pprint
8
+import json
9
+from tempfile import mkstemp
10
+from configparser import ConfigParser
11
+import os
12
+
13
+from serial import Serial
14
+import umodbus
15
+from umodbus.client.serial import rtu
16
+
17
+
18
+from pyheatpump.conf import config
19
+from pyheatpump.db import initialize
20
+from pyheatpump.models.variable_type import VariableType
21
+from pyheatpump import modbus
22
+
23
+@pytest.fixture(scope='module')
24
+def set_test_db():
25
+    _, tmpdb = mkstemp(suffix='.db', dir=os.getcwd(), )
26
+    print(f'Will store database in {tmpdb}')
27
+    config['heatpump']['database'] = tmpdb
28
+    if not initialize(os.path.join(os.getcwd(), 'db/pyheatpump.sql')):
29
+        sys.exit(-1)
30
+
31
+    if not initialize(os.path.join(os.getcwd(), 'db/test_variables.sql')):
32
+        sys.exit(-1)
33
+
34
+    yield
35
+
36
+    os.unlink(tmpdb)
37
+
38
+@pytest.fixture(scope='module')
39
+def serial_conn():
40
+    s = modbus.connect()
41
+    assert type(s) == Serial
42
+    return s
43
+
44
+
45
+@patch('umodbus.client.serial.rtu.send_message')
46
+@patch('umodbus.client.serial.rtu.read_coils')
47
+def test_rtu_call_mocked(RtuReadCoils, RtuSendMessage, serial_conn):
48
+    modbus.read_holding_registers(1, 3)
49
+    RtuReadCoils.assert_any_call(slave_id=1, starting_address=1, quantity=2)
50
+    RtuSendMessage.assert_called()
51
+
52
+    modbus.read_coils(1, 3)
53
+    RtuReadCoils.assert_any_call(slave_id=1, starting_address=1, quantity=2)
54
+    RtuSendMessage.assert_called()
55
+
56
+def test_rtu_call_holding_registers(serial_conn):
57
+    r = modbus.read_holding_registers(1, 1)
58
+    assert type(r) == list
59
+    assert len(r) == 0
60
+
61
+    r = modbus.read_holding_registers(1, 5)
62
+    assert type(r) == list
63
+    assert len(r) == 4
64
+
65
+    r = modbus.read_holding_registers(1, 126)
66
+    assert type(r) == list
67
+    assert len(r) == 125
68
+
69
+    r = modbus.read_holding_registers(1, 151)
70
+    assert type(r) == list
71
+    assert len(r) == 150
72
+
73
+
74
+
75
+
76
+def test_get_var(set_test_db, serial_conn):
77
+    d_var_types = VariableType.getall()
78
+
79
+    analog = d_var_types['Analog']
80
+    res = modbus.read_holding_registers(analog.start_address, analog.end_address)
81
+    assert type(res) == list
82
+    assert len(res) == analog.end_address - analog.start_address
83
+    for r in res:
84
+        assert type(r) == int
85
+
86
+    integer = d_var_types['Integer']
87
+    try:
88
+        res = modbus.read_holding_registers(integer.start_address, integer.end_address)
89
+    except umodbus.exceptions.IllegalDataAddressError:
90
+        print(f'The start and end addresses are not available [{integer.start_address}, {integer.end_address}]')
91
+    assert type(res) == list
92
+    assert len(res) == integer.end_address - integer.start_address
93
+    for r in res:
94
+        assert type(r) == int

+ 5
- 4
tests/test_variable.py View File

@@ -36,11 +36,12 @@ def test_get_(set_test_db):
36 36
     assert r.status_code == 200
37 37
 
38 38
     d_resp = json.loads(r.content.decode())
39
+    pprint(d_resp)
39 40
     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
41
+    assert '10' in d_resp['A'].keys()
42
+    assert len(d_resp['A'].keys()) == 4
43
+    assert len(d_resp['I'].keys()) == 4
44
+    assert len(d_resp['D'].keys()) == 4
44 45
 
45 46
 
46 47
 @pytest.mark.skip

+ 1
- 0
tests/test_variable_types.py View File

@@ -50,6 +50,7 @@ async def test_get_variable_types(set_test_db):
50 50
     assert 'Digital' in d_resp.keys()
51 51
     assert type(d_resp['Digital']) == dict
52 52
 
53
+@pytest.mark.skip
53 54
 def test_set_variable_types(set_test_db):
54 55
     c = TestClient(app)
55 56
     r = c.post('/', json=json.dumps({

+ 48
- 8
tests/test_variable_values.py View File

@@ -1,6 +1,7 @@
1 1
 #!/usr/bin/env python3
2 2
 import pytest
3 3
 from starlette.authentication import UnauthenticatedUser
4
+from starlette.exceptions import HTTPException 
4 5
 from starlette.testclient import TestClient
5 6
 from unittest.mock import patch, MagicMock
6 7
 from pprint import pprint
@@ -9,10 +10,13 @@ from tempfile import mkstemp
9 10
 from configparser import ConfigParser
10 11
 import os
11 12
 import sys
13
+from datetime import datetime, timedelta
12 14
 
13 15
 from pyheatpump.conf import config
14 16
 from pyheatpump.db import initialize, connect
15 17
 from pyheatpump.variables import app, get_variables, set_variables, ROUTES
18
+from pyheatpump.variable_values import app, get_variable_value, set_variable_value, ROUTES
19
+from pyheatpump.models.variable_value import VariableValue
16 20
 
17 21
 @pytest.fixture(scope='module')
18 22
 def set_test_db():
@@ -25,22 +29,58 @@ def set_test_db():
25 29
     if not initialize(os.path.join(os.getcwd(), 'db/test_variables.sql')):
26 30
         sys.exit(-1)
27 31
 
32
+    if not initialize(os.path.join(os.getcwd(), 'db/test_variable_values.sql')):
33
+        sys.exit(-1)
34
+
28 35
     yield
29 36
 
30 37
     os.unlink(tmpdb)
31 38
 
32 39
 
33
-def test_get_(set_test_db):
40
+def test_get_type_address(set_test_db):
34 41
     c = TestClient(app)
35
-    r = c.get('/')
42
+    r = c.get('/A/10')
36 43
     assert r.status_code == 200
37 44
 
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
45
+    d_resp = r.content.decode()
46
+    assert int(d_resp) == 42
47
+
48
+    try:
49
+        r = c.get('/X/10')
50
+    except HTTPException as e:
51
+        assert e.status_code == 404
52
+
53
+    r = c.get('/A/10/{}'.format(
54
+        (datetime.now() - timedelta(days=1)).isoformat()
55
+    ))
56
+    d_resp = r.content.decode()
57
+    assert int(d_resp) == 20
58
+
59
+    r = c.get('/A/10/{}'.format(
60
+        (datetime.now() - timedelta(days=2)).isoformat()
61
+    ))
62
+    d_resp = r.content.decode()
63
+    assert int(d_resp) == 0
64
+
65
+    r = c.get('/I/5010')
66
+    d_resp = r.content.decode()
67
+    assert int(d_resp) == 42
68
+
69
+    r = c.get('/I/5011')
70
+    d_resp = r.content.decode()
71
+    assert int(d_resp) == 24
72
+
73
+    r = c.get('/I/5010/{}'.format(
74
+        (datetime.now() - timedelta(hours=1)).isoformat()
75
+    ))
76
+    d_resp = r.content.decode()
77
+    assert int(d_resp) == 20
78
+
79
+    r = c.get('/I/5010/{}'.format(
80
+        (datetime.now() - timedelta(hours=2)).isoformat()
81
+    ))
82
+    d_resp = r.content.decode()
83
+    assert int(d_resp) == 0
44 84
 
45 85
 
46 86
 @pytest.mark.skip

Loading…
Cancel
Save