Skip to content

Commit

Permalink
Include worker test in on-device test app
Browse files Browse the repository at this point in the history
Exercise the `--worker` option in the on-device test app. This requires
raising the SDK version to 30.
  • Loading branch information
dbnicholson committed Jun 1, 2022
1 parent 1f02f85 commit 699eb3b
Show file tree
Hide file tree
Showing 4 changed files with 158 additions and 2 deletions.
3 changes: 2 additions & 1 deletion testapps/on_device_unit_tests/setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,14 +41,15 @@
'sqlite3,libffi,openssl,pyjnius,kivy,python3,requests,urllib3,'
'chardet,idna'
),
'android-api': 27,
'android-api': 30,
'ndk-api': 21,
'dist-name': 'bdist_unit_tests_app',
'arch': 'armeabi-v7a',
'bootstrap' : 'sdl2',
'permissions': ['INTERNET', 'VIBRATE'],
'orientation': 'sensor',
'service': 'P4a_test_service:app_service.py',
'worker': 'P4a_test_worker:app_worker.py',
}

# check if we overwrote the default test_app requirements via `cli`
Expand Down
81 changes: 81 additions & 0 deletions testapps/on_device_unit_tests/test_app/app_flask.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,10 +35,12 @@ class App(Flask):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.service_running = False
self.work_request = None

def get_status(self):
return jsonify({
'service_running': self.service_running,
'worker_running': self.worker_running,
})

@property
Expand All @@ -60,6 +62,64 @@ def service_stop(self):
self.service.stop(activity)
self.service_running = False

@property
@skip_if_not_running_from_android_device
def work_manager(self):
from jnius import autoclass

WorkManager = autoclass('androidx.work.WorkManager')
activity = get_android_python_activity()
return WorkManager.getInstance(activity)

@property
@skip_if_not_running_from_android_device
def P4a_test_workerWorker(self):
from jnius import autoclass

return autoclass('org.test.unit_tests_app.P4a_test_workerWorker')

@skip_if_not_running_from_android_device
def worker_start(self):
from jnius import autoclass

if self.worker_running:
return

OneTimeWorkRequestBuilder = autoclass('androidx.work.OneTimeWorkRequest$Builder')
data = self.P4a_test_workerWorker.buildInputData('10')
self.work_request = (
OneTimeWorkRequestBuilder(self.P4a_test_workerWorker._class)
.setInputData(data)
.build()
)
op = self.work_manager.enqueue(self.work_request)
op.getResult().get()

@skip_if_not_running_from_android_device
def worker_stop(self):
if self.worker_running:
op = self.work_manager.cancelWorkById(self.work_request.getId())
op.getResult().get()

@property
@skip_if_not_running_from_android_device
def work_info(self):
if self.work_request is None:
return None

return self.work_manager.getWorkInfoById(self.work_request.getId()).get()

@property
@skip_if_not_running_from_android_device
def worker_running(self):
info = self.work_info
if info is None:
print('Work request not started')
return False
state = info.getState()
print('Work request state:', state.toString())
return not state.isFinished()


app = App(__name__)
TESTS_TO_PERFORM = dict()
Expand Down Expand Up @@ -89,6 +149,7 @@ def index():
'index.html',
platform='Android' if RUNNING_ON_ANDROID else 'Desktop',
service_running=current_app.service_running,
worker_running=current_app.worker_running,
)


Expand Down Expand Up @@ -196,3 +257,23 @@ def service():
else:
current_app.service_stop()
return ('', 204)


@app.route('/worker')
def worker():
if not RUNNING_ON_ANDROID:
print(NON_ANDROID_DEVICE_MSG, '...cancelled worker.')
return (NON_ANDROID_DEVICE_MSG, 400)
args = request.args
if 'action' not in args:
print('ERROR: asked to manage worker but no action specified')
return ('No action specified', 400)

action = args['action']
if action == 'start':
current_app.worker_start()
elif action == 'stop':
current_app.worker_stop()
else:
return ('Invalid action "{}"'.format(action), 400)
return ('', 204)
26 changes: 26 additions & 0 deletions testapps/on_device_unit_tests/test_app/app_worker.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-

import datetime
import time

from os import environ

argument = environ.get('PYTHON_SERVICE_ARGUMENT', '')
print(
'app_worker.py was successfully called with argument: "{}"'.format(
argument,
),
)

try:
duration = int(argument)
except ValueError:
duration = 60

print('Running the test worker for {} seconds'.format(duration))
while duration > 0:
print(duration, 'seconds remaining')
duration -= 1
time.sleep(1)
print('Exiting the test worker')
50 changes: 49 additions & 1 deletion testapps/on_device_unit_tests/test_app/templates/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -134,18 +134,66 @@ <h3 class="text-underline">Android tests</h3>
</script>
</div>

<div>
<button onClick="start_worker()">
start worker
</button>

<button onClick="stop_worker()">
stop worker
</button>

<div id="worker-status">
{{ 'Worker started' if worker_running else 'Worker stopped' }}
</div>

<script>
function start_worker() {
var request = new XMLHttpRequest();
request.onload = function() {
var elem = document.getElementById('worker-status');
if (this.status >= 400)
elem.textContent = `Worker start failed: ${this.statusText}`;
else
elem.textContent = 'Worker started';
};
request.open('GET', 'worker?action=start', true);
request.send();
}

function stop_worker() {
var request = new XMLHttpRequest();
request.onload = function() {
var elem = document.getElementById('worker-status');
if (this.status >= 400)
elem.textContent = `Worker stop failed: ${this.statusText}`;
else
elem.textContent = 'Worker stopped';
};
request.open('GET', 'worker?action=stop', true);
request.send();
}
</script>
</div>

<script>
function update_status() {
var request = new XMLHttpRequest();
request.onload = function() {
var service_status = document.getElementById('service-status');
var worker_status = document.getElementById('worker-status');

if (this.status >= 400) {
service_status.textContent = `App status failed: ${this.statusText}`;
service_status.textContent = worker_status.textContent =
`App status failed: ${this.statusText}`;
} else {
var status = JSON.parse(this.responseText);
service_status.textContent = status.service_running
? 'Service started'
: 'Service stopped';
worker_status.textContent = status.worker_running
? 'Worker started'
: 'Worker stopped';
}
};
request.open('GET', 'status', true);
Expand Down

0 comments on commit 699eb3b

Please sign in to comment.