gnunet_testing.py.in 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327
  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. import os
  22. import subprocess
  23. import sys
  24. import shutil
  25. import time
  26. from gnunet_pyexpect import pexpect
  27. import logging
  28. logger = logging.getLogger()
  29. handler = logging.StreamHandler()
  30. formatter = logging.Formatter(
  31. '%(asctime)s %(name)-12s %(levelname)-8s %(message)s')
  32. handler.setFormatter(formatter)
  33. logger.addHandler(handler)
  34. logger.setLevel(logging.DEBUG)
  35. class Check(object):
  36. def __init__(self, test):
  37. self.fulfilled = False
  38. self.conditions = list()
  39. self.test = test
  40. def add(self, condition):
  41. self.conditions.append(condition)
  42. def run(self):
  43. fulfilled = True
  44. pos = 0
  45. neg = 0
  46. for c in self.conditions:
  47. if (False == c.check()):
  48. fulfilled = False
  49. neg += 1
  50. else:
  51. pos += 1
  52. return fulfilled
  53. def run_blocking(self, timeout, pos_cont, neg_cont):
  54. execs = 0
  55. res = False
  56. while ((False == res) and (execs < timeout)):
  57. res = self.run()
  58. time.sleep(1)
  59. execs += 1
  60. if ((False == res) and (execs >= timeout)):
  61. logger.debug('Check had timeout after %s seconds', str(timeout))
  62. neg_cont(self)
  63. elif ((False == res) and (execs < timeout)):
  64. if (None != neg_cont):
  65. neg_cont(self)
  66. else:
  67. if (None != pos_cont):
  68. pos_cont(self)
  69. return res
  70. def run_once(self, pos_cont, neg_cont):
  71. execs = 0
  72. res = False
  73. res = self.run()
  74. if ((res == False) and (neg_cont != None)):
  75. neg_cont(self)
  76. if ((res == True) and (pos_cont != None)):
  77. pos_cont(self)
  78. return res
  79. def evaluate(self, failed_only):
  80. pos = 0
  81. neg = 0
  82. for c in self.conditions:
  83. if (False == c.evaluate(failed_only)):
  84. neg += 1
  85. else:
  86. pos += 1
  87. logger.debug('%s out of %s conditions fulfilled', str(pos), str(pos+neg))
  88. return self.fulfilled
  89. def reset(self):
  90. self.fulfilled = False
  91. for c in self.conditions:
  92. c.fulfilled = False
  93. class Condition(object):
  94. def __init__(self):
  95. self.fulfilled = False
  96. self.type = 'generic'
  97. def __init__(self, type):
  98. self.fulfilled = False
  99. self.type = type
  100. def check(self):
  101. return False
  102. def evaluate(self, failed_only):
  103. if ((self.fulfilled == False) and (failed_only == True)):
  104. logger.debug('%s condition for was %s', str(self.type), str(self.fulfilled))
  105. elif (failed_only == False):
  106. logger.debug('%s condition for was %s', str(self.type), str(self.fulfilled))
  107. return self.fulfilled
  108. class FileExistCondition(Condition):
  109. def __init__(self, file):
  110. self.fulfilled = False
  111. self.type = 'file'
  112. self.file = file
  113. def check(self):
  114. if (self.fulfilled == False):
  115. res = os.path.isfile(self.file)
  116. if (res == True):
  117. self.fulfilled = True
  118. return True
  119. else:
  120. return False
  121. else:
  122. return True
  123. def evaluate(self, failed_only):
  124. if ((self.fulfilled == False) and (failed_only == True)):
  125. logger.debug('%s confition for file %s was %s', str(self.type), self.file, str(self.fulfilled))
  126. elif (failed_only == False):
  127. logger.debug('%s confition for file %s was %s', str(self.type), self.file, str(self.fulfilled))
  128. return self.fulfilled
  129. class StatisticsCondition(Condition):
  130. def __init__(self, peer, subsystem, name, value):
  131. self.fulfilled = False
  132. self.type = 'statistics'
  133. self.peer = peer
  134. self.subsystem = subsystem
  135. self.name = name
  136. self.value = str(value)
  137. self.result = -1
  138. def check(self):
  139. if (self.fulfilled == False):
  140. self.result = self.peer.get_statistics_value(self.subsystem, self.name)
  141. if (self.result == self.value):
  142. self.fulfilled = True
  143. return True
  144. else:
  145. return False
  146. else:
  147. return True
  148. def evaluate(self, failed_only):
  149. if (self.fulfilled == False):
  150. fail = " FAIL!"
  151. op = " != "
  152. else:
  153. fail = ""
  154. op = " == "
  155. if (((self.fulfilled == False) and (failed_only == True)) or (failed_only == False)):
  156. logger.debug('%s %s condition in subsystem %s: %s: (expected/real value) %s %s %s %s', self.peer.id[:4].decode("utf-8"), self.peer.cfg, self.subsystem.ljust(12), self.name.ljust(30), self.value, op, self.result, fail)
  157. return self.fulfilled
  158. # Specify two statistic values and check if they are equal
  159. class EqualStatisticsCondition(Condition):
  160. def __init__(self, peer, subsystem, name, peer2, subsystem2, name2):
  161. self.fulfilled = False
  162. self.type = 'equalstatistics'
  163. self.peer = peer
  164. self.subsystem = subsystem
  165. self.name = name
  166. self.result = -1
  167. self.peer2 = peer2
  168. self.subsystem2 = subsystem2
  169. self.name2 = name2
  170. self.result2 = -1
  171. def check(self):
  172. if (self.fulfilled == False):
  173. self.result = self.peer.get_statistics_value(self.subsystem, self.name)
  174. self.result2 = self.peer2.get_statistics_value(self.subsystem2, self.name2)
  175. if (self.result == self.result2):
  176. self.fulfilled = True
  177. return True
  178. else:
  179. return False
  180. else:
  181. return True
  182. def evaluate(self, failed_only):
  183. if (((self.fulfilled == False) and (failed_only == True)) or (failed_only == False)):
  184. logger.debug('%s %s %s == %s %s %s %s %s', self.peer.id[:4], self.subsystem.ljust(12), self.name.ljust(30), self.result, self.peer2.id[:4], self.subsystem2.ljust(12), self.name2.ljust(30), self.result2)
  185. return self.fulfilled
  186. class Test(object):
  187. def __init__(self, testname, verbose):
  188. self.peers = list()
  189. self.verbose = verbose
  190. self.name = testname
  191. srcdir = "../.."
  192. gnunet_pyexpect_dir = os.path.join(srcdir, "contrib/scripts")
  193. if gnunet_pyexpect_dir not in sys.path:
  194. sys.path.append(gnunet_pyexpect_dir)
  195. self.gnunetarm = ''
  196. self.gnunetstatistics = ''
  197. if os.name == 'posix':
  198. self.gnunetarm = 'gnunet-arm'
  199. self.gnunetstatistics = 'gnunet-statistics'
  200. self.gnunetpeerinfo = 'gnunet-peerinfo'
  201. elif os.name == 'nt':
  202. self.gnunetarm = 'gnunet-arm.exe'
  203. self.gnunetstatistics = 'gnunet-statistics.exe'
  204. self.gnunetpeerinfo = 'gnunet-peerinfo.exe'
  205. if os.name == "nt":
  206. shutil.rmtree(os.path.join(os.getenv("TEMP"), testname), True)
  207. else:
  208. shutil.rmtree("/tmp/" + testname, True)
  209. def add_peer(self, peer):
  210. self.peers.append(peer)
  211. def p(self, msg):
  212. if (self.verbose == True):
  213. print(msg)
  214. class Peer(object):
  215. def __init__(self, test, cfg_file):
  216. if (False == os.path.isfile(cfg_file)):
  217. # print(("Peer cfg " + cfg_file + ": FILE NOT FOUND"))
  218. logger.debug('Peer cfg %s : FILE NOT FOUND', cfg_file)
  219. self.id = "<NaN>"
  220. self.test = test
  221. self.started = False
  222. self.cfg = cfg_file
  223. def __del__(self):
  224. if (self.started == True):
  225. # print('ERROR! Peer using cfg ' + self.cfg + ' was not stopped')
  226. logger.debug('ERROR! Peer using cfg %s was not stopped', self.cfg)
  227. ret = self.stop()
  228. if (False == ret):
  229. # print('ERROR! Peer using cfg ' +
  230. # self.cfg +
  231. # ' could not be stopped')
  232. logger.debug('ERROR! Peer using cfg %s could not be stopped', self.cfg)
  233. self.started = False
  234. return ret
  235. else:
  236. return False
  237. def start(self):
  238. os.unsetenv ("XDG_CONFIG_HOME")
  239. os.unsetenv ("XDG_DATA_HOME")
  240. os.unsetenv ("XDG_CACHE_HOME")
  241. self.test.p("Starting peer using cfg " + self.cfg)
  242. try:
  243. server = subprocess.Popen([self.test.gnunetarm, '-sq', '-c', self.cfg])
  244. server.communicate()
  245. except OSError:
  246. # print("Can not start peer")
  247. logger.debug('Can not start peer')
  248. self.started = False
  249. return False
  250. self.started = True
  251. test = ''
  252. try:
  253. server = pexpect()
  254. server.spawn(None, [self.test.gnunetpeerinfo, '-c', self.cfg, '-s'], stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
  255. test = server.read("stdout", 1024)
  256. except OSError:
  257. # print("Can not get peer identity")
  258. logger.debug('Can not get peer identity')
  259. test = (test.split(b'`')[1])
  260. self.id = test.split(b'\'')[0]
  261. return True
  262. def stop(self):
  263. if (self.started == False):
  264. return False
  265. self.test.p("Stopping peer using cfg " + self.cfg)
  266. try:
  267. server = subprocess.Popen([self.test.gnunetarm, '-eq', '-c', self.cfg])
  268. server.communicate()
  269. except OSError:
  270. # print("Can not stop peer")
  271. logger.debug('Can not stop peer')
  272. return False
  273. self.started = False
  274. return True
  275. def get_statistics_value(self, subsystem, name):
  276. server = pexpect()
  277. server.spawn(None, [self.test.gnunetstatistics, '-c', self.cfg, '-q', '-n', name, '-s', subsystem], stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
  278. # server.expect ("stdout", re.compile (r""))
  279. test = server.read("stdout", 10240)
  280. tests = test.partition(b'\n')
  281. # On W32 GNUnet outputs with \r\n, rather than \n
  282. if os.name == 'nt' and tests[1] == b'\n' and tests[0][-1] == b'\r':
  283. tests = (tests[0][:-1], tests[1], tests[2])
  284. tests = tests[0]
  285. result = tests.decode("utf-8").strip()
  286. logger.debug('running gnunet-statistics %s for %s "/" %s yields %s', self.cfg, name, subsystem, result)
  287. if (result.isdigit() == True):
  288. return result
  289. else:
  290. logger.debug('Invalid statistics value: %s is not a number!', result)
  291. return -1