utils.py 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. import unittest
  2. import sys
  3. import os
  4. import sys
  5. import time
  6. import json
  7. import urllib
  8. import urllib2
  9. import subprocess
  10. import signal
  11. import random
  12. sys.path.append("interface/HUTN")
  13. sys.path.append("scripts")
  14. from hutn_compiler.compiler import main as do_compile
  15. taskname = "test_task"
  16. INIT_TIMEOUT = 30
  17. try:
  18. import pytest
  19. slow = pytest.mark.skipif(
  20. not pytest.config.getoption("--runslow"),
  21. reason="need --runslow option to run"
  22. )
  23. except:
  24. slow = lambda i:i
  25. ports = set()
  26. def getFreePort():
  27. """Gets a unique new port."""
  28. while 1:
  29. port = random.randint(10000, 20000)
  30. # Check if this port is in the set of ports.
  31. if port not in ports:
  32. # We have found a unique port. Add it to the set and return.
  33. ports.add(port)
  34. return port
  35. def execute(scriptname, parameters=[], wait=False):
  36. if os.name not in ["nt", "posix"]:
  37. # Stop now, as we would have no clue on how to kill its subtree
  38. raise Exception("Unknown OS version: " + str(os.name))
  39. command = [sys.executable, "-u", "scripts/%s.py" % scriptname] + parameters
  40. if wait:
  41. return subprocess.call(command, shell=False)
  42. else:
  43. return subprocess.Popen(command, shell=False)
  44. def child_kill(pid):
  45. subprocess.call(["pkill", "-P", "%i" % pid])
  46. start = time.time()
  47. with open(os.devnull, 'w') as null:
  48. while subprocess.call(["pgrep", "-P", "%i" % pid], stdout=null) != 1:
  49. time.sleep(0.1)
  50. if time.time() > start + 4:
  51. subprocess.call(["pkill", "-9", "-P", "%i" % pid])
  52. def kill(process):
  53. if os.name == "nt":
  54. #TODO this is Windows and I don't care too much about that...
  55. subprocess.call(["taskkill", "/F", "/T", "/PID", "%i" % process.pid])
  56. elif os.name == "posix":
  57. child_kill(process.pid)
  58. process.send_signal(signal.SIGINT)
  59. process.wait()
  60. child_kill(os.getpid())
  61. def flush_data(address, data):
  62. if data:
  63. urllib2.urlopen(urllib2.Request(address, urllib.urlencode({"op": "set_input", "data": json.dumps(data), "taskname": taskname})), timeout=INIT_TIMEOUT).read()
  64. return []
  65. def start_mvc():
  66. port = getFreePort()
  67. address = "127.0.0.1:%s" % port
  68. print("Execute run local MV")
  69. proc = execute("run_local_modelverse", [str(port)], wait=False)
  70. return proc, address