From 4d4e61b58003e02d207b6c54dcc70ef5af640009 Mon Sep 17 00:00:00 2001 From: Tim Ryan Date: Fri, 10 Jul 2015 17:33:59 -0700 Subject: [PATCH 1/3] Adds a framework for testing with SITL. --- tests/sitl/__init__.py | 0 tests/sitl/__main__.py | 86 +++++++++++++++++++++++++++++++++++++++ tests/sitl/test_12.py | 23 +++++++++++ tests/sitl/test_simple.py | 12 ++++++ tests/sitl/testlib.py | 70 +++++++++++++++++++++++++++++++ 5 files changed, 191 insertions(+) create mode 100644 tests/sitl/__init__.py create mode 100755 tests/sitl/__main__.py create mode 100644 tests/sitl/test_12.py create mode 100644 tests/sitl/test_simple.py create mode 100644 tests/sitl/testlib.py diff --git a/tests/sitl/__init__.py b/tests/sitl/__init__.py new file mode 100644 index 000000000..e69de29bb diff --git a/tests/sitl/__main__.py b/tests/sitl/__main__.py new file mode 100755 index 000000000..8b1cf39d4 --- /dev/null +++ b/tests/sitl/__main__.py @@ -0,0 +1,86 @@ +#!/usr/bin/env python -u + +from __future__ import print_function +import time +import os +from subprocess import Popen, PIPE +import atexit +import sys +import tempfile + +bg = [] +def cleanup_processes(): + for p in bg: + p.kill() +atexit.register(cleanup_processes) + +testpath = os.path.dirname(__file__) + +from functools import wraps +import errno +import os +import signal + +class TimeoutError(Exception): + pass + +def timeout(seconds=10, error_message='Timeout Occurred'): + def decorator(func): + def _handle_timeout(signum, frame): + raise TimeoutError(error_message) + + def wrapper(*args, **kwargs): + signal.signal(signal.SIGALRM, _handle_timeout) + signal.alarm(seconds) + try: + result = func(*args, **kwargs) + finally: + signal.alarm(0) + return result + + return wraps(func)(wrapper) + + return decorator + + + +def lets_run_a_test(name): + sitl = Popen(['dronekit-sitl', 'copter-3.3-rc5', '-I0', '-S', '--model', 'quad', '--home=-35.363261,149.165230,584,353'], stdout=PIPE, stderr=PIPE) + bg.append(sitl) + + time.sleep(5) + + newenv = os.environ.copy() + newenv['PYTHONUNBUFFERED'] = '1' + + newenv['TEST_WRITE_OUT'] = str(os.dup(1)) + newenv['TEST_WRITE_ERR'] = str(os.dup(2)) + newenv['TEST_NAME'] = name + + print('[runner] ' + name, file=sys.stderr) + p = Popen(['mavproxy.py', '--logfile=' + tempfile.mkstemp()[1], '--master=tcp:127.0.0.1:5760', '--cmd=module load droneapi.module.api; ; api start testlib.py'], cwd=testpath, env=newenv, stdout=PIPE, stderr=PIPE) + bg.append(p) + + @timeout(90, 'Test timed out after 90s') + def communicate(): + p.communicate() + + try: + communicate() + except TimeoutError as e: + p.kill() + print('Error:', e.message) + p.returncode = 143 + bg.remove(p) + + sitl.kill() + bg.remove(sitl) + + if p.returncode != 0: + sys.exit(p.returncode) + + time.sleep(5) + +for i in os.listdir(testpath): + if i.startswith('test_') and i.endswith('.py'): + lets_run_a_test(i[:-3]) diff --git a/tests/sitl/test_12.py b/tests/sitl/test_12.py new file mode 100644 index 000000000..10beb9528 --- /dev/null +++ b/tests/sitl/test_12.py @@ -0,0 +1,23 @@ +from droneapi.lib import VehicleMode +from pymavlink import mavutil +import time +import sys +import os + +def current_milli_time(): + return int(round(time.time() * 1000)) + +def test_timeout(local_connect): + v = local_connect().get_vehicles()[0] + + print "Read vehicle param 'THR_MIN': %s" % v.parameters['THR_MIN'] + + print "Write vehicle param 'THR_MIN' : 50" + start = current_milli_time() + v.parameters['THR_MIN']=50 + end = current_milli_time() + + print "Read new value of param 'THR_MIN': %s" % v.parameters['THR_MIN'] + + # TODO + # assert end - start < 1000, 'time to set parameter was %s, over 1s' % (end - start,) diff --git a/tests/sitl/test_simple.py b/tests/sitl/test_simple.py new file mode 100644 index 000000000..9c4646740 --- /dev/null +++ b/tests/sitl/test_simple.py @@ -0,0 +1,12 @@ +from droneapi.lib import VehicleMode +from pymavlink import mavutil +import time +import sys +import os +from testlib import assert_equals + +def test_parameters(local_connect): + v = local_connect().get_vehicles()[0] + + # Simple parameter checks + assert_equals(type(v.parameters['THR_MIN']), float) diff --git a/tests/sitl/testlib.py b/tests/sitl/testlib.py new file mode 100644 index 000000000..4a296cbd8 --- /dev/null +++ b/tests/sitl/testlib.py @@ -0,0 +1,70 @@ +""" +We can't use nose right now, so we recreate some of +nose's features in a compatible way, but run it in-process. +""" + +import inspect +import traceback +import os +import sys +import importlib + +def assert_equals(a, b, msg=None): + if not a == b: + raise AssertionError(msg or "%r != %r" % (a, b)) + +def run_tests(lib): + # Work around weird test reloading issues. + try: + sys.local_connect = local_connect + except: + pass + + try: + old_out = sys.stdout + old_err = sys.stderr + + api_out = os.fdopen(int(os.environ['TEST_WRITE_OUT']), 'a') + api_err = os.fdopen(int(os.environ['TEST_WRITE_ERR']), 'a') + + class Intercept: + def __init__(self, api, old): + self.api = api + self.old = old + + def write(self, data): + import threading + if threading.current_thread().name.startswith('APIThread'): + self.api.write(data) + else: + self.old.write(data) + + def flush(self): + self.api.flush() + self.old.flush() + + sys.stdout = Intercept(api_out, old_out) + sys.stderr = Intercept(api_err, old_err) + + sys.path.append(os.path.dirname('__file__')) + mod = importlib.import_module(lib) + + tests = [] + for (name, m) in inspect.getmembers(mod, inspect.isfunction): + if name.startswith('test_'): + tests.append(m) + + if len(tests) == 0: + return + + for test in tests: + test(sys.local_connect) + sys.stdout.write('.') + except: + print '\nERROR' + traceback.print_exc() + os._exit(1) + print '\nOK' + os._exit(0) + +run_tests(os.environ['TEST_NAME']) From 2e6bd86139388110070e4f99a33bece46c135828 Mon Sep 17 00:00:00 2001 From: Tim Ryan Date: Fri, 10 Jul 2015 17:37:17 -0700 Subject: [PATCH 2/3] Moves web tests to subfolder. --- tests/{ => web}/__init__.py | 0 tests/{ => web}/cloud_client_test.py | 0 tests/{ => web}/web_integration_test.py | 0 3 files changed, 0 insertions(+), 0 deletions(-) rename tests/{ => web}/__init__.py (100%) rename tests/{ => web}/cloud_client_test.py (100%) rename tests/{ => web}/web_integration_test.py (100%) diff --git a/tests/__init__.py b/tests/web/__init__.py similarity index 100% rename from tests/__init__.py rename to tests/web/__init__.py diff --git a/tests/cloud_client_test.py b/tests/web/cloud_client_test.py similarity index 100% rename from tests/cloud_client_test.py rename to tests/web/cloud_client_test.py diff --git a/tests/web_integration_test.py b/tests/web/web_integration_test.py similarity index 100% rename from tests/web_integration_test.py rename to tests/web/web_integration_test.py From 236f14da8569d190440f30d6376efde19534db96 Mon Sep 17 00:00:00 2001 From: Tim Ryan Date: Fri, 10 Jul 2015 17:37:57 -0700 Subject: [PATCH 3/3] Updates CI tests to run SITL tests. --- .travis.yml | 12 ++-- appveyor.yml | 6 +- circle.yml | 10 +++- incisor.yml | 24 ++++---- requirements.txt | 1 + tests/sitl/__main__.py | 132 ++++++++++++++++++++++++++++------------- tests/sitl/testlib.py | 74 +++++++++++++++-------- 7 files changed, 170 insertions(+), 89 deletions(-) diff --git a/.travis.yml b/.travis.yml index 377c1885b..c2ea74852 100644 --- a/.travis.yml +++ b/.travis.yml @@ -4,13 +4,12 @@ env: install: - 'a() { set -e; }' - "z() { E=$?; test $E -eq 0 && return 0; printf \"\\n\\033[1;31mThe command failed with exit code $?.\\033[0m\"; set -e; return $E; }" - - (a; sudo pip2 install nose );z + - (a; sudo pip2 install nose psutil );z + - '(a; sudo pip2 install git+https://github.com/3drobotics/dronekit-sitl-runner.git );z' script: - (a; sudo python setup.py install );z - - |- - (a; cd tests - nosetests - );z + - (a; nosetests tests/web );z + - (a; cd tests; python -m sitl );z git: depth: 10 language: objective-c @@ -18,6 +17,3 @@ notifications: email: false matrix: fast_finish: true -branches: - only: - - master diff --git a/appveyor.yml b/appveyor.yml index 31b8688ba..97a766121 100644 --- a/appveyor.yml +++ b/appveyor.yml @@ -3,10 +3,12 @@ environment: init: [] install: - cmd: 'setlocal & python -m pip install pip -U & endlocal' - - cmd: "setlocal & SET PATH=%PYTHON%;c:\\Python27\\Scripts;%PATH% & pip2 install nose numpy & endlocal" + - cmd: "setlocal & SET PATH=%PYTHON%;c:\\Python27\\Scripts;%PATH% & pip2 install nose numpy psutil & endlocal" + - cmd: "setlocal & SET PATH=%PYTHON%;c:\\Python27\\Scripts;%PATH% & pip2 install git+https://github.com/3drobotics/dronekit-sitl-runner.git & endlocal" build_script: - cmd: 'setlocal & python setup.py install & endlocal' - - cmd: "setlocal & SET PATH=%PYTHON%;c:\\Python27\\Scripts;%PATH% & cd tests & nosetests & endlocal" + - cmd: "setlocal & SET PATH=%PYTHON%;c:\\Python27\\Scripts;%PATH% & nosetests tests\\web & endlocal" + - cmd: "setlocal & SET PATH=%PYTHON%;c:\\Python27\\Scripts;%PATH% & cd tests & python -m sitl & endlocal" clone_depth: 10 cache: - '%CYG_CACHE%' diff --git a/circle.yml b/circle.yml index c6b79f683..62c5cc561 100644 --- a/circle.yml +++ b/circle.yml @@ -2,12 +2,16 @@ machine: environment: {} dependencies: override: - - sudo python setup.py install: + - python setup.py install: environment: {} - - "cd tests\nnosetests\n": + - nosetests tests/web: + environment: {} + - cd tests; python -m sitl: environment: {} pre: - - sudo pip2 install nose: + - pip2 install nose psutil: + environment: {} + - 'pip2 install git+https://github.com/3drobotics/dronekit-sitl-runner.git': environment: {} test: override: diff --git a/incisor.yml b/incisor.yml index 4240308ff..d89fd715d 100644 --- a/incisor.yml +++ b/incisor.yml @@ -3,27 +3,29 @@ builds: stages: setup: - python -m pip install pip -U - - SET PATH=%PYTHON%;c:\Python27\Scripts;%PATH% & pip2 install nose numpy + - SET PATH=%PYTHON%;c:\Python27\Scripts;%PATH% & pip2 install nose numpy psutil + - SET PATH=%PYTHON%;c:\Python27\Scripts;%PATH% & pip2 install git+https://github.com/3drobotics/dronekit-sitl-runner.git build: - python setup.py install - - SET PATH=%PYTHON%;c:\Python27\Scripts;%PATH% & cd tests & nosetests + - SET PATH=%PYTHON%;c:\Python27\Scripts;%PATH% & nosetests tests\web + - SET PATH=%PYTHON%;c:\Python27\Scripts;%PATH% & cd tests & python -m sitl - os: linux stages: setup: - - sudo pip2 install nose + - pip2 install nose psutil + - pip2 install git+https://github.com/3drobotics/dronekit-sitl-runner.git build: - - sudo python setup.py install - - | - cd tests - nosetests + - python setup.py install + - nosetests tests/web + - cd tests; python -m sitl - os: osx stages: setup: - - sudo pip2 install nose + - sudo pip2 install nose psutil + - sudo pip2 install git+https://github.com/3drobotics/dronekit-sitl-runner.git build: - sudo python setup.py install - - | - cd tests - nosetests + - nosetests tests/web + - cd tests; python -m sitl diff --git a/requirements.txt b/requirements.txt index 3bf4fb6a8..04808fc4e 100644 --- a/requirements.txt +++ b/requirements.txt @@ -6,3 +6,4 @@ pymavlink>=1.1.50 sphinx-3dr-theme>=0.0.6 MAVProxy>=1.4.13 nose>=1.3.7 +psutil>=3.0.0 diff --git a/tests/sitl/__main__.py b/tests/sitl/__main__.py index 8b1cf39d4..470c8cfbf 100755 --- a/tests/sitl/__main__.py +++ b/tests/sitl/__main__.py @@ -7,80 +7,132 @@ import atexit import sys import tempfile - -bg = [] -def cleanup_processes(): - for p in bg: - p.kill() -atexit.register(cleanup_processes) - -testpath = os.path.dirname(__file__) - from functools import wraps import errno import os import signal +import time +import psutil -class TimeoutError(Exception): - pass - -def timeout(seconds=10, error_message='Timeout Occurred'): - def decorator(func): - def _handle_timeout(signum, frame): - raise TimeoutError(error_message) - - def wrapper(*args, **kwargs): - signal.signal(signal.SIGALRM, _handle_timeout) - signal.alarm(seconds) - try: - result = func(*args, **kwargs) - finally: - signal.alarm(0) +def wait_timeout(proc, seconds): + """Wait for a process to finish, or raise exception after timeout""" + start = time.time() + end = start + seconds + interval = min(seconds / 1000.0, .25) + + while True: + result = proc.poll() + if result is not None: return result + if time.time() >= end: + raise RuntimeError("Process timed out") + time.sleep(interval) + +def kill(proc_pid): + process = psutil.Process(proc_pid) + for proc in process.children(recursive=True): + try: + proc.kill() + except psutil.NoSuchProcess: + pass + try: + process.kill() + except psutil.NoSuchProcess: + pass - return wraps(func)(wrapper) +if sys.platform == "win32": + import msvcrt + import _subprocess +else: + import fcntl - return decorator +bg = [] +def cleanup_processes(): + for p in bg: + kill(p.pid) +atexit.register(cleanup_processes) + +testpath = os.path.dirname(__file__) +def wrap_fd(pipeout): + # Prepare to pass to child process + if sys.platform == "win32": + curproc = _subprocess.GetCurrentProcess() + pipeouth = msvcrt.get_osfhandle(pipeout) + pipeoutih = _subprocess.DuplicateHandle(curproc, pipeouth, curproc, 0, 1, _subprocess.DUPLICATE_SAME_ACCESS) + return (str(int(pipeoutih)), pipeoutih) + else: + return (str(pipeout), None) def lets_run_a_test(name): sitl = Popen(['dronekit-sitl', 'copter-3.3-rc5', '-I0', '-S', '--model', 'quad', '--home=-35.363261,149.165230,584,353'], stdout=PIPE, stderr=PIPE) bg.append(sitl) - time.sleep(5) + while sitl.poll() == None: + line = sitl.stdout.readline() + if 'Waiting for connection' in line: + break + if sitl.poll() != None and sitl.returncode != 0: + print('[runner] ...aborting with SITL error code ' + str(sitl.returncode)) + sys.stdout.flush() + sys.stderr.flush() + sys.exit(sitl.returncode) newenv = os.environ.copy() newenv['PYTHONUNBUFFERED'] = '1' - newenv['TEST_WRITE_OUT'] = str(os.dup(1)) - newenv['TEST_WRITE_ERR'] = str(os.dup(2)) + if sys.platform == 'win32': + out_fd = 1 + err_fd = 2 + else: + out_fd = os.dup(1) + err_fd = os.dup(2) + + (out_fd, out_h) = wrap_fd(out_fd) + (err_fd, err_h) = wrap_fd(err_fd) + + newenv['TEST_WRITE_OUT'] = out_fd + newenv['TEST_WRITE_ERR'] = err_fd newenv['TEST_NAME'] = name print('[runner] ' + name, file=sys.stderr) - p = Popen(['mavproxy.py', '--logfile=' + tempfile.mkstemp()[1], '--master=tcp:127.0.0.1:5760', '--cmd=module load droneapi.module.api; ; api start testlib.py'], cwd=testpath, env=newenv, stdout=PIPE, stderr=PIPE) - bg.append(p) - - @timeout(90, 'Test timed out after 90s') - def communicate(): - p.communicate() + sys.stdout.flush() + sys.stderr.flush() + timeout = 300 try: - communicate() - except TimeoutError as e: - p.kill() - print('Error:', e.message) + p = Popen([sys.executable, '-m', 'MAVProxy.mavproxy', '--logfile=' + tempfile.mkstemp()[1], '--master=tcp:127.0.0.1:5760', '--cmd=module load droneapi.module.api; ; api start testlib.py'], cwd=testpath, env=newenv, stdout=PIPE, stderr=PIPE) + bg.append(p) + wait_timeout(p, timeout) + except TimeoutExpired: + kill(p.pid) p.returncode = 143 + print('Error: Timeout after ' + str(timeout) + ' seconds.') bg.remove(p) - sitl.kill() + if sys.platform == 'win32': + out_h.Close() + err_h.Close() + + kill(sitl.pid) bg.remove(sitl) if p.returncode != 0: + print('[runner] ...aborting with dronekit error code ' + str(p.returncode)) + sys.stdout.flush() + sys.stderr.flush() sys.exit(p.returncode) + print('[runner] ...success.') time.sleep(5) for i in os.listdir(testpath): if i.startswith('test_') and i.endswith('.py'): lets_run_a_test(i[:-3]) + +print('[runner] finished.') +sys.stdout.flush() +sys.stdout.close() +sys.stderr.flush() +sys.stderr.close() diff --git a/tests/sitl/testlib.py b/tests/sitl/testlib.py index 4a296cbd8..82347d34f 100644 --- a/tests/sitl/testlib.py +++ b/tests/sitl/testlib.py @@ -13,6 +13,44 @@ def assert_equals(a, b, msg=None): if not a == b: raise AssertionError(msg or "%r != %r" % (a, b)) +def override_io(): + old_out = sys.stdout + old_err = sys.stderr + + fd_out = int(os.environ['TEST_WRITE_OUT']) + fd_err = int(os.environ['TEST_WRITE_ERR']) + if sys.platform == 'win32': + import msvcrt + fd_out = msvcrt.open_osfhandle(fd_out, 0) + fd_err = msvcrt.open_osfhandle(fd_err, 0) + api_out = os.fdopen(fd_out, 'w') + api_err = os.fdopen(fd_err, 'w') + + class Intercept: + def __init__(self, api, old): + self.api = api + self.old = old + + def write(self, data): + import threading + if threading.current_thread().name.startswith('APIThread'): + self.api.write(data) + else: + self.old.write(data) + + def flush(self): + self.api.flush() + self.old.flush() + + sys.stdout = Intercept(api_out, old_out) + sys.stderr = Intercept(api_err, old_err) + +def unoverride_io(): + sys.stdout.api.close() + sys.stdout = sys.stdout.old + sys.stderr.api.close() + sys.stderr = sys.stderr.old + def run_tests(lib): # Work around weird test reloading issues. try: @@ -21,31 +59,6 @@ def run_tests(lib): pass try: - old_out = sys.stdout - old_err = sys.stderr - - api_out = os.fdopen(int(os.environ['TEST_WRITE_OUT']), 'a') - api_err = os.fdopen(int(os.environ['TEST_WRITE_ERR']), 'a') - - class Intercept: - def __init__(self, api, old): - self.api = api - self.old = old - - def write(self, data): - import threading - if threading.current_thread().name.startswith('APIThread'): - self.api.write(data) - else: - self.old.write(data) - - def flush(self): - self.api.flush() - self.old.flush() - - sys.stdout = Intercept(api_out, old_out) - sys.stderr = Intercept(api_err, old_err) - sys.path.append(os.path.dirname('__file__')) mod = importlib.import_module(lib) @@ -57,14 +70,25 @@ def flush(self): if len(tests) == 0: return + override_io() + for test in tests: test(sys.local_connect) sys.stdout.write('.') except: print '\nERROR' traceback.print_exc() + + sys.stdout.flush() + sys.stderr.flush() + unoverride_io() os._exit(1) + print '\nOK' + + sys.stdout.flush() + sys.stderr.flush() + unoverride_io() os._exit(0) run_tests(os.environ['TEST_NAME'])