Blame view

src/majordome/majordome_test.py 8.53 KB
d51386bf   Etienne Pallier   new file majordom...
1
2
3
4
5
6
7
8
9
10
#!/usr/bin/env python

import os
import sys
import django
import subprocess
import fileinput
import time
from django.shortcuts import get_object_or_404
from django.conf import settings as djangosettings
cb0206d5   Etienne Pallier   assert that strin...
11
import datetime
d243a3ef   Etienne Pallier   Bugfix majordome_...
12
13
14
15
# DONE LATER:
#sys.path.append('..')
#from common.models import Config, PlcDeviceStatus

d51386bf   Etienne Pallier   new file majordom...
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38


DEBUG=True

agent="majordome"

fixture = 'tests/majordome_test'

#venv_bin = '../../private/venv_py3_pyros/bin/python'
venv_bin = '../private/venv_py3_pyros/bin/python'
venv_bin2 = '../../private/venv_py3_pyros/bin/python'






def tearDown(self):
    os.chdir('..')
    self.replacePatternInFile("MAJORDOME_TEST = True", "MAJORDOME_TEST = False", "pyros/settings.py")
    os.chdir('majordome')


d243a3ef   Etienne Pallier   Bugfix majordome_...
39
def replacePatternInFileOrError(pattern, replace, file_path):
cb0206d5   Etienne Pallier   assert that strin...
40
41
42
43
44
    with fileinput.FileInput(file_path, inplace=True, backup='.bak') as file:
        for line in file:
            print(line.replace(pattern, replace), end='')
    # Now, check that replacement has been done or ERROR !!!
    FOUND=False
737529b0   Etienne Pallier   bugfixes and impr...
45
46
    #with fileinput.FileInput(file_path) as file:
    with open(file_path) as file:
cb0206d5   Etienne Pallier   assert that strin...
47
        for line in file:
737529b0   Etienne Pallier   bugfixes and impr...
48
49
            #if replace in line:
            if line.startswith(replace):
cb0206d5   Etienne Pallier   assert that strin...
50
51
                FOUND = True
                break
737529b0   Etienne Pallier   bugfixes and impr...
52
    #if FOUND: print("pattern "+replace+" found in file "+file_path)
cb0206d5   Etienne Pallier   assert that strin...
53
54
55
56
    if not FOUND: raise(Exception("pattern "+replace+" not found in file "+file_path))

    

d51386bf   Etienne Pallier   new file majordom...
57
58
59
60
61
62
63
64
65
66
67

def execProcessAsync(command):
    #self.printFullTerm(Colors.BLUE, "Executing command [" + command + "]")
    p = subprocess.Popen(command, shell=True)
    '''
    self.subproc.append((p, command))
    self.printFullTerm(Colors.GREEN, "Process launched successfully")
    self.addExecuted(self.current_command, command)
    '''
    return p

d243a3ef   Etienne Pallier   Bugfix majordome_...
68
def execProcessFromVenvSync(command: str):
b6d6bfd5   Etienne Pallier   petit bugfix
69
    print(f"Execute command from venv as a process: {command}")
d51386bf   Etienne Pallier   new file majordom...
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
    command = venv_bin + ' ' + command
    args = command.split()
    process = subprocess.Popen(args)
    process.wait()
    if process.returncode == 0:
        print("Process executed successfully")
    else:
        print("Process execution failed")
    return process.returncode

def execProcessFromVenvAsync(command: str):
    command = venv_bin2 + ' ' + command
    args = command.split()
    #self.printFullTerm(Colors.BLUE, "Executing command from venv [" + str(' '.join(args[1:])) + "]")
    p = subprocess.Popen(args)
    #self.subproc.append((p, ' '.join(args[1:])))
    #self.printFullTerm(Colors.GREEN, "Process launched successfully")
    #self.addExecuted(self.current_command, str(' '.join(args[1:])))
    return p


def init_database():
    # Go into src/
    #os.chdir('..')
    print("Current directory : " + str(os.getcwd()))
b6d6bfd5   Etienne Pallier   petit bugfix
95
96
97
98
99
    # If executed the very first time, it raises errors, so executes it later
    #execProcessFromVenvSync("manage.py flush  --noinput")
    execProcessFromVenvSync("manage.py makemigrations")
    execProcessFromVenvSync("manage.py migrate")
    # Executed here, it is ok
d243a3ef   Etienne Pallier   Bugfix majordome_...
100
    execProcessFromVenvSync("manage.py flush  --noinput")
b6d6bfd5   Etienne Pallier   petit bugfix
101
    # Do we really need now to make migrations and to migrate again (a second time) ? (not sure)
d243a3ef   Etienne Pallier   Bugfix majordome_...
102
103
    execProcessFromVenvSync("manage.py makemigrations")
    execProcessFromVenvSync("manage.py migrate")
b6d6bfd5   Etienne Pallier   petit bugfix
104
    # Load fixture:
d243a3ef   Etienne Pallier   Bugfix majordome_...
105
    execProcessFromVenvSync("manage.py loaddata misc" + os.sep + "fixtures" + os.sep + fixture)
d51386bf   Etienne Pallier   new file majordom...
106
107
108
109
110
111
112
113
114

def getConfigFromDB():
    return get_object_or_404(Config, id=1)

def changeDirectory(path):
    #if DEBUG: print("Moving to : " + path)
    os.chdir(path)
    if DEBUG: print("NEW Current directory : " + str(os.getcwd()))

d243a3ef   Etienne Pallier   Bugfix majordome_...
115
def assert_majordome_has_now_state(state:str) -> bool: 
d51386bf   Etienne Pallier   new file majordom...
116
    config = getConfigFromDB()
737529b0   Etienne Pallier   bugfixes and impr...
117
    print()
d243a3ef   Etienne Pallier   Bugfix majordome_...
118
119
    #print("Majordome state should now be", config.pyros_state)
    print("=> Majordome state should now be", state)
d51386bf   Etienne Pallier   new file majordom...
120
    assert config.pyros_state == state
737529b0   Etienne Pallier   bugfixes and impr...
121
122
    print("=> CHECKED")
    print()
d51386bf   Etienne Pallier   new file majordom...
123

d243a3ef   Etienne Pallier   Bugfix majordome_...
124
125
126
127
128
129
130
131
132
133
134
def print_step_message(step_num:int, message:str):
    print()
    print('--------------')
    print(f'{step_num}) {message}')
    print('--------------')
    
def go_sleeping(nbsec:int):
    print(f"GO TO SLEEP {nbsec} seconds...")
    time.sleep(nbsec)
    print("...STOP SLEEPING")
    
d51386bf   Etienne Pallier   new file majordom...
135
136
137
138




d243a3ef   Etienne Pallier   Bugfix majordome_...
139
i=0
d51386bf   Etienne Pallier   new file majordom...
140
141
print("Current directory : " + str(os.getcwd()))

d243a3ef   Etienne Pallier   Bugfix majordome_...
142
143

i+=1; print_step_message(i, 'Change pyros/settings just for this test, so that it uses test database')
d51386bf   Etienne Pallier   new file majordom...
144
145
# Go into src/
os.chdir('..')
d243a3ef   Etienne Pallier   Bugfix majordome_...
146
replacePatternInFileOrError("MAJORDOME_TEST = False", "MAJORDOME_TEST = True", "pyros/settings.py")
d51386bf   Etienne Pallier   new file majordom...
147
148
#os.chdir('majordome')

d243a3ef   Etienne Pallier   Bugfix majordome_...
149

b6d6bfd5   Etienne Pallier   petit bugfix
150
i+=1; print_step_message(i, 'Init test database')
d51386bf   Etienne Pallier   new file majordom...
151
152
init_database()

d243a3ef   Etienne Pallier   Bugfix majordome_...
153
154

i+=1; print_step_message(i, 'Django setup')
d51386bf   Etienne Pallier   new file majordom...
155
sys.path.append('..')
737529b0   Etienne Pallier   bugfixes and impr...
156
#print(sys.path)
d51386bf   Etienne Pallier   new file majordom...
157
158
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "src.pyros.settings")
django.setup()
d243a3ef   Etienne Pallier   Bugfix majordome_...
159
assert djangosettings.DATABASES['default']['NAME'] == 'pyros_test'
d51386bf   Etienne Pallier   new file majordom...
160
161


d243a3ef   Etienne Pallier   Bugfix majordome_...
162
i+=1; print_step_message(i, 'Get config')
d51386bf   Etienne Pallier   new file majordom...
163
164
# Needs sys.path.append('..') 
from common.models import Config, PlcDeviceStatus
d51386bf   Etienne Pallier   new file majordom...
165
166
167
168
169
170
171
172
173
174
175
176
config = get_object_or_404(Config, id=1)
print("config id is", config.id)
print("config latitude is", config.latitude)
print("config global mode is", config.global_mode)
print("config row_data_save_frequency is", config.row_data_save_frequency)

#with print_lock:
print("global mode is", getConfigFromDB().global_mode)
#sys.stdout.write("global mode")
#sys.stdout.flush()
print("global mode is", getConfigFromDB().global_mode)
print("DB1 used is:", djangosettings.DATABASES['default']['NAME'])
d243a3ef   Etienne Pallier   Bugfix majordome_...
177
178
go_sleeping(2)
# ...
d51386bf   Etienne Pallier   new file majordom...
179
180


d243a3ef   Etienne Pallier   Bugfix majordome_...
181
'''
d51386bf   Etienne Pallier   new file majordom...
182
# Launch the Majordome agent
d243a3ef   Etienne Pallier   Bugfix majordome_...
183
184
'''
i+=1; print_step_message(i, 'Launch Majordome agent')
d51386bf   Etienne Pallier   new file majordom...
185
186
187
188
189
190
os.chdir(agent)
#p = execProcessFromVenvAsync(venv_bin + ' start_agent_'+agent+'_from_test.py')
#p = execProcessFromVenvAsync(venv_bin + ' start_agent_'+agent+'.py')
majordome = execProcessFromVenvAsync("start_agent_"+agent+'.py')
#p = self.execProcessFromVenvAsync('./start_agent_'+agent+'.py')
#p.wait()
d243a3ef   Etienne Pallier   Bugfix majordome_...
191
192
go_sleeping(10)
# ...
d51386bf   Etienne Pallier   new file majordom...
193
194


d243a3ef   Etienne Pallier   Bugfix majordome_...
195
'''
d51386bf   Etienne Pallier   new file majordom...
196
# START TESTING Majordome
d243a3ef   Etienne Pallier   Bugfix majordome_...
197
198
'''
i+=1; print_step_message(i, 'Start testing Majordome states')
d51386bf   Etienne Pallier   new file majordom...
199
200
201
plcstatus = get_object_or_404(PlcDeviceStatus, id=1)

# Now, Majordome should be in state "PASSIVE no PLC" (waiting for PLC)
d243a3ef   Etienne Pallier   Bugfix majordome_...
202
assert_majordome_has_now_state("PASSIVE_NO_PLC")
d51386bf   Etienne Pallier   new file majordom...
203

d243a3ef   Etienne Pallier   Bugfix majordome_...
204
print("\n- I now simulate that PLC is OK:")
d51386bf   Etienne Pallier   new file majordom...
205
206
# Let's pretend that PLC is now OK (via DB) 
# ==> check that it goes to state "PASSIVE" (waiting for PLC "AUTO")
cb0206d5   Etienne Pallier   assert that strin...
207
208
209
#plcstatus.created = "2018-07-24 11:49:49"
# ex: '2018-07-27T10:12:38.875112'
plcstatus.created = datetime.datetime.now().isoformat()
d51386bf   Etienne Pallier   new file majordom...
210
plcstatus.save()
d243a3ef   Etienne Pallier   Bugfix majordome_...
211
212
213
go_sleeping(5)
# ...
assert_majordome_has_now_state("PASSIVE")
d51386bf   Etienne Pallier   new file majordom...
214

d243a3ef   Etienne Pallier   Bugfix majordome_...
215
print("\n- I now simulate that PLC is AUTO:")
d51386bf   Etienne Pallier   new file majordom...
216
217
218
219
# Let's pretend that PLC is now AUTO (via DB)
# ==> check that it goes to state "STANDBY"
plcstatus.plc_mode = "AUTO"
plcstatus.save()
d243a3ef   Etienne Pallier   Bugfix majordome_...
220
221
222
go_sleeping(15)
# ...
assert_majordome_has_now_state("Standby")
d51386bf   Etienne Pallier   new file majordom...
223

d243a3ef   Etienne Pallier   Bugfix majordome_...
224
print("\n- I now simulate that Majordome is going REMOTE mode:")
d51386bf   Etienne Pallier   new file majordom...
225
226
227
228
229
# Let's pretend that we are going REMOTE mode
# ==> check that it goes to state "REMOTE"
config.global_mode = False
config.lock = False
config.save()
d243a3ef   Etienne Pallier   Bugfix majordome_...
230
231
232
go_sleeping(10)
# ...
assert_majordome_has_now_state("Remote")
d51386bf   Etienne Pallier   new file majordom...
233
234
235
236
237
238
239
240
241
242

# Let's pretend that PLC is now UNSAFE
# ==> check that shutter is closing
#TODO:
#plc_status.is_safe

# Let's pretend that PLC is now SAFE again
# ==> check that shutter is opening
#TODO:

d243a3ef   Etienne Pallier   Bugfix majordome_...
243
print("\n- I now simulate that Majordome is going SCHEDULER mode:")
d51386bf   Etienne Pallier   new file majordom...
244
245
246
247
248
# Let's pretend that we are going SCHEDULER mode
# ==> check that it goes to state "STANDBY"
config.global_mode = True
config.lock = False
config.save()
d243a3ef   Etienne Pallier   Bugfix majordome_...
249
250
251
go_sleeping(10)
# ...
assert_majordome_has_now_state("Standby")
d51386bf   Etienne Pallier   new file majordom...
252
253
254
255
256
257
258
259
260
261
262

# Let's set conditions for going to SCHEDULER mode
# ==> check that it goes to state "SCHEDULER"
#TODO:
# self.is_night() and self.plc_is_safe() and self.config.ack and not self.config.lock

# Let's set conditions for leaving the SCHEDULER mode
# ==> check that it goes to state "STANDBY"
#TODO:


d243a3ef   Etienne Pallier   Bugfix majordome_...
263
'''
d51386bf   Etienne Pallier   new file majordom...
264
# KILL agent Majordome (using DB config table)
d243a3ef   Etienne Pallier   Bugfix majordome_...
265
266
'''
i+=1; print_step_message(i, 'Stop (kill) Majordome agent process')
d51386bf   Etienne Pallier   new file majordom...
267
268
269
270
# Let's set conditions for stopping the Majordome
# ==> check that it goes to state config.majordome_state = "RUNNING"
config.majordome_state = "STOP"
config.save()
d243a3ef   Etienne Pallier   Bugfix majordome_...
271
272
go_sleeping(5)
# ...
d51386bf   Etienne Pallier   new file majordom...
273
274
275
276
277
278
279
280
281
config = getConfigFromDB()
print("config is", config.majordome_state)
assert config.majordome_state == "RUNNING"

##majordome.kill()

#self.execProcessAsync("ps aux | grep \"start_agent_majordome.py\" | awk '{ print $2 }' | xargs kill")
#self.execProcessAsync("ps aux | grep start_agent_majordome.py | awk '{ print $2 }' | xargs kill")
#'''
d243a3ef   Etienne Pallier   Bugfix majordome_...
282
283
284
go_sleeping(5)
# ...

d51386bf   Etienne Pallier   new file majordom...
285

d51386bf   Etienne Pallier   new file majordom...
286
287
288
#thread_majordome.join()
#thread_majordome.killExecutingSequence()

d243a3ef   Etienne Pallier   Bugfix majordome_...
289
i+=1; print_step_message(i, 'Restore pyros/settings as before')
d51386bf   Etienne Pallier   new file majordom...
290
os.chdir('..')
d243a3ef   Etienne Pallier   Bugfix majordome_...
291
replacePatternInFileOrError("MAJORDOME_TEST = True", "MAJORDOME_TEST = False", "pyros/settings.py")
d51386bf   Etienne Pallier   new file majordom...
292
#os.chdir('majordome')
d243a3ef   Etienne Pallier   Bugfix majordome_...
293