test1.py 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296
  1. import json
  2. import os
  3. import pexpect
  4. import sys
  5. import threading
  6. import time
  7. import urllib
  8. import urllib2
  9. sys.path.append("interface/HUTN")
  10. from hutn_compiler.compiler import main
  11. # CONSTANTS
  12. user = 'test'
  13. timeout = 10
  14. grammar_file = 'interface/HUTN/grammars/actionlanguage.g'
  15. # Consumes output of some subprocess in a background thread
  16. class OutletThread(threading.Thread):
  17. # obj: pexpect.spawn object
  18. # delay: time (in seconds) to wait between two reads
  19. def __init__(self, obj, delay = 1):
  20. threading.Thread.__init__(self)
  21. self.obj = obj
  22. self.on = True
  23. self.delay = delay
  24. # main
  25. def run(self):
  26. while self.on:
  27. try:
  28. x = self.obj.read_nonblocking(size=2048, timeout=0)
  29. sys.stdout.write(x)
  30. sys.stdout.flush()
  31. except pexpect.TIMEOUT:
  32. pass
  33. time.sleep(self.delay)
  34. # utils
  35. def join(self, timeout=None):
  36. self.on = False
  37. threading.Thread.join(self, timeout)
  38. def pause(self):
  39. self.on = False
  40. def resume(self):
  41. self.on = True
  42. # do obj.expect(s) and print the output of the spawned process
  43. def pp(obj, s):
  44. obj.expect(s)
  45. print obj.before + obj.after
  46. def execute(scriptname, parameters=[]):
  47. if os.name == "nt":
  48. command = "%s.bat" % scriptname
  49. elif os.name == "posix":
  50. command = "./%s.sh" % scriptname
  51. else:
  52. raise Exception("Unknown OS: " + str(os.name))
  53. ok = False
  54. proc = None
  55. while not ok:
  56. try:
  57. proc = pexpect.spawn(command, parameters)
  58. ok = True
  59. except:
  60. pass
  61. return proc
  62. def set_input(value, user=user, timeout=timeout):
  63. if isinstance(value, tuple):
  64. for v in value:
  65. set_input(v)
  66. else:
  67. args = {"op": "set_input",
  68. "element_type": "V",
  69. "value": json.dumps(value),
  70. "username": user}
  71. urllib2.urlopen(
  72. urllib2.Request("http://localhost:8001/", urllib.urlencode(args)),
  73. timeout=timeout).read()
  74. def flush_data(data, user=user, timeout=timeout):
  75. args = {"op": "set_input",
  76. "data": json.dumps(data),
  77. "username": user}
  78. urllib2.urlopen(
  79. urllib2.Request("http://localhost:8001/", urllib.urlencode(args)),
  80. timeout=timeout).read()
  81. return []
  82. def get_output(user=user, timeout=timeout):
  83. return urllib2.urlopen(
  84. urllib2.Request("http://localhost:8001/",
  85. urllib.urlencode({"op": "get_output",
  86. "username": user})),
  87. timeout=timeout).read()
  88. def create_user(user):
  89. ok = False
  90. while not ok:
  91. try:
  92. set_input(user, "user_manager")
  93. ok = True
  94. except:
  95. pass
  96. def run_file(input_file, test_input, test_output, mode="PS"):
  97. # Resolve file
  98. input_file = "integration/code/%s" % input_file
  99. # Run Modelverse server
  100. mv = execute("run_local_modelverse", ["bootstrap/bootstrap.m"])
  101. # consume output of MvK and print it in the main thread
  102. mvo = OutletThread(mv)
  103. mvo.start()
  104. # determine the interface
  105. if mode == "CS":
  106. interface = 1
  107. elif mode == "PS":
  108. interface = 0
  109. else:
  110. raise RuntimeError("Mode be either PS or CS")
  111. # compile to code
  112. code = main(input_file, grammar_file, mode)
  113. create_user(user)
  114. # set interface
  115. set_input(interface)
  116. try:
  117. # send code
  118. if mode == "CS":
  119. var_list = {}
  120. data = []
  121. for p in code:
  122. if isinstance(p, int):
  123. if p not in var_list:
  124. data = flush_data(data)
  125. data = []
  126. val = get_output()
  127. val = val.split("=", 2)[1].split("&", 1)[0]
  128. var_list[p] = val
  129. continue
  130. else:
  131. val = var_list[p]
  132. t = "R"
  133. else:
  134. val = p
  135. t = "V"
  136. data.append([t, val])
  137. data = flush_data(data)
  138. elif mode == "PS":
  139. set_input(code)
  140. # set input and get output
  141. for i in range(len(test_input)):
  142. set_input(test_input[i])
  143. val = get_output()
  144. val = val.split("=", 2)[2]
  145. print("For input %s, got output %s, expected %s" % (test_input[i], val, test_output[i]))
  146. assert str(val) == test_output[i]
  147. if str(val) != test_output[i]:
  148. return False
  149. finally:
  150. mvo.join()
  151. mv.sendintr()
  152. # All passed!
  153. return True
  154. def run_barebone(constructors_and_test_input, test_output, interface):
  155. # Run Modelverse server
  156. mv = execute("run_local_modelverse", ["bootstrap/bootstrap.m"])
  157. # consume output of MvK and print it in the main thread
  158. mvo = OutletThread(mv)
  159. mvo.start()
  160. create_user(user)
  161. # set interface
  162. set_input(interface)
  163. # send constructors and inpout
  164. var_list = {}
  165. data = []
  166. for p in constructors_and_test_input:
  167. if isinstance(p, int):
  168. if p not in var_list:
  169. data = flush_data(data)
  170. val = get_output()
  171. val = val.split("=", 2)[1].split("&", 1)[0]
  172. var_list[p] = val
  173. continue
  174. else:
  175. val = var_list[p]
  176. t = "R"
  177. else:
  178. val = p
  179. t = "V"
  180. data.append([t, val])
  181. data = flush_data(data)
  182. for e in test_output:
  183. val = get_output()
  184. val = val.split("=", 2)[2]
  185. print("Got %s, expected %s" % (val, e))
  186. assert str(val) == e
  187. if str(val) != e:
  188. mvo.join()
  189. mv.sendintr()
  190. return False
  191. # for e in test_output:
  192. # c = len(e) if isinstance(e, set) else 1
  193. # for _ in range(c):
  194. # val = get_output(user)
  195. # val = val.split("=", 2)[2]
  196. #
  197. # print("Got %s, expected %s" % (val, e))
  198. # if isinstance(e, set):
  199. # assert str(val) in e
  200. # if str(val) not in e:
  201. # mvo.join()
  202. # mv.sendintr()
  203. # return False
  204. # else:
  205. # assert str(val) == e
  206. # if str(val) != e:
  207. # mvo.join()
  208. # mv.sendintr()
  209. # return False
  210. # All passed!
  211. mvo.join()
  212. mv.sendintr()
  213. return True
  214. # assert(run_file("binary_to_decimal.al",
  215. # ["1", "10", "11", "100", "001", "1100111101"],
  216. # ["1", "2", "3", "4", "1", "829"],
  217. # "PS"))
  218. assert(run_file("binary_to_decimal.al",
  219. ["1", "10", "11", "100", "001", "1100111101"],
  220. ["1", "2", "3", "4", "1", "829"],
  221. "CS"))
  222. # assert(run_file("fibonacci.al", [1, 2, 3, 4], ["1", "1", "2", "3"]))
  223. # assert(run_file("fibonacci.al", [1, 2, 3, 4], ["1", "1", "2", "3"], mode="CS"))
  224. # assert(run_file("power.al", [(1, 0), (2, 1), (5, 0), (2, 2), (3, 2), (10, 2), (10, 10)], ["1", "2", "1", "4", "9", "100", "10000000000"]))
  225. # assert(run_file("binary_to_decimal.al", ["1", "10", "11", "100", "001", "1100111101"], ["1", "2", "3", "4", "1", "829"]))
  226. # assert(run_file("leap_year.al", [ 2016, 2015, 2014, 2013, 2012, 2001, 2000, 1999],
  227. # ["True", "False", "False", "False", "True", "False", "False", "False"]))
  228. #
  229. #
  230. # def flatten(lst):
  231. # new_lst = []
  232. # for f in lst:
  233. # if isinstance(f, (list, tuple)):
  234. # new_lst.extend(flatten(f))
  235. # else:
  236. # new_lst.append(f)
  237. # return new_lst
  238. #
  239. #
  240. # commands = [('"output"', # Output
  241. # ('"const"', 'true'),
  242. # 'true', # (has next)
  243. # ('"return"', # Return
  244. # 'true', # (has value)
  245. # ('"const"', 'true'),
  246. # ),
  247. # )
  248. # ]
  249. #
  250. #
  251. # assert(run_barebone(flatten(commands), ["True"], 1))