from com.xebialabs.xltest.domain import TestRun
from com.xebialabs.deployit.plugin.api.reflect import Type
from com.xebialabs.deployit.repository import SearchParameters

import urllib2

# self is an instance of Report, 'repository' is the JCR repo and 'testRun' contains info about the run.
# pass the result into 'resultholder' like this: resultHolder.setResult({ 'success': success })

testSetDefinitionId = testRun.testSetDefinition.id

query = SearchParameters().setType(Type.valueOf(TestRun));
testRunCis = repository.listEntities(query);

testRunCis = filter(lambda t: t.testSetDefinition.id == testSetDefinitionId, testRunCis)
# NB we now have a real python list....use len not size()....

testRunCis.sort(key=lambda t: t.startTime)
# get the last 5 (note the exclusion of the last as that is the last run itself!)
testRunCis = testRunCis[-6:-1]

# now get the jmeterresult event from each of the testruns
all_throughputs = []
print ""
for t in testRunCis:
  eventsInRun = t.getEvents()
  for ev in eventsInRun:
    if ev.type == 'jmeterresult':
      all_throughputs.append(float(ev.get('result')))

print 'previous throughput results', all_throughputs
avg_throughput = 0
if len(all_throughputs) > 0:
  avg_throughput = sum(all_throughputs) / len(all_throughputs)
else:
  print "WARNING avg throughput could not be computed. Its length is zero"

last_throughput = 0
import time
time.sleep(1) # delays for 1 seconds to get consistency in store. Yes this is debatable.
events_in_current_run = testRun.getEvents()
for ev in events_in_current_run:
  if ev.type == 'jmeterresult':
    last_throughput = float(ev.get('result'))

success = (float(last_throughput) * 1.1) > avg_throughput
print "success: ", success, "(float(last_throughput) * 1.1) is: ", (float(last_throughput) * 1.1), "should be larger than", avg_throughput
resultHolder.setResult(success)
