-
Notifications
You must be signed in to change notification settings - Fork 0
/
test.py
172 lines (138 loc) · 5.98 KB
/
test.py
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
import unittest
import mysql.connector
from urllib import request, error, parse
from json import loads, dumps
import base64
class TestDb(unittest.TestCase):
"""Database tests"""
def test_db_access(self):
"""Test database accesss with only-read user."""
conn = mysql.connector.connect(host="localhost", user="blue", passwd="blue21")
cursor = conn.cursor()
cursor.execute("select energy from elecprod.consumpdata where date = '2019-08-01 07:00:00';")
res = cursor.fetchone()
self.assertEqual(float(res[0]), 1.099)
cursor.close()
conn.close()
def test_db_insert(self):
"""Test if only-read user can insert data."""
conn = mysql.connector.connect(host="localhost", user="blue", passwd="blue21")
cursor = conn.cursor()
err = False
try:
cursor.execute("insert into elecprod.consumpdata(date, energy, reactive_energy, power, maximeter, reactive_power, voltage, intensity, power_factor)"
" values(STR_TO_DATE('2019-08-01 00:00:00', '%Y-%m-%d %T'), 1.211, 0.200, 5.156, 5.306, -8.382, 121.955, 53.003, 0.857);")
except mysql.connector.Error:
err = True
self.assertTrue(err)
cursor.close()
conn.close()
class TestApi(unittest.TestCase):
"""Api tests"""
token = None
def test0_error_login(self):
"""Test access the api with wrong password."""
err = False
try:
url = "http://127.0.0.1:5000/login"
req = request.Request(url)
credentials = ('%s:%s' % ("rick", "morty2"))
encoded_credentials = base64.b64encode(credentials.encode('ascii'))
req.add_header('Authorization', 'Basic %s' % encoded_credentials.decode("ascii"))
with request.urlopen(req) as response:
data = response.read()
except error.HTTPError:
err = True
self.assertTrue(err)
def test1_login(self):
"""Test api access with correct credentials."""
url = "http://127.0.0.1:5000/login"
enc_data = parse.urlencode([]).encode("ascii") # To make a post call
req = request.Request(url, data=enc_data)
credentials = ('%s:%s' % ("rick", "morty"))
encoded_credentials = base64.b64encode(credentials.encode('ascii'))
req.add_header('Authorization', 'Basic %s' % encoded_credentials.decode("ascii"))
data = None
with request.urlopen(req) as response:
data = response.read().decode("ascii")
self.assertIn("Authorization_type", data)
self.assertIn("SESSION", data)
self.assertIn("value_token", data)
data_dict = loads(data)
token = data_dict["value_token"]
if len(token) == 0:
raise AssertionError("Token empty")
# To use the token for the rest of the tests
TestApi.token = token
def test2_getDataById(self):
"""Test getDataById."""
id = "100"
url = "http://127.0.0.1:5000/apielec/getDataById?id=" + id
headers = {
"User-Agent": "Api_tests",
"Accept": "application/json",
"Session": TestApi.token
}
req = request.Request(url, headers=headers)
data = None
with request.urlopen(req) as response:
data = response.read().decode("ascii")
data_dict = loads(data)
self.assertEqual(data_dict["statusCode"], 200)
self.assertEqual(data_dict["values"]["numrecs"], 1)
self.assertEqual(data_dict["values"]["records"][0]["id"], id)
def test3_getData(self):
"""Test getData."""
url = "http://127.0.0.1:5000/apielec/getData"
headers = {
"User-Agent": "Api_tests",
"Accept": "application/json",
"Session": TestApi.token
}
req = request.Request(url, headers=headers)
data = None
with request.urlopen(req) as response:
data = response.read().decode("ascii")
data_dict = loads(data)
self.assertEqual(data_dict["statusCode"], 200)
self.assertEqual(data_dict["values"]["numrecs"], 11716)
self.assertEqual(data_dict["values"]["records"][0]["id"], "1")
def test4_getDataByDate(self):
"""Test getDataByDate."""
date = "2019-09-11 10:45:00"
url = "http://127.0.0.1:5000/apielec/getDataByDate?date=" + parse.quote_plus(date)
headers = {
"User-Agent": "Api_tests",
"Accept": "application/json",
"Session": TestApi.token
}
req = request.Request(url, headers=headers)
data = None
with request.urlopen(req) as response:
data = response.read().decode("ascii")
data_dict = loads(data)
self.assertEqual(data_dict["statusCode"], 200)
self.assertEqual(data_dict["values"]["numrecs"], 1)
self.assertEqual(data_dict["values"]["records"][0]["date"], date)
self.assertEqual(data_dict["values"]["records"][0]["id"], "3980")
def test5_getDataByRange(self):
"""Test getDataByRange."""
date = "2019-09-11 10:45:00"
end_date = "2019-09-11 12:%"
url = "http://127.0.0.1:5000/apielec/getDataByRange?date={0}&end_date={1}".format(parse.quote_plus(date), parse.quote_plus(end_date))
headers = {
"User-Agent": "Api_tests",
"Accept": "application/json",
"Session": TestApi.token
}
req = request.Request(url, headers=headers)
data = None
with request.urlopen(req) as response:
data = response.read().decode("ascii")
data_dict = loads(data)
self.assertEqual(data_dict["statusCode"], 200)
self.assertEqual(data_dict["values"]["numrecs"], 6)
self.assertEqual(data_dict["values"]["records"][0]["date"], date)
self.assertEqual(data_dict["values"]["records"][2]["id"], "3982")
if __name__ == "__main__":
unittest.main()