dcfc99e8d7ce6d66005610fc05ac4f97dd76e49d
[oweals/gnunet.git] / src / integration-tests / gnunet_testing.py.in
1 #!@PYTHON@
2 #    This file is part of GNUnet.
3 #    (C) 2010, 2017, 2018 Christian Grothoff (and other contributing authors)
4 #
5 #    GNUnet is free software: you can redistribute it and/or modify it
6 #    under the terms of the GNU Affero General Public License as published
7 #    by the Free Software Foundation, either version 3 of the License,
8 #    or (at your option) any later version.
9 #
10 #    GNUnet is distributed in the hope that it will be useful, but
11 #    WITHOUT ANY WARRANTY; without even the implied warranty of
12 #    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13 #    Affero General Public License for more details.
14 #
15 #    You should have received a copy of the GNU Affero General Public License
16 #    along with this program.  If not, see <http://www.gnu.org/licenses/>.
17 #
18 #    SPDX-License-Identifier: AGPL3.0-or-later
19 #
20 # Functions for integration testing
21 from __future__ import unicode_literals
22 from __future__ import print_function
23 from builtins import object
24 from builtins import str
25 import os
26 import subprocess
27 import sys
28 import shutil
29 import time
30 from gnunet_pyexpect import pexpect
31 import logging
32
33 logger = logging.getLogger()
34 handler = logging.StreamHandler()
35 formatter = logging.Formatter(
36         '%(asctime)s %(name)-12s %(levelname)-8s %(message)s')
37 handler.setFormatter(formatter)
38 logger.addHandler(handler)
39 logger.setLevel(logging.DEBUG)
40
41 class Check(object):
42     def __init__(self, test):
43         self.fulfilled = False
44         self.conditions = list()
45         self.test = test
46
47     def add(self, condition):
48         self.conditions.append(condition)
49
50     def run(self):
51         fulfilled = True
52         pos = 0
53         neg = 0
54         for c in self.conditions:
55             if (False == c.check()):
56                 fulfilled = False
57                 neg += 1
58             else:
59                 pos += 1
60         return fulfilled
61
62     def run_blocking(self, timeout, pos_cont, neg_cont):
63         execs = 0
64         res = False
65         while ((False == res) and (execs < timeout)):
66             res = self.run()
67             time.sleep(1)
68             execs += 1
69         if ((False == res) and (execs >= timeout)):
70             logger.debug('Check had timeout after %s seconds', str(timeout))
71             # print(('Check had timeout after ' + str(timeout) + ' seconds'))
72             neg_cont(self)
73         elif ((False == res) and (execs < timeout)):
74             if (None != neg_cont):
75                 neg_cont(self)
76         else:
77             if (None != pos_cont):
78                 pos_cont(self)
79         return res
80
81     def run_once(self, pos_cont, neg_cont):
82         execs = 0
83         res = False
84         res = self.run()
85         if ((res == False) and (neg_cont != None)):
86             neg_cont(self)
87         if ((res == True) and (pos_cont != None)):
88             pos_cont(self)
89         return res
90
91     def evaluate(self, failed_only):
92         pos = 0
93         neg = 0
94         for c in self.conditions:
95             if (False == c.evaluate(failed_only)):
96                 neg += 1
97             else:
98                 pos += 1
99         # print((str(pos) + ' out of ' + str(pos+neg) + ' conditions fulfilled'))
100         logger.debug('%s out of %s conditions fulfilled', str(pos), str(pos+neg))
101         return self.fulfilled
102
103     def reset(self):
104         self.fulfilled = False
105         for c in self.conditions:
106             c.fulfilled = False
107
108
109 class Condition(object):
110     def __init__(self):
111         self.fulfilled = False
112         self.type = 'generic'
113
114     def __init__(self, type):
115         self.fulfilled = False
116         self.type = type
117
118     def check(self):
119         return False
120
121     def evaluate(self, failed_only):
122         if ((self.fulfilled == False) and (failed_only == True)):
123             # print(str(self.type) + 'condition for was ' + str(self.fulfilled))
124             logger.debug('%s condition for was %s', str(self.type), str(self.fulfilled))
125         elif (failed_only == False):
126             # print(str(self.type) + 'condition for was ' + str(self.fulfilled))
127             logger.debug('%s condition for was %s', str(self.type), str(self.fulfilled))
128         return self.fulfilled
129
130
131 class FileExistCondition(Condition):
132     def __init__(self, file):
133         self.fulfilled = False
134         self.type = 'file'
135         self.file = file
136
137     def check(self):
138         if (self.fulfilled == False):
139             res = os.path.isfile(self.file)
140             if (res == True):
141                 self.fulfilled = True
142                 return True
143             else:
144                 return False
145         else:
146             return True
147
148     def evaluate(self, failed_only):
149         if ((self.fulfilled == False) and (failed_only == True)):
150             # print(str(self.type) +
151             #      'condition for file ' +
152             #      self.file +
153             #      ' was ' +
154             #      str(self.fulfilled))
155             logger.debug('%s confition for file %s was %s', str(self.type), self.file, str(self.fulfilled))
156         elif (failed_only == False):
157             # print(str(self.type) +
158             #      'condition for file ' +
159             #      self.file +
160             #      ' was ' +
161             #      str(self.fulfilled))
162             logger.debug('%s confition for file %s was %s', str(self.type), self.file, str(self.fulfilled))
163         return self.fulfilled
164
165
166 class StatisticsCondition(Condition):
167     def __init__(self, peer, subsystem, name, value):
168         self.fulfilled = False
169         self.type = 'statistics'
170         self.peer = peer
171         self.subsystem = subsystem
172         self.name = name
173         self.value = value
174         self.result = -1
175
176     def check(self):
177         if (self.fulfilled == False):
178             self.result = self.peer.get_statistics_value(self.subsystem, self.name)
179             if (str(self.result) == str(self.value)):
180                 self.fulfilled = True
181                 return True
182             else:
183                 return False
184         else:
185             return True
186
187     def evaluate(self, failed_only):
188         if (self.result == -1):
189             res = b'NaN'
190         else:
191             res = str(self.result).encode('utf-8')
192         if (self.fulfilled == False):
193             fail = b" FAIL!"
194             op = b" != "
195         else:
196             fail = b""
197             op = b" == "
198         if (((self.fulfilled == False) and (failed_only == True)) or (failed_only == False)):
199             # print(self.peer.id[:4] +
200             #       b" " +
201             #       self.peer.cfg.encode('utf-8') +
202             #       b" " +
203             #       str(self.type).encode('utf-8') +
204             #       b' condition in subsystem "' +
205             #       self.subsystem.encode('utf-8').ljust(12) +
206             #       b'" : "' +
207             #       self.name.encode('utf-8').ljust(30) +
208             #       b'" : (expected/real value) ' +
209             #       str(self.value).encode('utf-8') +
210             #       op +
211             #       res +
212             #       fail)
213             logger.debug('%s %s %s condition in subsystem %s : %s : (expected/real value) %s %s %s %s', self.peer.id[:4], self.peer.cfg.encode('utf-8'), str(self.type).encode('utf-8'), self.subsystem.encode('utf-8').ljust(12), self.name.encode('utf-8').ljust(30), str(self.value).encode('utf-8'), op, res, fail)
214         return self.fulfilled
215
216
217 # Specify two statistic values and check if they are equal
218 class EqualStatisticsCondition(Condition):
219     def __init__(self, peer, subsystem, name, peer2, subsystem2, name2):
220         self.fulfilled = False
221         self.type = 'equalstatistics'
222         self.peer = peer
223         self.subsystem = subsystem
224         self.name = name
225         self.result = -1
226         self.peer2 = peer2
227         self.subsystem2 = subsystem2
228         self.name2 = name2
229         self.result2 = -1
230
231     def check(self):
232         if (self.fulfilled == False):
233             self.result = self.peer.get_statistics_value(self.subsystem, self.name)
234             self.result2 = self.peer2.get_statistics_value(self.subsystem2, self.name2)
235             if (str(self.result) == str(self.result2)):
236                 self.fulfilled = True
237                 return True
238             else:
239                 return False
240         else:
241             return True
242
243     def evaluate(self, failed_only):
244         if (self.result == -1):
245             res = b'NaN'
246         else:
247             res = str(self.result).encode('utf-8')
248         if (self.result2 == -1):
249             res2 = b'NaN'
250         else:
251             res2 = str(self.result2).encode('utf-8')
252         if (self.fulfilled == False):
253             fail = b" FAIL!"
254             op = b" != "
255         else:
256             fail = b""
257             op = b" == "
258         if (((self.fulfilled == False) and (failed_only == True)) or (failed_only == False)):
259             # print(self.peer.id[:4] +
260             #       b' "' +
261             #       self.subsystem.encode('utf-8').ljust(12) +
262             #       b'" "' +
263             #       self.name.encode('utf-8').ljust(30) +
264             #       b'" == ' +
265             #       str(self.result).encode('utf-8') +
266             #       b" " +
267             #       self.peer2.id[:4] +
268             #       b' "' +
269             #       self.subsystem2.encode('utf-8').ljust(12) +
270             #       b'" ' +
271             #       self.name2.encode('utf-8').ljust(30) +
272             #       b'" ' +
273             #       str(self.result2).encode('utf-8'))
274             logger.debug('%s %s %s == %s %s %s %s %s', self.peer.id[:4], self.subsystem.encode('utf-8').ljust(12), self.name.encode('utf-8').ljust(30), str(self.result).encode('utf-8'), self.peer2.id[:4], self.subsystem2.encode('uft-8').ljust(12), self.name2.encode('utf-8').ljust(30), str(self.result2).encode('utf-8'))
275         return self.fulfilled
276
277
278 class Test(object):
279     def __init__(self, testname, verbose):
280         self.peers = list()
281         self.verbose = verbose
282         self.name = testname
283         srcdir = "../.."
284         gnunet_pyexpect_dir = os.path.join(srcdir, "contrib/scripts")
285         if gnunet_pyexpect_dir not in sys.path:
286             sys.path.append(gnunet_pyexpect_dir)
287         self.gnunetarm = ''
288         self.gnunetstatistics = ''
289         if os.name == 'posix':
290             self.gnunetarm = 'gnunet-arm'
291             self.gnunetstatistics = 'gnunet-statistics'
292             self.gnunetpeerinfo = 'gnunet-peerinfo'
293         elif os.name == 'nt':
294             self.gnunetarm = 'gnunet-arm.exe'
295             self.gnunetstatistics = 'gnunet-statistics.exe'
296             self.gnunetpeerinfo = 'gnunet-peerinfo.exe'
297         if os.name == "nt":
298             shutil.rmtree(os.path.join(os.getenv("TEMP"), testname), True)
299         else:
300             shutil.rmtree("/tmp/" + testname, True)
301
302     def add_peer(self, peer):
303         self.peers.append(peer)
304
305     def p(self, msg):
306         if (self.verbose == True):
307             print(msg)
308
309
310 class Peer(object):
311     def __init__(self, test, cfg_file):
312         if (False == os.path.isfile(cfg_file)):
313             # print(("Peer cfg " + cfg_file + ": FILE NOT FOUND"))
314             logger.debug('Peer cfg %s : FILE NOT FOUND', cfg_file)
315         self.id = "<NaN>"
316         self.test = test
317         self.started = False
318         self.cfg = cfg_file
319
320     def __del__(self):
321         if (self.started == True):
322             # print('ERROR! Peer using cfg ' + self.cfg + ' was not stopped')
323             logger.debug('ERROR! Peer using cfg %s was not stopped', self.cfg)
324             ret = self.stop()
325             if (False == ret):
326                 # print('ERROR! Peer using cfg ' +
327                 #       self.cfg +
328                 #       ' could not be stopped')
329                 logger.debug('ERROR! Peer using cfg %s could not be stopped', self.cfg)
330                 self.started = False
331             return ret
332         else:
333             return False
334
335     def start(self):
336         self.test.p("Starting peer using cfg " + self.cfg)
337         try:
338             server = subprocess.Popen([self.test.gnunetarm, '-sq', '-c', self.cfg])
339             server.communicate()
340         except OSError:
341             # print("Can not start peer")
342             logger.debug('Can not start peer')
343             self.started = False
344             return False
345         self.started = True
346         test = ''
347         try:
348             server = pexpect()
349             server.spawn(None, [self.test.gnunetpeerinfo, '-c', self.cfg, '-s'], stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
350             test = server.read("stdout", 1024)
351         except OSError:
352             # print("Can not get peer identity")
353             logger.debug('Can not get peer identity')
354         test = (test.split(b'`')[1])
355         self.id = test.split(b'\'')[0]
356         return True
357
358     def stop(self):
359         if (self.started == False):
360             return False
361         self.test.p("Stopping peer using cfg " + self.cfg)
362         try:
363             server = subprocess.Popen([self.test.gnunetarm, '-eq', '-c', self.cfg])
364             server.communicate()
365         except OSError:
366             # print("Can not stop peer")
367             logger.debug('Can not stop peer')
368             return False
369         self.started = False
370         return True
371
372     def get_statistics_value(self, subsystem, name):
373         server = pexpect()
374         server.spawn(None, [self.test.gnunetstatistics, '-c', self.cfg, '-q', '-n', name, '-s', subsystem], stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
375         # server.expect ("stdout", re.compile (r""))
376         test = server.read("stdout", 10240)
377         tests = test.partition(b'\n')
378         # On W32 GNUnet outputs with \r\n, rather than \n
379         if os.name == 'nt' and tests[1] == b'\n' and tests[0][-1] == b'\r':
380             tests = (tests[0][:-1], tests[1], tests[2])
381         tests = tests[0]
382         # print("running gnunet-statistics " + self.cfg + " for " + name + "/" + subsystem + " yields " + tests.decode("utf-8"))
383         logger.debug('running gnunet-statistics %s for %s "/" %s yields %s', self.cfg, name, subsystem, test.decode("utf-8"))
384         if (tests.isdigit() == True):
385             return tests
386         else:
387             # print("Invalid statistics value: " + str(tests) + " is not a number!")
388             logger.debug('Invalid statistics value: %s is not a number!', str(tests))
389             return -1