Ejemplo n.º 1
0
def post_mockreturn(method="POST", url=None, data=None, timeout=50, **kwargs):
    if data is not None:
        with open(data_path(DATA_FILES['async']), 'rb') as r:
            response = MockResponse(r.read(), **kwargs)
    else:
        with open(data_path(DATA_FILES['result']), 'rb') as r:
            response = MockResponse(r.read(), **kwargs)
    return response
Ejemplo n.º 2
0
def mockreturn(*args, method='GET', data={}, url='', **kwargs):
    if method == 'GET':
        molecule = url.split('cdmstab')[1].split('.')[0]
        with open(data_path(molecule + ".data"), 'rb') as fh:
            content = fh.read()
        return MockResponse(content=content)
    elif method == 'POST':
        molecule = dict(data)['Molecules']
        with open(data_path("post_response.html"), 'r') as fh:
            content = fh.read().format(replace=molecule).encode()
        return MockResponse(content=content)
Ejemplo n.º 3
0
def post_mockreturn(self, httpverb, url, data={}, **kwargs):
    if url == mpc.core.MPC.MPES_URL:
        prefix = data['TextArea'].replace(' ', '')
        suffix = '-'.join((data['c'], data['raty'], data['s']))
        filename = data_path('{}_ephemeris_{}.html'.format(prefix, suffix))
        content = open(filename, 'rb').read()
    else:
        content = None

    response = MockResponse(content, url=url)
    response.request = Request('POST', url, data=data).prepare()

    return response
Ejemplo n.º 4
0
def post_mockreturn(self,
                    method="POST",
                    url=None,
                    data=None,
                    timeout=10,
                    **kwargs):
    if "columnsconfig" in url:
        if "Mast.Catalogs.Tess.Cone" in data:
            service = "ticcolumns"
        elif "Mast.Catalogs.Dd.Cone" in data:
            service = "ddcolumns"
        else:
            service = 'columnsconfig'
    elif "catalogs.mast" in url:
        service = re.search(r"(\/api\/v\d*.\d*\/)(\w*)", url).group(2)
    else:
        service = re.search(r"service%22%3A%20%22([\w\.]*)%22", data).group(1)

    # Grabbing the Catalogs.all columns config calls
    if "Catalogs.All.Tic" in data or "Mast.Catalogs.Filtered.Tic.Position" in data:
        service = "ticcol_filtered"
    elif "Catalogs.All.DiskDetective" in data:
        service = "ddcol_filtered"

    # need to distiguish counts queries
    if ("Filtered" in service) and (re.search(r"COUNT_BIG%28%2A%29", data)):
        service = "Counts"
    filename = data_path(DATA_FILES[service])
    content = open(filename, 'rb').read()

    # returning as list because this is what the mast _request function does
    return [MockResponse(content)]
Ejemplo n.º 5
0
def get_mockreturn(method, url, params=None, timeout=10, cache=True, **kwargs):
    if 'SpecObjAll' in params['cmd']:
        filename = data_path(DATA_FILES['spectra_id'])
    else:
        filename = data_path(DATA_FILES['images_id'])
    content = open(filename, 'rb').read()
    return MockResponse(content, **kwargs)
Ejemplo n.º 6
0
def nonremote_request(self, request_type, url, **kwargs):

    filename = '3552_coordtype{}.dat'.format(kwargs['params']['-tcoor'])
    with open(data_path(filename), 'rb') as f:
        response = MockResponse(content=f.read(), url=url)

    return response
Ejemplo n.º 7
0
def post_mockreturn(method, url, data, timeout, files=None, **kwargs):
    if files is not None:
        content = open(data_path(DATA_FILES['gal_0_3']), 'rb').read()
        response = MockResponse(content, **kwargs)
    else:
        raise ValueError("Unsupported post request.")
    return response
Ejemplo n.º 8
0
def nonremote_request(self, url, **kwargs):

    targetname = kwargs['params']['sstr']

    with open(data_path(DATA_FILES[targetname]), 'rb') as f:
        response = MockResponse(content=f.read(), url=url)
    return response
Ejemplo n.º 9
0
def service_mockreturn(self,
                       method="POST",
                       url=None,
                       data=None,
                       timeout=10,
                       use_json=False,
                       **kwargs):
    if "panstarrs" in url:
        filename = data_path(DATA_FILES["panstarrs"])
    elif "tesscut" in url:
        if "sector" in url:
            filename = data_path(DATA_FILES['tess_sector'])
        else:
            filename = data_path(DATA_FILES['tess_cutout'])
    elif "zcut" in url:
        if "survey" in url:
            filename = data_path(DATA_FILES['z_survey'])
        else:
            filename = data_path(DATA_FILES['z_cutout_fit'])
    elif use_json and data['radius'] == 5:
        filename = data_path(DATA_FILES["mission_incorrect_results"])
    elif use_json:
        filename = data_path(DATA_FILES["mission_search_results"])
    content = open(filename, 'rb').read()
    return MockResponse(content)
Ejemplo n.º 10
0
def get_mockreturn(url, params=None, stream=False, timeout=10, **kwargs):
    if stream:
        filename = data_path(DATA_FILES['img'])
        return MockResponse(open(filename, 'rb').read(),
                            content_type='image/fits',
                            **kwargs)
    elif params['RA'] == 163.6136:
        filename = data_path(DATA_FILES['pos_t'])
    elif params['NAIFID'] == 2003226:
        filename = data_path(DATA_FILES['nid_t'])
    elif params['PID'] == 30080:
        filename = data_path(DATA_FILES['pid_t'])
    elif params['REQKEY'] == 21641216:
        filename = data_path(DATA_FILES['rqk_t'])
    else:
        raise ValueError("Query not pre-loaded.")

    content = open(filename, 'rb').read()
    return MockResponse(content, **kwargs)
Ejemplo n.º 11
0
def get_mockreturn(method, url, params=None, timeout=10, **kwargs):
    search_type = params.get('search_type')
    if search_type is not None:
        filename = data_path(DATA_FILES[search_type])
    elif 'imgdata' in url:
        filename = data_path(DATA_FILES['extract_urls'])
    else:
        filename = data_path(DATA_FILES['object'])
    content = open(filename, "rb").read()
    return MockResponse(content, **kwargs)
Ejemplo n.º 12
0
def get_mockreturn(self, httpverb, url, params={}, auth=None, **kwargs):
    if mpc.core.MPC.MPC_URL in url:
        content = open(data_path('comet_object_C2012S1.json'), 'rb').read()
    elif url == mpc.core.MPC.OBSERVATORY_CODES_URL:
        content = open(data_path('ObsCodes.html'), 'rb').read()
    elif mpc.core.MPC.MPCOBS_URL in url:
        content = open(data_path('mpc_obs.dat'), 'rb').read()
    else:
        content = None

    return MockResponse(content, url=url, auth=auth)
Ejemplo n.º 13
0
def get_mockreturn(self,
                   method,
                   url,
                   data=None,
                   timeout=10,
                   files=None,
                   params=None,
                   headers=None,
                   **kwargs):
    filename = data_path(DATA_FILES[data])
    content = open(filename, 'rb').read()
    return MockResponse(content)
Ejemplo n.º 14
0
def tesscut_get_mockreturn(method="GET",
                           url=None,
                           data=None,
                           timeout=10,
                           **kwargs):
    if "sector" in url:
        filename = data_path(DATA_FILES['tess_sector'])
    else:
        filename = data_path(DATA_FILES['tess_cutout'])

    content = open(filename, 'rb').read()
    return MockResponse(content)
Ejemplo n.º 15
0
def test_parse_result(capsys):
    content = open(data_path(DATA_FILES['error']), 'rb').read()
    response = MockResponse(content)
    with pytest.raises(RemoteServiceError) as exinfo:
        ned.core.Ned._parse_result(response)
    if hasattr(exinfo.value, 'message'):
        assert exinfo.value.message == ("The remote service returned the "
                                        "following error message.\nERROR:  "
                                        "No note found.")
    else:
        assert exinfo.value.args == ("The remote service returned the "
                                     "following error message.\nERROR:  "
                                     "No note found.", )
Ejemplo n.º 16
0
def post_mockreturn(self,
                    method,
                    url,
                    data=None,
                    timeout=10,
                    files=None,
                    params=None,
                    headers=None,
                    **kwargs):
    if method != 'POST':
        raise ValueError("A 'post request' was made with method != POST")
    filename = data_path(SPLAT_DATA)
    content = open(filename, "rb").read()
    return MockResponse(content, **kwargs)
Ejemplo n.º 17
0
def nonremote_request(self, request_type, url, **kwargs):
    if kwargs['params']['COMMAND'] == '"Ceres"':
        # pick DATA_FILE based on query type and time request
        query_type = {
            'OBSERVER': 'ephemerides',
            'ELEMENTS': 'elements',
            'VECTORS': 'vectors'
        }[kwargs['params']['EPHEM_TYPE']]

        if 'TLIST' in kwargs['params']:
            query_type += '-single'
        elif ('START_TIME' in kwargs['params']
              and 'STOP_TIME' in kwargs['params']
              and 'STEP_SIZE' in kwargs['params']):
            query_type += '-range'

        with open(data_path(DATA_FILES[query_type]), 'rb') as f:
            response = MockResponse(content=f.read(), url=url)
    else:
        with open(data_path(DATA_FILES[kwargs['params']['COMMAND']]),
                  'rb') as f:
            response = MockResponse(content=f.read(), url=url)

    return response
Ejemplo n.º 18
0
def get_mockreturn(method, url, params=None, timeout=10, cache=None, **kwargs):
    if ('WavelengthEff_min' in params
            and (params['WavelengthEff_min'] == TEST_LAMBDA
                 and params['WavelengthEff_max'] == TEST_LAMBDA + 100)):
        filename = data_path(DATA_FILES['filter_index'])
    elif 'ID' in params and params['ID'] == TEST_FILTER_ID:
        filename = data_path(DATA_FILES['filter_index'])
    elif 'Facility' in params and (params['Facility'] == TEST_FACILITY and
                                   params['Instrument'] == TEST_INSTRUMENT):
        filename = data_path(DATA_FILES['filter_list'])
    else:
        raise NotImplementedError("Test type not implemented")

    content = open(filename, 'rb').read()
    return MockResponse(content, **kwargs)
Ejemplo n.º 19
0
def get_mockreturn(method='GET', url='default_url',
                   params=None, timeout=10, **kwargs):
    if "Image" in url:
        filename = DATA_FILES["image_results"]
        url = "Image_URL"
    elif "SQL" in url:
        filename = DATA_FILES["vo_results"]
        url = "SQL_URL"
    elif "error" in url:
        filename = DATA_FILES["error"]
        url = "error.html"
    else:
        raise ValueError("Mismatch: no test made for specified URL")

    content = open(data_path(filename), "rb").read()
    return MockResponse(content=content, url=url, **kwargs)
Ejemplo n.º 20
0
def get_mockreturn(method="GET",
                   url=None,
                   data=None,
                   timeout=60,
                   cache=True,
                   **kwargs):
    if ((("GW170817" in data) or ("catalog" in data)) and ("csv" in data)):
        file_key = 'phot_csv'
    elif ((("GW170817" in data) or ("catalog" in data)) and ("json" in data)):
        file_key = 'phot_json'
    elif "SN2014J" in data:
        file_key = 'single_spec'
    else:
        file_key = 'multi_spec'
    content = open(data_path(DATA_FILES[file_key]), 'rb').read()
    response = MockResponse(content, **kwargs)
    return response
Ejemplo n.º 21
0
def post_mockreturn(self,
                    method,
                    url,
                    data=None,
                    timeout=10,
                    files=None,
                    params=None,
                    headers=None,
                    **kwargs):
    if method != 'POST':
        raise ValueError("A 'post request' was made with method != POST")

    if params['PROTOCOL'] == "VOTable-XML":
        filename = data_path(DATA_FILES['votable'])
    elif params['PROTOCOL'] == "HTML" and params['QUERYTYPE'] == 'ARCHIVE':
        filename = data_path(DATA_FILES['archive'])
    else:
        raise NotImplementedError("Test type not implemented")

    content = open(filename, "rb").read()
    return MockResponse(content, **kwargs)
Ejemplo n.º 22
0
def mock_get(self, method, url, *args, **kwargs):  # pragma: nocover
    assert url == conf.url_api

    params = kwargs.get("params", None)
    assert params is not None

    try:
        with open(RESPONSE_FILE, "r") as f:
            responses = json.load(f)
    except FileNotFoundError:
        responses = {}

    # Work out where the expected response is saved
    table = params["table"]
    key = urlencode(sorted(params.items()))
    try:
        index = responses.get(table, []).index(key)
    except ValueError:
        index = -1

    # If the NASA_EXOPLANET_ARCHIVE_GENERATE_RESPONSES environment variable is set, we make a
    # remote request if necessary. Otherwise we throw a ValueError.
    if index < 0:
        if "NASA_EXOPLANET_ARCHIVE_GENERATE_RESPONSES" not in os.environ:
            raise ValueError("unexpected request")
        with requests.Session() as session:
            resp = session.old_request(method, url, params=params)
        responses[table] = responses.get(table, [])
        responses[table].append(key)
        index = len(responses[table]) - 1
        with open(os.path.join(TEST_DATA, "{0}_expect_{1}.txt".format(table, index)), "w") as f:
            f.write(resp.text)
        with open(RESPONSE_FILE, "w") as f:
            json.dump(responses, f, sort_keys=True, indent=2)

    with open(os.path.join(TEST_DATA, "{0}_expect_{1}.txt".format(table, index)), "r") as f:
        data = f.read()

    return MockResponse(data.encode("utf-8"))
Ejemplo n.º 23
0
def get_mockreturn(method, url, params=None, timeout=10, **kwargs):
    filename = data_path(DATA_FILES['lines'])
    content = open(filename, 'rb').read()
    return MockResponse(content, **kwargs)
Ejemplo n.º 24
0
def post_mockreturn(method, url, params=None, timeout=0, **kwargs):
    filename = data_path(DATA_FILES['images_id'])
    content = open(filename, 'rb').read()
    return MockResponse(content)
Ejemplo n.º 25
0
def nonremote_request(self, url, **kwargs):

    with open(data_path(DATA_FILE), 'rb') as f:
        response = MockResponse(content=f.read(), url=url)
    return response
Ejemplo n.º 26
0
def resolver_mockreturn(*args, **kwargs):
    filename = data_path(DATA_FILES["Mast.Name.Lookup"])
    content = open(filename, 'rb').read()
    return MockResponse(content)
Ejemplo n.º 27
0
def eso_request(request_type, url, **kwargs):
    with open(data_path(DATA_FILES[request_type][url]), 'rb') as f:
        response = MockResponse(content=f.read(), url=url)
    return response
Ejemplo n.º 28
0
def post_mockreturn(method, url, data, timeout, **kwargs):
    filename = data_path(DATA_FILES['image'])
    content = open(filename, 'rb').read()
    return MockResponse(content, **kwargs)
Ejemplo n.º 29
0
def get_mockreturn(method, url, params=None, timeout=10, cache=False, **kwargs):
    filename = data_path(DATA_FILES[params['spatial']])
    content = open(filename, 'rb').read()
    return MockResponse(content, **kwargs)
Ejemplo n.º 30
0
def nonremote_request(self, request_type, url, **kwargs):
    # kwargs are ignored in this case, but they don't have to be
    # (you could use them to define which data file to read)
    with open(data_path(DATA_FILES[request_type][url]), 'rb') as f:
        response = MockResponse(content=f.read(), url=url)
    return response