utils.py 2.6 KB

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