"""
A rough integration test for UWS 1.1 slow poll.
Because this is a slow test requiring a DaCHS with tests enabled, this
isn't run as a part of anything run casually.
"""

import os
import time

import requests

from gavo import votable
from gavo.votable import tapquery

ENDPOINT_URL = os.environ.get("ENDPOINT_URL",
	"http://localhost:8080/tap")

def time_differ():
	last_time = time.time()
	while True:
		next_time = time.time()
		yield next_time-last_time
		last_time = next_time
		

def run_basic_tests(job):
	job.executionDuration = 10
	jobURL = job.makeJobURL("")
	times = time_differ()
	times.next()

	# no waiting in PENDING
	res = requests.get(jobURL, params={"WAIT": "-1"}).text
	assert '<uws:phase>PENDING</uws:phase>' in res
	assert times.next()<0.1

	# now run the job and see if we time out after roughly 5 seconds.
	job.start()
	res = requests.get(jobURL, params={"WAIT": "5"}).text
	assert '<uws:phase>EXECUTING</uws:phase>' in res
	assert abs(times.next()-5)<2.5

	# make sure things come pack immediately if PHASE isn't right
	res = requests.get(jobURL, params={"PHASE": "QUEUED", "WAIT": "-1"}).text
	assert '<uws:phase>EXECUTING</uws:phase>' in res
	assert abs(times.next())<0.1

	# then wait for completion
	res = requests.get(jobURL, params={"WAIT": "-1"}).text
	assert '<uws:phase>COMPLETED</uws:phase>' in res
	assert abs(times.next()-5)<2.5


def run_slowpoll_test():
	job = votable.ADQLTAPJob(ENDPOINT_URL,	
		"JUST HANG around")

	try:
		run_basic_tests(job)
	finally:
		job.delete()

if __name__=="__main__":
	run_slowpoll_test()


