# Path: tests/common.py
# def get_output(doc):
#     """Copied from pywps/tests/test_execute.py.
#     TODO: make this helper method public in pywps."""
#     output = {}
#     for output_el in xpath_ns(doc, '/wps:ExecuteResponse'
#                                    '/wps:ProcessOutputs/wps:Output'):
#         [identifier_el] = xpath_ns(output_el, './ows:Identifier')
# 
#         lit_el = xpath_ns(output_el, './wps:Data/wps:LiteralData')
#         if lit_el != []:
#             output[identifier_el.text] = lit_el[0].text
# 
#         ref_el = xpath_ns(output_el, './wps:Reference')
#         if ref_el != []:
#             output[identifier_el.text] = ref_el[0].attrib['href']
# 
#         data_el = xpath_ns(output_el, './wps:Data/wps:ComplexData')
#         if data_el != []:
#             output[identifier_el.text] = data_el[0].text
# 
#     return output
# 
# CFG_FILE = os.path.join(TESTS_HOME, 'test.cfg')
# 
# Path: flyingpigeon/processes/wps_subset_wfs_polygon.py
# class SubsetWFSPolygonProcess(Process, Subsetter):
#     """Subset a NetCDF file using WFS geometry."""
# 
#     def __init__(self):
#         inputs = [
#             resource,
#             LiteralInput('typename',
#                          'TypeName',
#                          abstract='Name of the layer in GeoServer.',
#                          data_type='string',
#                          min_occurs=0,
#                          max_occurs=1),
#             LiteralInput('featureids',
#                          'Feature Ids',
#                          abstract='fid(s) of the feature in the layer.',
#                          data_type='string',
#                          min_occurs=0,
#                          max_occurs=1000),
#             LiteralInput('geoserver',
#                          'Geoserver',
#                          abstract=('Typically of the form '
#                                    'http://host:port/geoserver/wfs'),
#                          data_type='string',
#                          min_occurs=0),
#             start, end, variable]
# 
#         outputs = [output, metalink]
# 
#         super(SubsetWFSPolygonProcess, self).__init__(
#             self._handler,
#             identifier='subset-wfs-polygon',
#             title='Subset',
#             version='0.2',
#             abstract=('Return the data for which grid cells intersect the '
#                       'selected polygon for each input dataset as well as'
#                       'the time range selected.'),
#             inputs=inputs,
#             outputs=outputs,
#             status_supported=True,
#             store_supported=True,
#         )
# 
#     def _handler(self, request, response):
#         geoms, fids = self.parse_feature(request)
#         dr = self.parse_daterange(request)
# 
#         ml = MetaLink4('subset', workdir=self.workdir)
# 
#         for res in self.parse_resources(request):
#             variables = self.parse_variable(request, res)
#             prefix = Path(res).stem
#             # The name must not grow too long.
#             prefix += "_" + fids[0].split(".")[0]
# 
#             rd = ocgis.RequestDataset(res, variables)
# 
#             try:
#                 ops = ocgis.OcgOperations(
#                     dataset=rd, geom=geoms,
#                     agg_selection=True,
#                     spatial_operation='intersects', aggregate=False,
#                     time_range=dr, output_format='nc',
#                     interpolate_spatial_bounds=True,
#                     spatial_wrapping="wrap",
#                     prefix=prefix, dir_output=tempfile.mkdtemp(dir=self.workdir))
# 
#                 out = ops.execute()
# 
#                 mf = MetaFile(prefix, fmt=FORMATS.NETCDF)
#                 mf.file = out
#                 ml.append(mf)
# 
#             except ocgis.exc.ExtentError:
#                 continue
# 
#         response.outputs['output'].file = ml.files[0].file
#         response.outputs['metalink'].data = ml.xml
#         response.update_status("Completed", 100)
# 
#         return response


from pywps import Service
from pywps.tests import client_for, assert_response_success
from .common import get_output, CFG_FILE
from flyingpigeon.processes.wps_subset_wfs_polygon import SubsetWFSPolygonProcess



def test_wps_subset():
    client = client_for(Service(processes=[SubsetWFSPolygonProcess()], cfgfiles=CFG_FILE))

    datainputs = "resource=@xlink:href={nc};" \
                 "typename={typename};" \
                 "geoserver={geoserver};" \
                 "featureids={fid1};" \
                 "featureids={fid2};"

    inputs = dict(nc="https://pavics.ouranos.ca/twitcher/ows/proxy/thredds/dodsC/birdhouse/nrcan"
                     "/nrcan_northamerica_monthly"
                     "/tasmax/nrcan_northamerica_monthly_2015_tasmax.nc",
                  typename="public:USGS_HydroBASINS_lake_na_lev12",
                  geoserver="https://pavics.ouranos.ca/geoserver/wfs",
                  fid1="USGS_HydroBASINS_lake_na_lev12.67061",
                  fid2="USGS_HydroBASINS_lake_na_lev12.67088",
                  )

    resp = client.get(

# Path: tests/common.py
# def get_output(doc):
#     """Copied from pywps/tests/test_execute.py.
#     TODO: make this helper method public in pywps."""
#     output = {}
#     for output_el in xpath_ns(doc, '/wps:ExecuteResponse'
#                                    '/wps:ProcessOutputs/wps:Output'):
#         [identifier_el] = xpath_ns(output_el, './ows:Identifier')
# 
#         lit_el = xpath_ns(output_el, './wps:Data/wps:LiteralData')
#         if lit_el != []:
#             output[identifier_el.text] = lit_el[0].text
# 
#         ref_el = xpath_ns(output_el, './wps:Reference')
#         if ref_el != []:
#             output[identifier_el.text] = ref_el[0].attrib['href']
# 
#         data_el = xpath_ns(output_el, './wps:Data/wps:ComplexData')
#         if data_el != []:
#             output[identifier_el.text] = data_el[0].text
# 
#     return output
# 
# CFG_FILE = os.path.join(TESTS_HOME, 'test.cfg')
# 
# Path: flyingpigeon/processes/wps_subset_wfs_polygon.py
# class SubsetWFSPolygonProcess(Process, Subsetter):
#     """Subset a NetCDF file using WFS geometry."""
# 
#     def __init__(self):
#         inputs = [
#             resource,
#             LiteralInput('typename',
#                          'TypeName',
#                          abstract='Name of the layer in GeoServer.',
#                          data_type='string',
#                          min_occurs=0,
#                          max_occurs=1),
#             LiteralInput('featureids',
#                          'Feature Ids',
#                          abstract='fid(s) of the feature in the layer.',
#                          data_type='string',
#                          min_occurs=0,
#                          max_occurs=1000),
#             LiteralInput('geoserver',
#                          'Geoserver',
#                          abstract=('Typically of the form '
#                                    'http://host:port/geoserver/wfs'),
#                          data_type='string',
#                          min_occurs=0),
#             start, end, variable]
# 
#         outputs = [output, metalink]
# 
#         super(SubsetWFSPolygonProcess, self).__init__(
#             self._handler,
#             identifier='subset-wfs-polygon',
#             title='Subset',
#             version='0.2',
#             abstract=('Return the data for which grid cells intersect the '
#                       'selected polygon for each input dataset as well as'
#                       'the time range selected.'),
#             inputs=inputs,
#             outputs=outputs,
#             status_supported=True,
#             store_supported=True,
#         )
# 
#     def _handler(self, request, response):
#         geoms, fids = self.parse_feature(request)
#         dr = self.parse_daterange(request)
# 
#         ml = MetaLink4('subset', workdir=self.workdir)
# 
#         for res in self.parse_resources(request):
#             variables = self.parse_variable(request, res)
#             prefix = Path(res).stem
#             # The name must not grow too long.
#             prefix += "_" + fids[0].split(".")[0]
# 
#             rd = ocgis.RequestDataset(res, variables)
# 
#             try:
#                 ops = ocgis.OcgOperations(
#                     dataset=rd, geom=geoms,
#                     agg_selection=True,
#                     spatial_operation='intersects', aggregate=False,
#                     time_range=dr, output_format='nc',
#                     interpolate_spatial_bounds=True,
#                     spatial_wrapping="wrap",
#                     prefix=prefix, dir_output=tempfile.mkdtemp(dir=self.workdir))
# 
#                 out = ops.execute()
# 
#                 mf = MetaFile(prefix, fmt=FORMATS.NETCDF)
#                 mf.file = out
#                 ml.append(mf)
# 
#             except ocgis.exc.ExtentError:
#                 continue
# 
#         response.outputs['output'].file = ml.files[0].file
#         response.outputs['metalink'].data = ml.xml
#         response.update_status("Completed", 100)
# 
#         return response


# Path: tests/test_wps_subset_wfs_polygon.py
from pywps import Service
from pywps.tests import client_for, assert_response_success
from .common import get_output, CFG_FILE
from flyingpigeon.processes.wps_subset_wfs_polygon import SubsetWFSPolygonProcess




def test_wps_subset():
    client = client_for(Service(processes=[SubsetWFSPolygonProcess()], cfgfiles=CFG_FILE))

    datainputs = "resource=@xlink:href={nc};" \
                 "typename={typename};" \
                 "geoserver={geoserver};" \
                 "featureids={fid1};" \
                 "featureids={fid2};"

    inputs = dict(nc="https://pavics.ouranos.ca/twitcher/ows/proxy/thredds/dodsC/birdhouse/nrcan"
                     "/nrcan_northamerica_monthly"
                     "/tasmax/nrcan_northamerica_monthly_2015_tasmax.nc",
                  typename="public:USGS_HydroBASINS_lake_na_lev12",
                  geoserver="https://pavics.ouranos.ca/geoserver/wfs",
                  fid1="USGS_HydroBASINS_lake_na_lev12.67061",
                  fid2="USGS_HydroBASINS_lake_na_lev12.67088",
                  )

    resp = client.get(

        "?service=WPS&request=Execute&version=1.0.0&identifier=subset-wfs-polygon&datainputs={}".format(