test_log.py 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350
  1. #!/usr/bin/python
  2. # -*- coding: utf-8 -*-
  3. import os, random, sys, time, json, getopt, threading
  4. sys.path.append('../../stm32_prs/stm32_prs/branches/epu_tester')
  5. import extdevices
  6. import checklogfile
  7. reload(sys)
  8. sys.setdefaultencoding('utf8')
  9. login = "admin"
  10. password = "12345"
  11. def print_test_list():
  12. print "\t\t1 - ON/OFF test\r\n\
  13. \t2 - RAM buffer test\r\n\
  14. \t3 - Log file download test"
  15. def usage():
  16. print "Usage: test_log.py -t <test number> <ip>\r\n\
  17. --help, -h \t\tprint usage info\r\n\
  18. --test, -t \t\ttest number to run"
  19. print_test_list()
  20. def ping(hostname):
  21. response = os.system("ping -q -c1 -W1 " + hostname + ">> /dev/null")
  22. if response == 0:
  23. return True
  24. else:
  25. return False
  26. def do_login():
  27. os.system("curl -s -b /tmp/cookies.txt -c /tmp/cookies.txt -d \"login=%s&password=%s\" http://%s/login.cgi > /dev/null" % (login, password, ip))
  28. def do_logout():
  29. os.system("curl -s -b /tmp/cookies.txt -c /tmp/cookies.txt http://%s/logout.cgi > /dev/null" %ip)
  30. def do_reset_sett():
  31. os.system("curl -s -b /tmp/cookies.txt -c /tmp/cookies.txt \"http://%s/reset.cgi\" > /dev/null" %ip)
  32. def log_get_page(page):
  33. return os.popen("curl -s -b /tmp/cookies.txt -c /tmp/cookies.txt \"http://%s/history.cgi?page=%s&_=%s\" --compressed | jq -r -j '.page'" % (ip, page, random.randint(0, 0xFFFF))).read()
  34. def log_get_string(page, string):
  35. return os.popen("curl -s -b /tmp/cookies.txt -c /tmp/cookies.txt \"http://%s/history.cgi?page=%s&_=%s\" --compressed | jq -r -j '.page[%s]'" % (ip, page, random.randint(0, 0xFFFF), string)).read().decode('utf-8')
  36. def log_get_ramstrnum():
  37. page = log_get_pagesnum()
  38. return os.popen("curl -s -b /tmp/cookies.txt -c /tmp/cookies.txt \"http://%s/history.cgi?page=%s&_=%s\" --compressed | jq -r -j '.page | length'" % (ip, page, random.randint(0, 0xFFFF))).read()
  39. def log_get_pagesnum():
  40. return os.popen("curl -s -b /tmp/cookies.txt -c /tmp/cookies.txt \"http://%s/history.cgi?page=1&_=%s\" --compressed | jq -r -j '.pages'" % (ip, random.randint(0, 0xFFFF))).read()
  41. def log_download(path):
  42. print "Downloading log file..."
  43. if 0 == os.system("curl -b /tmp/cookies.txt -c /tmp/cookies.txt \"http://%s/history.cgi?page=all&_=%s\" --output %s --progress" % (ip, random.randint(0, 0xFFFF), path)):
  44. return True
  45. else:
  46. return False
  47. def log_add_message():
  48. do_logout()
  49. do_login()
  50. time.sleep(1)
  51. def reboot(method):
  52. if method == "snmp":
  53. os.system("snmpset -v1 -t0.1 -r0 -c public %s .1.3.6.1.4.1.41752.5.17.2.9.1.0 i 1 > /dev/null" %ip)
  54. if method == "web":
  55. os.system("curl -s -b /tmp/cookies.txt -c /tmp/cookies.txt http://%s/reboot.cgi" %ip)
  56. else:
  57. print "Unknown method"
  58. def stop_spam_task():
  59. res = os.popen("curl -s -b /tmp/cookies.txt -c /tmp/cookies.txt \"http://%s/led.cgi?state=%s&_=%s\" --compressed" % (ip, "off", random.randint(0, 0xFFFF))).read()
  60. if res == "OFF":
  61. print "Spam stoped"
  62. return True
  63. else:
  64. print "Error"
  65. return False
  66. def rambuf_test():
  67. passed = False;
  68. results = [0]*10
  69. if not ping(ip):
  70. print "Host not found"
  71. return False
  72. do_login()
  73. while len(filter(lambda x: x > 0, results)) < 10:
  74. while True:
  75. last_msg = log_get_string(1, 0)
  76. ram_num = int(log_get_ramstrnum())
  77. if ram_num == 10:
  78. ram_num = 0;
  79. if results[ram_num] > 0:
  80. log_add_message()
  81. else:
  82. break
  83. print "\r\nLast message: ", last_msg
  84. print "Messages in RAM: %s" %ram_num
  85. reboot("web")
  86. time.sleep(10)
  87. do_login()
  88. for i in range(1, 10):
  89. page = log_get_page(i)
  90. print "\r\nPage " + str(i) + "\r\n" + page
  91. parsed_page = json.loads(page)
  92. if last_msg in parsed_page:
  93. str_num = parsed_page.index(last_msg) + 1
  94. print "\r\nLast message found as %s-th message (page %s, string %s)" %(str_num + (i - 1) * 10 , i, str_num)
  95. results[ram_num] += 1
  96. break
  97. if "Перезагрузка" in parsed_page:
  98. print "Error: Last message not found"
  99. return False
  100. print "\r\nResults:", results
  101. return True
  102. def on_off_test():
  103. num = 0 #External device addr
  104. device = extdevices.io_device(num)
  105. msg = ''
  106. timestamp = ''
  107. res = False
  108. device.set_outputs(0x02)
  109. time.sleep(8)
  110. if not ping(ip):
  111. print "Host not found"
  112. return False
  113. while True:
  114. try:
  115. device.set_outputs(0x00)
  116. print "OFF"
  117. time.sleep(0.2)
  118. device.set_outputs(0x02)
  119. print "ON"
  120. time.sleep(4)
  121. time.sleep(random.randint(1, 4))
  122. except KeyboardInterrupt:
  123. sys.exit(0)
  124. except ValueError:
  125. print "JSON parse error."
  126. stop_spam_task()
  127. return False
  128. except:
  129. print "Retry"
  130. stop_spam_task()
  131. return res
  132. def download_test_ram(start_num, add_num):
  133. print "RAM:", start_num, "+", add_num
  134. PATH = "/tmp/testlog_ram"+str(start_num)+"_"+str(add_num)+".csv"
  135. do_login()
  136. while True:
  137. last_msg = log_get_string(1, 0)
  138. ram_num = int(log_get_ramstrnum())
  139. if ram_num == 10:
  140. ram_num = 0;
  141. if ram_num == start_num:
  142. break
  143. else:
  144. log_add_message()
  145. thr = threading.Thread(target=log_download, args=(PATH,), kwargs={})
  146. thr.start()
  147. time.sleep(1)
  148. for i in range(add_num):
  149. log_add_message()
  150. thr.join()
  151. print "Last message:", last_msg
  152. fsize = os.path.getsize(PATH)
  153. print "File size: ", fsize
  154. if fsize != 120*30000 + 3 + 120*start_num:
  155. print "Error. File size missmatch"
  156. return False
  157. res = checklogfile.check(PATH)
  158. if not res:
  159. return False
  160. lines = checklogfile.parse(PATH)
  161. res = False
  162. for i in range(len(lines)):
  163. s = lines[i]
  164. if last_msg in s:
  165. res = True
  166. break
  167. if not res:
  168. print "Error. Last message not found"
  169. return False
  170. else:
  171. print "Last message found"
  172. do_logout()
  173. return True
  174. def download_test():
  175. passed = False;
  176. results = [0]*10
  177. if not ping(ip):
  178. print "Host not found"
  179. return False
  180. do_login()
  181. #Проверка добавления записи в лог во время загрузки файла (строка попала в RAM и вызвала запись страницы)
  182. if not download_test_ram(8, 5):
  183. return False
  184. #Проверка добавления записи в лог во время загрузки файла (строка попала в RAM, без записи страницы)
  185. if not download_test_ram(1, 2):
  186. return False
  187. #Проверка загрузки лога при количестве строк в RAM 0-9
  188. do_login()
  189. while len(filter(lambda x: x > 0, results)) < 10:
  190. while True:
  191. last_msg = log_get_string(1, 0)
  192. ram_num = int(log_get_ramstrnum())
  193. if ram_num == 10:
  194. ram_num = 0;
  195. if results[ram_num] > 0:
  196. log_add_message()
  197. else:
  198. break
  199. print "\r\nLast message: ", last_msg
  200. print "Messages in RAM: %s" %ram_num
  201. PATH = "/tmp/testlog_" + str(ram_num) + ".csv"
  202. thr = threading.Thread(target=log_download, args=(PATH,), kwargs={})
  203. thr.start()
  204. thr.join()
  205. #log_download(PATH)
  206. fsize = os.path.getsize(PATH)
  207. print "File size: ", fsize
  208. res = checklogfile.check(PATH)
  209. if res:
  210. results[ram_num] += 1
  211. else:
  212. return False
  213. lines = checklogfile.parse(PATH)
  214. res = False
  215. for i in range(len(lines)):
  216. s = lines[i]
  217. if last_msg in s:
  218. res = True
  219. break
  220. if not res:
  221. print "Error. Last message not found"
  222. return False
  223. else:
  224. print "Last message found"
  225. print "\r\nResults:", results
  226. return True
  227. test_list = [0, on_off_test, rambuf_test, download_test]
  228. def main():
  229. testnum = 0
  230. global ip
  231. try:
  232. opts, args = getopt.getopt(sys.argv[1:], "ht:", \
  233. ["help", "test="])
  234. except getopt.GetoptError:
  235. usage()
  236. sys.exit(2)
  237. for opt, arg in opts:
  238. if opt in ("-h", "--help"):
  239. usage()
  240. sys.exit()
  241. if opt in ("-t", "--test"):
  242. testnum = int(arg)
  243. if testnum == 0 or len(sys.argv) < 3:
  244. usage()
  245. sys.exit(2)
  246. ip = sys.argv[-1]
  247. #Run test by number
  248. if not test_list[testnum]():
  249. print "\r\nFailed\r\n"
  250. else:
  251. print "\r\nPassed\r\n"
  252. if __name__ == "__main__":
  253. main()