"""
Some (regression-type) tests for didresolver.

This depends on an installed GAVO DaCHS.

We'll instrument didresolver.requests and didresolver_query_registry
left and right for these tests; the instrumentation context manager.

Sorry for the messy source code.  Maybe we should keep the canned
responses and answers somewhere else?
"""

import contextlib
import os
os.environ["GAVO_OOTTEST"] = "dontcare"

from gavo import api
from gavo import utils
from gavo.helpers import testhelpers


RD = api.getRD("ivoidval/q")
modName = os.path.join(RD.resdir, "bin/didresolver")
didresolver, _ = utils.loadPythonModule(modName)


class _FakeResponse(object):
	"""fakes a requests.Response object.
	"""
	def __init__(self, s):
		if isinstance(s, bytes):
			self.text = s.decode("utf-8")
			self.content = s
		else:
			self.text = s
			self.content = s.encode("utf-8")


@contextlib.contextmanager
def instrumentation(registry_responses, requests_get_responses,
		obscore_responses):
	real_qr = didresolver.query_registry
	real_rg = didresolver.requests.get
	real_qo = didresolver.query_obscore

	didresolver.query_registry = SeqReturner(registry_responses)
	didresolver.requests.get = SeqReturner(requests_get_responses,
		wrapper=_FakeResponse)
	didresolver.query_obscore = SeqReturner(obscore_responses)

	try:
		yield None
	finally:
		didresolver.query_registry = real_qr
		didresolver.requests.get = real_rg
		didresolver.query_obscore = real_qo


class SeqReturner(object):
	"""An instrumentation helper returning one response after the
	other on being called.
	"""
	def __init__(self, responses, wrapper=lambda s:s):
		self.responses = responses[:]
		self.wrapper = wrapper
	
	def __call__(self, *args, **kwargs):
		return self.wrapper(self.responses.pop(0))


class OfflineTest(testhelpers.VerboseTest):
	def test_no_DID(self):
		self.assertEqual(
			didresolver.resolve_did("ivo://iova.net/stc/Identifiers"),
			[{'rec_type': 'ERROR', 'message': "No PubDID (no local part?)",
				'access_uri': None}])

	def test_no_ivoid(self):
		self.assertEqual(
			didresolver.resolve_did("http://iova.net/stc/Identifiers?foo"),
			[{'rec_type': 'ERROR', 'message': "No PubDID (not in ivo:// scheme)",
				'access_uri': None}])


class _InstrumentedTest(testhelpers.VerboseTest):
	"""A base class for tests with canned responses from the registry and
	then net.

	In registry_responses, you give a sequence of responses to be
	returned on consecutive calls to query_registry; similarly
	requests_get_responses for requests.get.

	Then call the get_core_response() method, and you'll get the sequence as
	returned by resolve_did.
	"""
	registry_responses = []
	requests_get_responses = []
	obscore_responses = []

	def get_core_response(self, force_related=False):
		with instrumentation(self.registry_responses,
				self.requests_get_responses, self.obscore_responses):
			return didresolver.resolve_did("ivo://test?testing",
				force_related=force_related)


class NotFoundTest(_InstrumentedTest):
	def test_empty_error(self):
		self.assertEqual(self.get_core_response(),
			[{'message': 'Could not resolve ivo://test?testing', 'rec_type': 'ERROR', 'access_uri': None}])

	registry_responses = [[], []]
	requests_get_responses = []
	

class DatalinkTest(_InstrumentedTest):
	def testResolution(self):
		res = self.get_core_response()
		self.assertEqual(res,
			[{'message': 'From a datalink service at http://dc.zah.uni-heidelberg.de/__system__/products/dl/dlmeta', 'rec_type': 'RESULT', 'access_uri': 'http://dc.zah.uni-heidelberg.de/getproduct/flashheros/data/taut/f0691.mt'}])

	registry_responses = [[{'ivoid': 'ivo://org.gavo.dc/~', 'urls': 'http://dc.zah.uni-heidelberg.de/__system__/products/dl/dlmeta_&ID_SEP&_http://dc.zah.uni-heidelberg.de/__system__/products/p/availability_&ID_SEP&_http://dc.zah.uni-heidelberg.de/__system__/products/p/capabilities_&ID_SEP&_http://dc.zah.uni-heidelberg.de/__system__/products/p/tableMetadata', 'caps': 'ivo://ivoa.net/std/datalink#links-1.0_&ID_SEP&_ivo://ivoa.net/std/vosi#availability_&ID_SEP&_ivo://ivoa.net/std/vosi#capabilities_&ID_SEP&_ivo://ivoa.net/std/vosi#tables'}]]
	requests_get_responses = [b'<?xml-stylesheet href=\'/static/xsl/datalink-to-html.xsl\' type=\'text/xsl\'?><VOTABLE version="1.2" xmlns="http://www.ivoa.net/xml/VOTable/v1.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.ivoa.net/xml/VOTable/v1.2 http://vo.ari.uni-heidelberg.de/docs/schemata/VOTable-1.2.xsd"><RESOURCE type="results"><TABLE name="dlresponse"><DESCRIPTION>Data links for data sets.</DESCRIPTION><FIELD ID="ID" arraysize="*" datatype="char" name="ID" ucd="meta.id;meta.main"><DESCRIPTION>Publisher data set id; this is an identifier for the dataset in question and can be used to retrieve the data.</DESCRIPTION></FIELD><FIELD ID="access_url" arraysize="*" datatype="char" name="access_url" ucd="meta.ref.url"><DESCRIPTION>URL to retrieve the data or access the service.</DESCRIPTION></FIELD><FIELD ID="service_def" arraysize="*" datatype="char" name="service_def" ucd="meta.code"><DESCRIPTION>Identifier for the type of service if accessURL refers to a service.</DESCRIPTION></FIELD><FIELD ID="error_message" arraysize="*" datatype="char" name="error_message" ucd="meta.code.error"><DESCRIPTION>If accessURL is empty, this column gives the reason why.</DESCRIPTION></FIELD><FIELD ID="description" arraysize="*" datatype="char" name="description" ucd="meta.note"><DESCRIPTION>More information on this link</DESCRIPTION></FIELD><FIELD ID="semantics" arraysize="*" datatype="char" name="semantics" ucd="meta.code"><DESCRIPTION>What kind of data is linked here? Standard identifiers here include science, calibration, preview, info, auxiliary</DESCRIPTION></FIELD><FIELD ID="content_type" arraysize="*" datatype="char" name="content_type" ucd="meta.code.mime"><DESCRIPTION>MIME type for the data returned.</DESCRIPTION></FIELD><FIELD ID="content_length" datatype="long" name="content_length" ucd="phys.size;meta.file" unit="byte"><DESCRIPTION>Size of the resource at access_url</DESCRIPTION><VALUES null="-1"></VALUES></FIELD><DATA><TABLEDATA><TR><TD>ivo://org.gavo.dc/~?flashheros/data/taut/f0691.mt</TD><TD>http://dc.zah.uni-heidelberg.de/getproduct/flashheros/data/taut/f0691.mt</TD><TD></TD><TD></TD><TD>The full dataset.</TD><TD>#this</TD><TD>image/fits</TD><TD>100800</TD></TR><TR><TD>ivo://org.gavo.dc/~?flashheros/data/taut/f0691.mt</TD><TD>http://dc.zah.uni-heidelberg.de/getproduct/flashheros/data/taut/f0691.mt?preview=True</TD><TD></TD><TD></TD><TD>A preview for the dataset.</TD><TD>#preview</TD><TD>image/png</TD><TD>-1</TD></TR></TABLEDATA></DATA></TABLE></RESOURCE></VOTABLE>']


class SSATest(_InstrumentedTest):
	def testResolution(self):
		self.assertEqual(self.get_core_response(),
			[{'message': 'From an SSAP service at http://dc.zah.uni-heidelberg.de/feros/q/ssa/ssap.xml?', 'rec_type': 'RESULT', 'access_uri': 'http://dc.zah.uni-heidelberg.de/getproduct/feros/data/f04031.fits'}, {'message': 'From an SSAP service at http://dc.zah.uni-heidelberg.de/feros/q/ssa/ssap.xml?', 'rec_type': 'RESULT', 'access_uri': 'http://dc.zah.uni-heidelberg.de/getproduct/feros/data/f04031.vot'}])
	
	registry_responses = [[{'ivoid': 'ivo://org.gavo.dc/feros/q/ssa', 'urls': 'http://dc.zah.uni-heidelberg.de/feros/q/ssa/ssap.xml?_&ID_SEP&_http://dc.zah.uni-heidelberg.de/feros/q/ssa/availability_&ID_SEP&_http://dc.zah.uni-heidelberg.de/feros/q/ssa/capabilities_&ID_SEP&_http://dc.zah.uni-heidelberg.de/feros/q/ssa/tableMetadata', 'caps': 'ivo://ivoa.net/std/ssa_&ID_SEP&_ivo://ivoa.net/std/vosi#availability_&ID_SEP&_ivo://ivoa.net/std/vosi#capabilities_&ID_SEP&_ivo://ivoa.net/std/vosi#tables'}]]
	requests_get_responses = [b'<VOTABLE version="1.2" xmlns="http://www.ivoa.net/xml/VOTable/v1.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.ivoa.net/xml/VOTable/v1.2 http://vo.ari.uni-heidelberg.de/docs/schemata/VOTable-1.2.xsd" xmlns:ssa="http://www.ivoa.net/xml/DalSsap/v1.0"><DESCRIPTION> Spectra from FEROS spectrograph at La Silla\'s 1.5m telescope as\nobtained during commissioning and guaranteed time.</DESCRIPTION><INFO name="legal" value="\nIf you use this data, please reference \n`Kaufer, A., et al: Commissioning FEROS, the new high-resolution\nspectrograph at La-Silla.\n&lt;http://ads.ari.uni-heidelberg.de/abs/1999Msngr..95....8K&gt;`_."></INFO><RESOURCE type="results"><INFO name="SERVICE_PROTOCOL" value="1.04">SSAP</INFO><INFO name="QUERY_STATUS" value="OK"></INFO><TABLE name="result"><INFO name="source" value="1999Msngr..95....8K"></INFO><GROUP utype="stc:CatalogEntryLocation"><PARAM arraysize="*" datatype="char" name="CoordFlavor" utype="stc:AstroCoordSystem.SpaceFrame.CoordFlavor" value="SPHERICAL"/><PARAM arraysize="*" datatype="char" name="CoordRefFrame" utype="stc:AstroCoordSystem.SpaceFrame.CoordRefFrame" value="ICRS"/><PARAM arraysize="*" datatype="char" name="URI" utype="stc:DataModel.URI" value="http://www.ivoa.net/xml/STC/stc-v1.30.xsd"/><FIELDref ref="location_ra" utype="stc:AstroCoords.Position2D.Value2.C1"/><FIELDref ref="location_dec" utype="stc:AstroCoords.Position2D.Value2.C2"/></GROUP><GROUP utype="stc:CatalogEntryLocation"><PARAM arraysize="*" datatype="char" name="CoordFlavor" utype="stc:AstroCoordSystem.SpaceFrame.CoordFlavor" value="SPHERICAL"/><PARAM arraysize="*" datatype="char" name="CoordRefFrame" utype="stc:AstroCoordSystem.SpaceFrame.CoordRefFrame" value="ICRS"/><PARAM arraysize="*" datatype="char" name="TimeScale" utype="stc:AstroCoordSystem.TimeFrame.TimeScale" value="TT"/><PARAM arraysize="*" datatype="char" name="URI" utype="stc:DataModel.URI" value="http://www.ivoa.net/xml/STC/stc-v1.30.xsd"/><FIELDref ref="ssa_specend" utype="stc:AstroCoordArea.SpectralInterval.HiLimit"/><FIELDref ref="ssa_specstart" utype="stc:AstroCoordArea.SpectralInterval.LoLimit"/><FIELDref ref="ssa_aperture" utype="stc:AstroCoords.Position2D.Size2Radius"/><FIELDref ref="ssa_location" utype="stc:AstroCoords.Position2D.Value2"/><FIELDref ref="ssa_specmid" utype="stc:AstroCoords.Spectral.Value"/><FIELDref ref="ssa_dateObs" utype="stc:AstroCoords.Time.TimeInstant"/></GROUP><FIELD ID="ssa_score" datatype="float" name="ssa_score" ucd="" utype="ssa:Query.Score"><DESCRIPTION>A measure of how closely the record matches your query. Higher numbers mean better matches.</DESCRIPTION></FIELD><FIELD ID="location_ra" datatype="float" name="location_ra" ucd="pos.eq.ra;meta.main" unit="deg" utype="ssa:Char.SpatialAxis.Coverage.Location.Value.C1"/><FIELD ID="location_dec" datatype="float" name="location_dec" ucd="pos.eq.dec;meta.main" unit="deg" utype="ssa:Char.SpatialAxis.Coverage.Location.Value.C2"/><FIELD ID="location_arr" arraysize="2" datatype="float" name="location_arr" ucd="pos.eq" utype="ssa:Char.SpatialAxis.Coverage.Location.Value"><DESCRIPTION>Observed position RA and Dec as a 2-real array as required by SSAP.</DESCRIPTION></FIELD><FIELD ID="target_arr" arraysize="2" datatype="float" name="target_arr" ucd="pos.eq;src" utype="ssa:Target.Pos"><DESCRIPTION>Target RA and Dec as a 2-real array as required by SSAP.</DESCRIPTION></FIELD><FIELD ID="preview" arraysize="*" datatype="char" name="preview" ucd="meta.ref.url;datalink.preview"><DESCRIPTION>URL of a preview for the dataset, where available.</DESCRIPTION></FIELD><FIELD ID="accref" arraysize="*" datatype="char" name="accref" ucd="meta.ref.url;meta.dataset" utype="ssa:Access.Reference"><DESCRIPTION>Access key for the data</DESCRIPTION></FIELD><FIELD ID="mime" arraysize="*" datatype="char" name="mime" ucd="" utype="ssa:Access.Format"><DESCRIPTION>MIME type of the file served</DESCRIPTION></FIELD><FIELD ID="accsize" datatype="int" name="accsize" ucd="VOX:Image_FileSize" unit="byte" utype="ssa:Access.Size"><DESCRIPTION>Size of the data in bytes</DESCRIPTION><VALUES null="-1"></VALUES></FIELD><FIELD ID="ssa_dstitle" arraysize="*" datatype="char" name="ssa_dstitle" ucd="meta.title;meta.dataset" utype="ssa:DataID.Title"><DESCRIPTION>Title or the dataset (usually, spectrum)</DESCRIPTION></FIELD><FIELD ID="ssa_creatorDID" arraysize="*" datatype="char" name="ssa_creatorDID" ucd="meta.id" utype="ssa:DataID.CreatorDID"><DESCRIPTION>Dataset identifier assigned by the creator</DESCRIPTION></FIELD><FIELD ID="ssa_pubDID" arraysize="*" datatype="char" name="ssa_pubDID" ucd="" utype="ssa:Curation.PublisherDID"><DESCRIPTION>Dataset identifier assigned by the publisher</DESCRIPTION></FIELD><FIELD ID="ssa_cdate" arraysize="*" datatype="char" name="ssa_cdate" ucd="time;meta.dataset" utype="ssa:DataID.Date" xtype="adql:TIMESTAMP"><DESCRIPTION>Processing/Creation date</DESCRIPTION><VALUES null=""></VALUES></FIELD><FIELD ID="ssa_pdate" arraysize="*" datatype="char" name="ssa_pdate" ucd="" utype="ssa:Curation.Date" xtype="adql:TIMESTAMP"><DESCRIPTION>Date last published.</DESCRIPTION><VALUES null=""></VALUES></FIELD><FIELD ID="ssa_bandpass" arraysize="*" datatype="char" name="ssa_bandpass" ucd="instr.bandpass" utype="ssa:DataID.Bandpass"><DESCRIPTION>Bandpass (i.e., rough spectral location) of this dataset; use something generic like \'Optical\' here.</DESCRIPTION></FIELD><FIELD ID="ssa_cversion" arraysize="*" datatype="char" name="ssa_cversion" ucd="meta.version;meta.dataset" utype="ssa:DataID.Version"><DESCRIPTION>Creator assigned version for this dataset (will be incremented when this particular item is changed).</DESCRIPTION></FIELD><FIELD ID="ssa_targname" arraysize="*" datatype="char" name="ssa_targname" ucd="meta.id;src" utype="ssa:Target.Name"><DESCRIPTION>Common name of object observed.</DESCRIPTION></FIELD><FIELD ID="ssa_targclass" arraysize="*" datatype="char" name="ssa_targclass" ucd="src.class" utype="ssa:Target.Class"><DESCRIPTION>Object class (star, QSO,...)</DESCRIPTION></FIELD><FIELD ID="ssa_redshift" datatype="float" name="ssa_redshift" ucd="src.redshift" utype="ssa:Target.Redshift"><DESCRIPTION>Redshift of target object</DESCRIPTION></FIELD><FIELD ID="ssa_targetpos" arraysize="2" datatype="double" name="ssa_targetpos" ucd="pos.eq;src" utype="ssa:Target.pos.spoint"><DESCRIPTION>Equatorial (ICRS) position of the target object.</DESCRIPTION></FIELD><FIELD ID="ssa_snr" datatype="float" name="ssa_snr" ucd="stat.snr" utype="ssa:Derived.SNR"><DESCRIPTION>Signal-to-noise ratio estimated for this dataset</DESCRIPTION></FIELD><FIELD ID="ssa_location" arraysize="2" datatype="double" name="ssa_location" ucd="pos.eq" unit="deg" utype="stc:AstroCoords.Position2D.Value2"><DESCRIPTION>ICRS location of aperture center</DESCRIPTION></FIELD><FIELD ID="ssa_aperture" datatype="float" name="ssa_aperture" ucd="instr.fov" unit="deg" utype="ssa:Char.SpatialAxis.Coverage.Bounds.Extent"><DESCRIPTION>Angular diameter of aperture</DESCRIPTION></FIELD><FIELD ID="ssa_dateObs" datatype="double" name="ssa_dateObs" ucd="time.epoch" unit="d" utype="ssa:Char.TimeAxis.Coverage.Location.Value" xtype="mjd"><DESCRIPTION>Midpoint of exposure</DESCRIPTION></FIELD><FIELD ID="ssa_timeExt" datatype="float" name="ssa_timeExt" ucd="time.duration" unit="s" utype="ssa:Char.TimeAxis.Coverage.Bounds.Extent"><DESCRIPTION>Exposure duration</DESCRIPTION></FIELD><FIELD ID="ssa_specmid" datatype="float" name="ssa_specmid" ucd="em.wl;instr.bandpass" unit="m" utype="ssa:Char.SpectralAxis.Coverage.Location.Value"><DESCRIPTION>Midpoint of region covered in this dataset</DESCRIPTION></FIELD><FIELD ID="ssa_specext" datatype="float" name="ssa_specext" ucd="em.wl;instr.bandwidth" unit="m" utype="ssa:Char.SpectralAxis.Coverage.Bounds.Extent"><DESCRIPTION>Width of the spectrum</DESCRIPTION></FIELD><FIELD ID="ssa_specstart" datatype="float" name="ssa_specstart" ucd="em.wl;stat.min" unit="m" utype="ssa:Char.SpectralAxis.Coverage.Bounds.Start"><DESCRIPTION>Lower value of spectral coordinate</DESCRIPTION></FIELD><FIELD ID="ssa_specend" datatype="float" name="ssa_specend" ucd="em.wl;stat.max" unit="m" utype="ssa:Char.SpectralAxis.Coverage.Bounds.Stop"><DESCRIPTION>Upper value of spectral coordinate</DESCRIPTION></FIELD><FIELD ID="ssa_length" datatype="int" name="ssa_length" ucd="" utype="ssa:Dataset.Length"><DESCRIPTION>Number of points in the spectrum</DESCRIPTION><VALUES null="-1"></VALUES></FIELD><PARAM arraysize="*" datatype="char" name="ssa_model" ucd="" utype="ssa:Dataset.DataModel" value="Spectrum-1.0"><DESCRIPTION>Data model name and version</DESCRIPTION></PARAM><PARAM arraysize="*" datatype="char" name="ssa_csysName" ucd="" utype="ssa:CoordSys.SpaceFrame.Name" value="ICRS"><DESCRIPTION>System RA and Dec are given in</DESCRIPTION></PARAM><PARAM arraysize="*" datatype="char" name="ssa_timeSI" ucd="" utype="ssa:Dataset.TimeSI" value=""><DESCRIPTION>Time conversion factor in Osuna-Salgado convention.</DESCRIPTION></PARAM><PARAM arraysize="*" datatype="char" name="ssa_spectralSI" ucd="" utype="ssa:Dataset.SpectralSI" value=""><DESCRIPTION>Spectral conversion factor in Osuna-Salgado convention</DESCRIPTION></PARAM><PARAM arraysize="*" datatype="char" name="ssa_spectralucd" ucd="" utype="ssa:Char.SpectralAxis.Ucd" value="em.wl"><DESCRIPTION>UCD of the spectral column</DESCRIPTION></PARAM><PARAM arraysize="*" datatype="char" name="ssa_spectralunit" ucd="" utype="ssa:Char.SpectralAxis.Unit" value="0.1 nm"><DESCRIPTION>Unit of the spectral column</DESCRIPTION></PARAM><PARAM arraysize="*" datatype="char" name="ssa_fluxSI" ucd="" utype="ssa:Dataset.FluxSI" value=""><DESCRIPTION>Flux/magnitude conversion factor in Osuna-Salgado convention</DESCRIPTION></PARAM><PARAM arraysize="*" datatype="char" name="ssa_fluxucd" ucd="" utype="ssa:Char.FluxAxis.Ucd" value="phot.flux.density"><DESCRIPTION>UCD of the flux column</DESCRIPTION></PARAM><PARAM arraysize="*" datatype="char" name="ssa_fluxunit" ucd="" utype="ssa:Char.FluxAxis.Unit" value=" "><DESCRIPTION>Unit of the flux column</DESCRIPTION></PARAM><PARAM arraysize="*" datatype="char" name="ssa_dstype" ucd="" utype="ssa:Dataset.Type" value="Spectrum"><DESCRIPTION>Type of data (spectrum, time series, etc)</DESCRIPTION></PARAM><PARAM arraysize="*" datatype="char" name="ssa_publisher" ucd="" utype="ssa:Curation.Publisher" value="ivo://org.gavo.dc"><DESCRIPTION>Publisher of the datasets included here.</DESCRIPTION></PARAM><PARAM arraysize="*" datatype="char" name="ssa_creator" ucd="" utype="ssa:DataID.Creator" value=""><DESCRIPTION>Creator of the datasets included here.</DESCRIPTION></PARAM><PARAM arraysize="*" datatype="char" name="ssa_collection" ucd="" utype="ssa:DataID.Collection" value=""><DESCRIPTION>IOVA id of the originating data collection</DESCRIPTION></PARAM><PARAM arraysize="*" datatype="char" name="ssa_instrument" ucd="meta.id;instr" utype="ssa:DataID.Instrument" value="FEROS"><DESCRIPTION>Instrument or code used to produce these datasets</DESCRIPTION></PARAM><PARAM arraysize="*" datatype="char" name="ssa_datasource" ucd="" utype="ssa:DataID.DataSource" value="pointed"><DESCRIPTION>Method of generation for the data.</DESCRIPTION></PARAM><PARAM arraysize="*" datatype="char" name="ssa_creationtype" ucd="" utype="ssa:DataID.CreationType" value="archival"><DESCRIPTION>Process used to produce the data</DESCRIPTION></PARAM><PARAM arraysize="*" datatype="char" name="ssa_reference" ucd="" utype="ssa:Curation.Reference" value="1999Msngr..95....8K"><DESCRIPTION>URL or bibcode of a publication describing this data.</DESCRIPTION></PARAM><PARAM datatype="float" name="ssa_fluxStatError" ucd="stat.error;phot.flux.density;em" utype="ssa:Char.FluxAxis.Accuracy.StatError" value=""><DESCRIPTION>Statistical error in flux</DESCRIPTION><VALUES null="NaN"></VALUES></PARAM><PARAM datatype="float" name="ssa_fluxSysError" ucd="stat.error.sys;phot.flux.density;em" utype="ssa:Char.FluxAxis.Accuracy.SysError" value=""><DESCRIPTION>Systematic error in flux</DESCRIPTION><VALUES null="NaN"></VALUES></PARAM><PARAM arraysize="*" datatype="char" name="ssa_fluxcalib" ucd="" utype="ssa:Char.FluxAxis.Calibration" value="UNCALIBRATED"><DESCRIPTION>Type of flux calibration</DESCRIPTION></PARAM><PARAM datatype="float" name="ssa_binSize" ucd="em.wl;spect.binSize" unit="m" utype="ssa:Char.SpectralAxis.Accuracy.BinSize" value=""><DESCRIPTION>Bin size in wavelength</DESCRIPTION></PARAM><PARAM datatype="float" name="ssa_spectStatError" ucd="stat.error;em" unit="m" utype="ssa:Char.SpectralAxis.Accuracy.StatError" value=""><DESCRIPTION>Statistical error in wavelength</DESCRIPTION><VALUES null="NaN"></VALUES></PARAM><PARAM datatype="float" name="ssa_spectSysError" ucd="stat.error.sys;em" unit="m" utype="ssa:Char.SpectralAxis.Accuracy.SysError" value=""><DESCRIPTION>Systematic error in wavelength</DESCRIPTION><VALUES null="NaN"></VALUES></PARAM><PARAM arraysize="*" datatype="char" name="ssa_speccalib" ucd="meta.code.qual" utype="ssa:Char.SpectralAxis.Calibration" value="ABSOLUTE"><DESCRIPTION>Type of wavelength calibration</DESCRIPTION></PARAM><PARAM datatype="float" name="ssa_specres" ucd="spect.resolution;em.wl" unit="m" utype="ssa:Char.SpectralAxis.Resolution" value="48000"><DESCRIPTION>Resolution on the spectral axis</DESCRIPTION><VALUES null="NaN"></VALUES></PARAM><PARAM datatype="float" name="ssa_spaceError" ucd="stat.error;pos.eq" unit="deg" utype="ssa:Char.SpatialAxis.Accuracy.StatError" value=""><DESCRIPTION>Statistical error in position</DESCRIPTION><VALUES null="NaN"></VALUES></PARAM><PARAM arraysize="*" datatype="char" name="ssa_spaceCalib" ucd="meta.code.qual" utype="ssa:Char.SpatialAxis.Calibration" value=""><DESCRIPTION>Type of calibration in spatial coordinates</DESCRIPTION></PARAM><PARAM datatype="float" name="ssa_spaceRes" ucd="pos.angResolution" unit="deg" utype="ssa:Char.SpatialAxis.Resolution" value=""><DESCRIPTION>Spatial resolution of data</DESCRIPTION></PARAM><DATA><TABLEDATA><TR><TD>0.0</TD><TD>64.9483493733183</TD><TD>15.6276431732484</TD><TD>64.9483493733183 15.6276431732484</TD><TD>NaN NaN</TD><TD>http://dc.zah.uni-heidelberg.de/getproduct/feros/data/f04031.fits?preview=True</TD><TD>http://dc.zah.uni-heidelberg.de/getproduct/feros/data/f04031.fits</TD><TD>image/fits</TD><TD>771840</TD><TD>Feros HD 27371 MJD 51095.2417593</TD><TD></TD><TD>ivo://org.gavo.dc/feros/q/ssa?f04031.bdf</TD><TD>1999-02-11T09:12:42</TD><TD>2015-09-30T09:58:38.370047</TD><TD>Optical,IR</TD><TD></TD><TD>HD 27371</TD><TD>star</TD><TD>NaN</TD><TD>NaN NaN</TD><TD>NaN</TD><TD>64.9483493733183 15.6276431732484</TD><TD>0.00075</TD><TD>51095.2417593002</TD><TD>60.0</TD><TD>6.37081e-07</TD><TD>5.68203e-07</TD><TD>3.5298e-07</TD><TD>9.21183e-07</TD><TD>189402</TD></TR><TR><TD>0.0</TD><TD>64.9483493733183</TD><TD>15.6276431732484</TD><TD>64.9483493733183 15.6276431732484</TD><TD>NaN NaN</TD><TD>http://dc.zah.uni-heidelberg.de/getproduct/feros/data/f04031.vot?preview=True</TD><TD>http://dc.zah.uni-heidelberg.de/getproduct/feros/data/f04031.vot</TD><TD>application/x-votable+xml</TD><TD>771840</TD><TD>Feros HD 27371 MJD 51095.2417593</TD><TD></TD><TD>ivo://org.gavo.dc/feros/q/ssa?f04031.bdf</TD><TD>1999-02-11T09:12:42</TD><TD>2015-09-30T09:58:38.370240</TD><TD>Optical,IR</TD><TD></TD><TD>HD 27371</TD><TD>star</TD><TD>NaN</TD><TD>NaN NaN</TD><TD>NaN</TD><TD>64.9483493733183 15.6276431732484</TD><TD>0.00075</TD><TD>51095.2417593002</TD><TD>60.0</TD><TD>6.37081e-07</TD><TD>5.68203e-07</TD><TD>3.5298e-07</TD><TD>9.21183e-07</TD><TD>189402</TD></TR></TABLEDATA></DATA></TABLE></RESOURCE><RESOURCE name="getDataMeta"><TABLE name="generationParameters"><PARAM arraysize="*" datatype="char" name="FLUXCALIB" value=""><DESCRIPTION>Recalibrate the spectrum to...</DESCRIPTION><VALUES><OPTION name="RELATIVE" value="RELATIVE"/><OPTION name="UNCALIBRATED" value="UNCALIBRATED"/></VALUES></PARAM><PARAM arraysize="m" datatype="char" name="BAND" unit="m" value=""><DESCRIPTION>The spectral range of the cutout</DESCRIPTION><VALUES><MIN value="3.5298e-07"></MIN><MAX value="9.21183e-07"></MAX></VALUES></PARAM><PARAM arraysize="*" datatype="char" name="FORMAT" value="application/x-votable+xml"><DESCRIPTION>Format to deliver the spectrum in.</DESCRIPTION><VALUES><OPTION name="VOTable, experimental spectral DM 2 serialization" value="application/x-votable+xml;content=spec2"/><OPTION name="FITS binary table" value="application/fits"/><OPTION name="Comma separated values" value="text/csv"/><OPTION name="VOTable, tabledata encoding" value="application/x-votable+xml;serialization=tabledata"/><OPTION name="VOTable, binary encoding" value="application/x-votable+xml"/><OPTION name="Tab separated values" value="text/plain"/></VALUES></PARAM></TABLE></RESOURCE><RESOURCE ID="ahehhawbwedn" type="meta" utype="adhoc:service"><GROUP utype="stc:CatalogEntryLocation"><PARAM arraysize="*" datatype="char" name="URI" utype="stc:DataModel.URI" value="http://www.ivoa.net/xml/STC/stc-v1.30.xsd"/><PARAMref ref="ahepaebuwedn" utype="stc:AstroCoordArea.SpectralInterval.HiLimit"/><PARAMref ref="aeepaebuwedn" utype="stc:AstroCoordArea.SpectralInterval.LoLimit"/></GROUP><GROUP name="inputParams"><PARAM arraysize="*" datatype="char" name="ID" ref="ssa_pubDID" ucd="meta.id;meta.main" value=""><DESCRIPTION>The pubisher DID of the dataset of interest</DESCRIPTION><LINK content-role="ddl:id-source" value="#ssa_pubDID"/></PARAM><PARAM arraysize="*" datatype="char" name="FLUXCALIB" ucd="phot.calib" utype="ssa:Char.FluxAxis.Calibration" value=""><DESCRIPTION>Recalibrate the spectrum.  Right now, the only recalibration supported is max(flux)=1 (\'RELATIVE\').</DESCRIPTION><VALUES><OPTION name="RELATIVE" value="RELATIVE"/><OPTION name="UNCALIBRATED" value="UNCALIBRATED"/></VALUES></PARAM><PARAM ID="aeepaebuwedn" datatype="float" name="LAMBDA_MIN" ucd="par.min;em.wl" unit="m" value=""><DESCRIPTION>Spectral cutout interval, lower limit</DESCRIPTION><VALUES><MIN value="3.5298e-07"></MIN><MAX value="9.21183e-07"></MAX></VALUES></PARAM><PARAM ID="ahepaebuwedn" datatype="float" name="LAMBDA_MAX" ucd="par.max;em.wl" unit="m" value=""><DESCRIPTION>Spectral cutout interval, upper limit</DESCRIPTION><VALUES><MIN value="3.5298e-07"></MIN><MAX value="9.21183e-07"></MAX></VALUES></PARAM><PARAM arraysize="*" datatype="char" name="FORMAT" ucd="meta.code.mime" utype="ssa:Access.Format" value=""><DESCRIPTION>MIME type of the output format</DESCRIPTION><VALUES><OPTION name="VOTable, experimental spectral DM 2 serialization" value="application/x-votable+xml;content=spec2"/><OPTION name="FITS binary table" value="application/fits"/><OPTION name="Comma separated values" value="text/csv"/><OPTION name="VOTable, tabledata encoding" value="application/x-votable+xml;serialization=tabledata"/><OPTION name="VOTable, binary encoding" value="application/x-votable+xml"/><OPTION name="Tab separated values" value="text/plain"/></VALUES></PARAM></GROUP><PARAM arraysize="*" datatype="char" name="accessURL" ucd="meta.ref.url" value="http://dc.zah.uni-heidelberg.de/feros/q/sdl/dlget"/><PARAM arraysize="*" datatype="char" name="standardID" value="ivo://ivoa.net/std/SSDP#sync"/></RESOURCE><RESOURCE type="meta" utype="adhoc:service"><GROUP name="inputParams"><PARAM arraysize="*" datatype="char" name="ID" ref="ssa_pubDID" ucd="meta.id;meta.main" value=""><LINK content-role="ddl:id-source" value="#ssa_pubDID"/></PARAM></GROUP><PARAM arraysize="*" datatype="char" name="standardID" value="ivo://ivoa.net/std/DataLink#links-1.0"/><PARAM arraysize="*" datatype="char" name="accessURL" value="http://dc.zah.uni-heidelberg.de/feros/q/sdl/dlmeta"/></RESOURCE></VOTABLE>']


# ivo://org.gavo.dc/tap?mlqso/data/slits/BRI0952_data.fits
class ObscoreTest(_InstrumentedTest):
	def testResolution(self):
		self.assertEqual(self.get_core_response(),
			[{'rec_type': 'RESULT', 'message': 'From an obscore service at http://dc.zah.uni-heidelberg.de/tap', 'access_uri': 'http://dc.zah.uni-heidelberg.de/getproduct?key=mlqso/data/slits/BRI0952_data.fits'}])

	registry_responses = [[{'ivoid': 'ivo://org.gavo.dc/tap', 'urls': 'http://dc.zah.uni-heidelberg.de/tap_&ID_SEP&_http://dc.zah.uni-heidelberg.de/__system__/tap/run/availability_&ID_SEP&_http://dc.zah.uni-heidelberg.de/__system__/tap/run/capabilities_&ID_SEP&_http://dc.zah.uni-heidelberg.de/__system__/tap/run/tableMetadata', 'caps': 'ivo://ivoa.net/std/tap_&ID_SEP&_ivo://ivoa.net/std/vosi#availability_&ID_SEP&_ivo://ivoa.net/std/vosi#capabilities_&ID_SEP&_ivo://ivoa.net/std/vosi#tables'}]]
	requests_get_responses = []
	obscore_responses = [[{'access_url': 'http://dc.zah.uni-heidelberg.de/getproduct?key=mlqso/data/slits/BRI0952_data.fits', 'access_format': 'image/fits'}]]


# ivo://org.gavo.dc/apo/res/apo/frames?apo/cd/9506/L2237_950602_r_01.fits
class IndirectTest(_InstrumentedTest):
	def testResolution(self):
		self.assertEqual(self.get_core_response(True),
			[{'rec_type': 'RESULT', 'message': 'From an obscore service at http://dc.zah.uni-heidelberg.de/__system__/tap/run/tap', 'access_uri': 'http://dc.zah.uni-heidelberg.de/getproduct?key=apo/cd/9506/L2237_950602_r_01.fits'}, {'rec_type': 'RESULT', 'message': 'From an obscore service at http://dc.zah.uni-heidelberg.de/tap', 'access_uri': 'http://dc.zah.uni-heidelberg.de/getproduct?key=apo/cd/9506/L2237_950602_r_01.fits'}, {'rec_type': 'RESULT', 'message': 'From an obscore service at http://dc.zah.uni-heidelberg.de/tap', 'access_uri': 'http://dc.zah.uni-heidelberg.de/getproduct?key=apo/cd/9506/L2237_950602_r_01.fits'}])
	
	registry_responses = [[{'ivoid': 'ivo://org.gavo.dc/apo/res/apo/frames', 'urls': 'http://dc.zah.uni-heidelberg.de/lensunion/q/im/siap.xml?_&ID_SEP&_http://dc.zah.uni-heidelberg.de/__system__/tap/run/tap', 'caps': 'ivo://ivoa.net/std/sia#aux_&ID_SEP&_ivo://ivoa.net/std/tap#aux'}], [{'related_id': 'ivo://org.gavo.dc/tap'}, {'related_id': 'ivo://org.gavo.dc/lensunion/q/im'}, {'related_id': 'ivo://org.gavo.dc/tap'}], [{'ivoid': 'ivo://org.gavo.dc/tap', 'urls': 'http://dc.zah.uni-heidelberg.de/tap_&ID_SEP&_http://dc.zah.uni-heidelberg.de/__system__/tap/run/availability_&ID_SEP&_http://dc.zah.uni-heidelberg.de/__system__/tap/run/capabilities_&ID_SEP&_http://dc.zah.uni-heidelberg.de/__system__/tap/run/tableMetadata', 'caps': 'ivo://ivoa.net/std/tap_&ID_SEP&_ivo://ivoa.net/std/vosi#availability_&ID_SEP&_ivo://ivoa.net/std/vosi#capabilities_&ID_SEP&_ivo://ivoa.net/std/vosi#tables'}], [{'ivoid': 'ivo://org.gavo.dc/lensunion/q/im', 'urls': 'http://dc.zah.uni-heidelberg.de/lensunion/q/im/siap.xml?_&ID_SEP&_http://dc.zah.uni-heidelberg.de/lensunion/q/im/availability_&ID_SEP&_http://dc.zah.uni-heidelberg.de/lensunion/q/im/capabilities_&ID_SEP&_http://dc.zah.uni-heidelberg.de/lensunion/q/im/tableMetadata', 'caps': 'ivo://ivoa.net/std/sia_&ID_SEP&_ivo://ivoa.net/std/vosi#availability_&ID_SEP&_ivo://ivoa.net/std/vosi#capabilities_&ID_SEP&_ivo://ivoa.net/std/vosi#tables'}], [{'ivoid': 'ivo://org.gavo.dc/tap', 'urls': 'http://dc.zah.uni-heidelberg.de/tap_&ID_SEP&_http://dc.zah.uni-heidelberg.de/__system__/tap/run/availability_&ID_SEP&_http://dc.zah.uni-heidelberg.de/__system__/tap/run/capabilities_&ID_SEP&_http://dc.zah.uni-heidelberg.de/__system__/tap/run/tableMetadata', 'caps': 'ivo://ivoa.net/std/tap_&ID_SEP&_ivo://ivoa.net/std/vosi#availability_&ID_SEP&_ivo://ivoa.net/std/vosi#capabilities_&ID_SEP&_ivo://ivoa.net/std/vosi#tables'}]]
	requests_get_responses = []
	obscore_responses = [[{'access_url': 'http://dc.zah.uni-heidelberg.de/getproduct?key=apo/cd/9506/L2237_950602_r_01.fits', 'access_format': 'image/fits'}], [{'access_url': 'http://dc.zah.uni-heidelberg.de/getproduct?key=apo/cd/9506/L2237_950602_r_01.fits', 'access_format': 'image/fits'}], [{'access_url': 'http://dc.zah.uni-heidelberg.de/getproduct?key=apo/cd/9506/L2237_950602_r_01.fits', 'access_format': 'image/fits'}]]


if __name__=="__main__":
	testhelpers.main(OfflineTest)
