def test_render_a_report_from_an_existing_template_id(
         self, csdk, requests_mock):
     template_id = "0545253258577a632a99065f0572720225f5165cc43db9515e9cef0e17b40114"
     expected_report_name = "DGW298DWIU28939DOWIJ.odt"
     # Request to post the render the report
     render_id = "MTAuMjAuMjEuMTAgICAg01E98H4R7PMC2H6XSE5Z6J8XYQ.odt"
     requests_mock.post(csdk._api_url + "/render/" + template_id,
                        json={
                            'success': True,
                            'data': {
                                'renderId': render_id,
                                'inputFileExtension': 'odt'
                            }
                        })
     # Request to get the report
     filename = os.path.join(os.path.dirname(__file__), 'template.test.odt')
     file_data = open(filename, "rb")
     requests_mock.get(csdk._api_url + "/render/" + render_id,
                       body=file_data,
                       headers={
                           'content-disposition':
                           'filename="' + expected_report_name + '"'
                       })
     # Call the function
     resp, unique_report_name = csdk.render(
         template_id, {"data": {
             "firstname": "john",
             "lastname": "wick"
         }})
     file_data = open(filename, "rb")
     assert file_data.read() == resp
     assert expected_report_name == unique_report_name
def test_rest_api_expected_status_with_error(requests_mock):
    conn = RestApiConnection(API_URL)
    requests_mock.get("https://oeo.test/bar",
                      status_code=406,
                      json={
                          "code": "NoBar",
                          "message": "no bar please"
                      })
    # First check for API error by default
    with pytest.raises(OpenEoApiError, match=r"\[406\] NoBar: no bar please"):
        conn.get("/bar", expected_status=200)
    with pytest.raises(OpenEoApiError, match=r"\[406\] NoBar: no bar please"):
        conn.get("/bar", expected_status=[201, 202])
    # Don't fail when an error status is actually expected
    conn.get("/bar", expected_status=406)
    conn.get("/bar", expected_status=[406, 407])
    with pytest.raises(OpenEoApiError, match=r"\[406\] NoBar: no bar please"):
        conn.get("/bar", expected_status=[401, 402])

    # Don't check for error, just status
    conn.get("/bar", check_error=False, expected_status=406)
    with pytest.raises(
            OpenEoClientException,
            match=r"Got status code 406 for `GET /bar` \(expected \[302\]\)"):
        conn.get("/bar", check_error=False, expected_status=302)
    with pytest.raises(
            OpenEoClientException,
            match=
            r"Got status code 406 for `GET /bar` \(expected \[302, 303\]\)"):
        conn.get("/bar", check_error=False, expected_status=[302, 303])
def test_get_udp(requests_mock):
    requests_mock.get(API_URL, json={"api_version": "1.0.0"})
    conn = Connection(API_URL)

    udp = conn.user_defined_process('evi')

    assert udp.user_defined_process_id == 'evi'
def test_authenticate_oidc_100_multiple_wrong_id(requests_mock):
    requests_mock.get(API_URL, json={"api_version": "1.0.0"})
    client_id = "myclient"
    requests_mock.get(API_URL + 'credentials/oidc',
                      json={
                          "providers": [
                              {
                                  "id": "fauth",
                                  "issuer": "https://fauth.test",
                                  "title": "Foo Auth",
                                  "scopes": ["openid", "w"]
                              },
                              {
                                  "id": "bauth",
                                  "issuer": "https://bauth.test",
                                  "title": "Bar Auth",
                                  "scopes": ["openid", "w"]
                              },
                          ]
                      })

    # With all this set up, kick off the openid connect flow
    conn = Connection(API_URL)
    assert isinstance(conn.auth, NullAuth)
    match = r"'lol' not available\. Should be one of \[('fauth', 'bauth'|'bauth', 'fauth')\]\."
    with pytest.raises(OpenEoClientException, match=match):
        conn.authenticate_OIDC(client_id=client_id,
                               provider_id="lol",
                               webbrowser_open=pytest.fail)
def test_webhook_decorator(app, requests_mock, slack_mock):
    with app.app_context():
        url = 'http://example.com/web/hook'
        app.config['API_WEBHOOK_URL'] = url
        requests_mock.get(url, json={'it': 'worked'})

        @api.route('/test_webhook', methods=['GET'])
        @notify_webhook
        def successful_function():
            return "blah blah", 201

        assert requests_mock.call_count == 0
        successful_function()
        assert requests_mock.call_count == 1
        assert slack_mock.files_upload.call_count == 0

        @api.route('/test_webhook_fail', methods=['GET'])
        def unsuccessful_function():
            return "blah blah", 500

        assert requests_mock.call_count == 1
        unsuccessful_function()
        # webhook should not be called because the operation failed
        assert requests_mock.call_count == 1
        assert slack_mock.files_upload.call_count == 0
def test_load_collection_arguments_100(requests_mock):
    requests_mock.get(API_URL, json={"api_version": "1.0.0"})
    conn = Connection(API_URL)
    requests_mock.get(API_URL + "collections/FOO",
                      json={
                          "summaries": {
                              "eo:bands": [{
                                  "name": "red"
                              }, {
                                  "name": "green"
                              }, {
                                  "name": "blue"
                              }]
                          }
                      })
    spatial_extent = {"west": 1, "south": 2, "east": 3, "north": 4}
    temporal_extent = ["2019-01-01", "2019-01-22"]
    im = conn.load_collection("FOO",
                              spatial_extent=spatial_extent,
                              temporal_extent=temporal_extent,
                              bands=["red", "green"])
    assert im._pg.process_id == "load_collection"
    assert im._pg.arguments == {
        "id": "FOO",
        "spatial_extent": spatial_extent,
        "temporal_extent": temporal_extent,
        "bands": ["red", "green"]
    }
예제 #7
0
파일: fixtures.py 프로젝트: up42/up42-py
def order_mock(auth_mock, requests_mock):

    # order info
    url_order_info = (
        f"{auth_mock._endpoint()}/workspaces/{auth_mock.workspace_id}/orders/{ORDER_ID}"
    )
    requests_mock.get(url=url_order_info, json=JSON_ORDER)

    # metadata
    requests_mock.get(
        url=
        f"{auth_mock._endpoint()}/workspaces/{auth_mock.workspace_id}/orders/{ORDER_ID}/metadata",
        json={
            "data": {
                "id": ORDER_ID,
                "userId": "1094497b-11d8-4fb8-9d6a-5e24a88aa825",
                "customerReference": "158e8ca9-c5e9-4705-8f44-7aefee1d33ff",
                "sqKmArea": 0.1,
                "createdAt": "2021-01-18T16:18:19.395198Z",
                "updatedAt": "2021-01-18T16:18:19.395198Z",
            },
            "error": None,
        },
    )

    order = Order(auth=auth_mock, order_id=ORDER_ID)

    return order
예제 #8
0
def test_get_starship(requests_mock, cache):
    requests_mock.get(
        'https://swapi.co/api/starships/9/',
        text='{'
        '"name": "Death Star",'
        '"model": "DS-1 Orbital Battle Station",'
        '"manufacturer": "Imperial Department of Military Research, Sienar Fleet Systems",'
        '"cost_in_credits": "1000000000000",'
        '"length": "120000",'
        '"max_atmosphering_speed": "n/a",'
        '"crew": "342953",'
        '"passengers": "843342",'
        '"cargo_capacity": "1000000000000",'
        '"consumables": "3 years",'
        '"hyperdrive_rating": "4.0",'
        '"MGLT": "10",'
        '"starship_class": "Deep Space Mobile Battlestation",'
        '"pilots": [],'
        '"films": ['
        '"https://swapi.co/api/films/1/"'
        '],'
        '"created": "2014-12-10T16:36:50.509000Z",'
        '"edited": "2014-12-22T17:35:44.452589Z",'
        '"url": "https://swapi.co/api/starships/9/"'
        '}')

    expected_starship = Starship(
        '9', 'DS-1 Orbital Battle Station', 'Deep Space Mobile Battlestation',
        '4.0', '1000000000000',
        'Imperial Department of Military Research, Sienar Fleet Systems')

    assert get_starship('9', cache) == expected_starship
    assert cache.starships == OrderedDict({'9': expected_starship})
예제 #9
0
def test_get_blacklist_query_and_filter(requests_mock):
    """
    Given:
        - The `filter` arg set to `ip`
        - The `query` arg set to `8.8.*.8`
        - API response with a URL and IP

    When:
        - Running the get-blacklist command

    Then:
        - Ensure only the IP is returned
    """
    import Zscaler
    api_res = {
        'blacklistUrls': [
            'demisto.com',
            '8.8.8.8',
        ],
    }
    requests_mock.get(
        'http://cloud/api/v1/security/advanced',
        json=api_res,
    )
    args = {
        'filter': 'ip',
        'query': '8.8.*.8',
    }
    cmd_res = Zscaler.get_blacklist_command(args)
    assert cmd_res['Contents'] == [api_res['blacklistUrls'][1]]
예제 #10
0
파일: fixtures.py 프로젝트: up42/up42-py
def auth_mock(requests_mock):
    # token for initial authentication
    url_get_token = f"https://{PROJECT_ID}:{PROJECT_APIKEY}@api.up42.com/oauth/token"
    json_get_token = {"data": {"accessToken": TOKEN}}
    requests_mock.post(
        url=url_get_token,
        json=json_get_token,
    )

    url_get_workspace = f"https://api.up42.com/projects/{PROJECT_ID}"
    json_get_workspace = {"data": {"workspaceId": WORKSPACE_ID}}
    requests_mock.get(
        url=url_get_workspace,
        json=json_get_workspace,
    )
    auth = Auth(
        project_id=PROJECT_ID,
        project_api_key=PROJECT_APIKEY,
        authenticate=True,
        retry=False,
    )

    # get_blocks
    url_get_blocks = f"{auth._endpoint()}/blocks"
    requests_mock.get(
        url=url_get_blocks,
        json=JSON_BLOCKS,
    )

    return auth
예제 #11
0
 def test_watchlist_image(self, requests_mock, generate_spotter, sample_adsbx_json):
     """Test that image path is assigned from watchlist"""
     spots = generate_spotter
     requests_mock.get(spots.url, json=sample_adsbx_json, status_code=200)
     spots.check_spots()
     for i in [p['img'] for p in spots.spot_queue if p['type'] == 'P28A']:
         assert i == 'test.png'
예제 #12
0
def test_get_blacklist_query(requests_mock):
    """
    Given:
        - The `query` arg set to `demisto`
        - API response with a URL and IP

    When:
        - Running the get-blacklist command

    Then:
        - Ensure only the URL (which contains `demisto`) is returned
    """
    import Zscaler
    api_res = {
        'blacklistUrls': [
            'demisto.com',
            '8.8.8.8',
        ],
    }
    requests_mock.get(
        'http://cloud/api/v1/security/advanced',
        json=api_res,
    )
    args = {
        'query': 'demisto',
    }
    cmd_res = Zscaler.get_blacklist_command(args)
    assert cmd_res['Contents'] == [api_res['blacklistUrls'][0]]
def test_request_429(requests_mock):
    requests_mock.get(BASE_URL, status_code=429)
    req = RequestInterface()
    
    req_result =  req.request_exchange_api()
    with pytest.raises(RateLimitException):
        req.check_response(req_result)
예제 #14
0
    def test_participant_by_ticket_id(self, requests_mock):
        url = "https://api.sympla.com.br/public/v3/events/856842/participants/102345"
        json = {
            "data": {
                "id": 102345,
                "order_id": "BC1BA1",
                "first_name": "Joaquim",
                "last_name": "Lopes",
                "email": "*****@*****.**",
                "ticket_number": "QHWA-1Q-3G0J",
                "ticket_num_qr_code": "QHWA1Q3G0J",
                "ticket_name": "VIP",
                "pdv_user": "******",
                "ticket_sale_price": 123.5,
                "checkin": {
                    "id": 1,
                    "check_in": True,
                    "check_in_date": "2018-09-10T10:21:10-03:00",
                },
                "custom_form": {
                    "id": 1,
                    "name": "CPF",
                    "value": "142.536.789-55"
                },
            }
        }
        requests_mock.get(url=url, json=json)

        participant = self.sympla.participant_by_ticket_id(
            event_id=856842, participant_id=102345)
        self.assertEqual(participant, json)
예제 #15
0
    def test_event_order_by_identifier(self, requests_mock):
        url = "https://api.sympla.com.br/public/v3/events/856842/orders/Q080KEE"
        json = {
            "data": {
                "id": "Q080KEE",
                "event_id": 10203040,
                "order_date": "2018-10-21 10:12:23",
                "order_status": "A",
                "updated_date": "2018-10-10 23:34:21",
                "discount_code": "10,00% - desconto10",
                "transaction_type": "CREDIT_CARD",
                "order_total_sale_price": 23.34,
                "buyer_first_name": "Joaquim",
                "buyer_last_name": "Lopes",
                "buyer_email": "*****@*****.**",
                "invoice_info": {
                    "doc_type": "CPF",
                    "doc_number": "142.536.789-55",
                    "client_name": "Joaquim",
                    "address_zip_code": "31112-000",
                    "address_street": "Rua Fernandes Tourinho",
                    "address_street_number": "147",
                    "address_street2": "10º Andar",
                    "address_neighborhood": "Funcionários",
                    "address_city": "Belo Horizonte",
                    "address_state": "MG",
                    "mei": False,
                },
            }
        }
        requests_mock.get(url=url, json=json)

        order = self.sympla.order_by_identifier(event_id=856842,
                                                order_id="Q080KEE")
        self.assertEqual(order, json)
예제 #16
0
def test_search_indicator_command__no_indicator(requests_mock, ioc_type,
                                                ioc_val):
    """
    Given:
        - Indicator not exist in AutoFocus

    When:
        - Run the reputation command

    Then:
        - Validate the expected result is return with detailed information
    """

    # prepare
    from AutofocusV2 import search_url_command, search_ip_command, search_domain_command, search_file_command
    ioc_type_to_command = {
        'url': search_url_command,
        'domain': search_domain_command,
        'ipv4_address': search_ip_command,
        'filehash': search_file_command,
    }
    no_indicator_response = {'tags': []}

    requests_mock.get(
        f'https://autofocus.paloaltonetworks.com/api/v1.0/tic?indicatorType={ioc_type}'
        f'&indicatorValue={ioc_val}&includeTags=true',
        json=no_indicator_response)

    # run
    result = ioc_type_to_command[ioc_type](ioc_val, 'B - Usually reliable',
                                           True)

    # validate
    assert f'{ioc_val} was not found in AutoFocus' in result[0].readable_output
예제 #17
0
 def test_public_curriculum_with_kwargs(self, requests_mock):
     url = "https://www.udemy.com/api-2.0/courses/12345/public-curriculum-items/"
     kwargs = {"page": 1, "page_size": 1}
     requests_mock.get(url, json=PUBLIC_CURRICULUM_WITH_PARAMS)
     self.assertEqual(
         self.udemy.public_curriculum(12345, **kwargs), PUBLIC_CURRICULUM_WITH_PARAMS
     )
예제 #18
0
파일: test_core.py 프로젝트: epopeia/lamper
def test_get_callapi(requests_mock):
    event = {
        'resource': '/example',
        'httpMethod': 'GET',
        'pathParameters': {
            'customer_id': '1',
            'name': 'EPOPEIA'
        }
    }

    class ExamplePathParam(Schema):
        customer_id = fields.Str()
        name = fields.Str()

    class ExampleResponse(Schema):
        customer = fields.Str()
        name = fields.Str()

    api_url = 'http://echo.jsontest.com/customer/{customer_id}/name/{name}'
    requests_mock.get(api_url.replace('{customer_id}',
                                      '1').replace('{name}', 'EPOPEIA'),
                      json={
                          "customer": "1",
                          "name": "EPOPEIA"
                      })
    result = core.callapi(path_param_schema=ExamplePathParam,
                          response_schema=ExampleResponse,
                          http_method=core.HttpMethod.GET,
                          api_url=api_url,
                          event=event)

    assert result.get('name') == "EPOPEIA"
    assert result.get('customer') == "1"
예제 #19
0
def test_feed_main_test_module(mocker, requests_mock):
    """
    Given
    - Parameters (url, ignore_regex, feed_url_to_config and tags) to configure a feed.

    When
    - Running test-module (clicking on Test).

    Then
    - Ensure 'ok' is returned.
    """
    feed_url = 'https://www.spamhaus.org/drop/asndrop.txt'
    indicator_type = 'ASN'
    tags = 'tag1,tag2'
    tlp_color = 'AMBER'
    feed_url_to_config = {
        'https://www.spamhaus.org/drop/asndrop.txt': {
            'indicator_type': indicator_type,
            'indicator': {
                'regex': '^AS[0-9]+'
            },
            'fields': [
                {
                    'asndrop_country': {
                        'regex': r'^.*;\W([a-zA-Z]+)\W+',
                        'transform': r'\1'
                    }
                },
                {
                    'asndrop_org': {
                        'regex': r'^.*\|\W+(.*)',
                        'transform': r'\1'
                    }
                }
            ]
        }
    }

    mocker.patch.object(
        demisto, 'params',
        return_value={
            'url': feed_url,
            'ignore_regex': '^;.*',
            'feed_url_to_config': feed_url_to_config,
            'feedTags': tags,
            'tlp_color': tlp_color
        }
    )
    mocker.patch.object(demisto, 'command', return_value='test-module')
    mocker.patch.object(demisto, 'results')

    with open('test_data/asn_ranges.txt') as asn_ranges_txt:
        asn_ranges = asn_ranges_txt.read().encode('utf8')

    requests_mock.get(feed_url, content=asn_ranges)
    feed_main('great_feed_name')

    assert demisto.results.call_count == 1
    results = demisto.results.call_args[0][0]
    assert results['HumanReadable'] == 'ok'
예제 #20
0
파일: fixtures.py 프로젝트: up42/up42-py
def jobs_mock(auth_mock, requests_mock):
    url_job_info = (
        f"{auth_mock._endpoint()}/projects/{auth_mock.project_id}/jobs/{JOB_ID}"
    )
    requests_mock.get(
        url=url_job_info,
        json={
            "data": {
                "xyz": 789,
                "mode": "DEFAULT"
            },
            "error": {}
        },
    )

    job1 = Job(auth=auth_mock, project_id=auth_mock.project_id, job_id=JOB_ID)

    url_job_info = (
        f"{auth_mock._endpoint()}/projects/{auth_mock.project_id}/jobs/{JOB_ID_2}"
    )
    requests_mock.get(url=url_job_info,
                      json={
                          "data": {
                              "xyz": 789
                          },
                          "error": {}
                      })

    job2 = Job(auth=auth_mock,
               project_id=auth_mock.project_id,
               job_id=JOB_ID_2)
    return [job1, job2]
예제 #21
0
    def _set_scrapinghub_requests_mock(pending_count=1,
                                       running_count=1,
                                       job_id='123/1/2',
                                       load_content=None):
        if load_content is None:
            load_content = sample_category_data_raw

        requests_mock.get(
            'https://storage.scrapinghub.com/ids/414324/spider/wb', text='1')
        requests_mock.get(
            'https://storage.scrapinghub.com/jobq/414324/count?state=pending&spider=wb',
            text=f'{pending_count}')
        requests_mock.get(
            'https://storage.scrapinghub.com/jobq/414324/count?state=running&spider=wb',
            text=f'{running_count}')
        requests_mock.post('https://app.scrapinghub.com/api/run.json',
                           json={
                               'status': 'ok',
                               'jobid': f'{job_id}'
                           })
        requests_mock.get(
            f'https://storage.scrapinghub.com/items/{job_id}?meta=_key',
            content=load_content,
            headers={'Content-Type': 'application/x-jsonlines; charset=UTF-8'})
        requests_mock.get(
            f'https://storage.scrapinghub.com/jobs/{job_id}/state',
            text='"finished"')
예제 #22
0
파일: bat_test.py 프로젝트: benderl/openWB
def test_update(monkeypatch, requests_mock: requests_mock.Mocker,
                mock_ramdisk):
    component_config = FroniusBatSetup()
    device_config = FroniusConfiguration()
    device_config.ip_address = SAMPLE_IP
    assert component_config.configuration.meter_id == 0
    battery = bat.FroniusBat(
        0, component_config,
        dataclass_from_dict(FroniusConfiguration, device_config))

    mock = Mock(return_value=None)
    monkeypatch.setattr(LoggingValueStore, "set", mock)
    monkeypatch.setattr(SimCountLegacy, "sim_count", Mock(return_value=[0, 0]))
    requests_mock.get("http://" + SAMPLE_IP +
                      "/solar_api/v1/GetPowerFlowRealtimeData.fcgi",
                      json=json)

    battery.update()

    # mock_valuestore.assert_called_once()
    battery_state = mock.call_args[0][0]
    assert battery_state.exported == 0
    assert battery_state.imported == 0
    assert battery_state.power == -2288
    assert battery_state.soc == 60.8
예제 #23
0
def test_command_line_interface(requests_mock: requests_mock) -> None:
    """Test the CLI."""
    runner = CliRunner()
    result = runner.invoke(cli.cli)
    assert result.exit_code == 0
    assert "Usage: cli" in result.output
    help_result = runner.invoke(cli.cli, ["--help"])
    assert help_result.exit_code == 0
    assert "Usage: cli" in help_result.output
    help_result = runner.invoke(cli.cli, ["--version"])
    assert help_result.exit_code == 0
    assert __version__ in help_result.output
    requests_mock.get(
        "http://localhost:19120/api/v1/trees",
        text=json.dumps([{
            "name": "main",
            "type": "BRANCH",
            "hash": "1234567890abcdef"
        }]),
    )
    help_result = runner.invoke(cli.cli, ["list-references"])
    assert help_result.exit_code == 0
    references = ReferenceSchema().loads(help_result.output, many=True)
    assert len(references) == 1
    assert references[0].name == "main"
    assert references[0].kind == "BRANCH"
    assert references[0].hash_ == "1234567890abcdef"
예제 #24
0
def test_get_vehicle(requests_mock, cache):
    requests_mock.get('https://swapi.co/api/vehicles/4/',
                      text='{'
                      '"name": "Sand Crawler",'
                      '"model": "Digger Crawler",'
                      '"manufacturer": "Corellia Mining Corporation",'
                      '"cost_in_credits": "150000",'
                      '"length": "36.8",'
                      '"max_atmosphering_speed": "30",'
                      '"crew": "46",'
                      '"passengers": "30",'
                      '"cargo_capacity": "50000",'
                      '"consumables": "2 months",'
                      '"vehicle_class": "wheeled",'
                      '"pilots": [],'
                      '"films": ['
                      '"https://swapi.co/api/films/5/",'
                      '"https://swapi.co/api/films/1/"'
                      '],'
                      '"created": "2014-12-10T15:36:25.724000Z",'
                      '"edited": "2014-12-22T18:21:15.523587Z",'
                      '"url": "https://swapi.co/api/vehicles/4/"'
                      '}')

    expected_vehicle = Vehicle('4', 'Sand Crawler', 'Digger Crawler', '150000')

    assert get_vehicle('4', cache) == expected_vehicle
    assert cache.vehicles == OrderedDict({'4': expected_vehicle})
예제 #25
0
    def test_get_assembly_report_mock(
            self,
            tmpdir,  # pytest fixture (py.path.local)
            logged_client: TeselaGenClient,
            requests_mock,  # noqa: F811
    ):
        """Checks report can be downloaded.

        TODO: Requires a specific ID! A new endpoint for listing IDS should be implemented!
        """
        TEST_REPORT_ID = 1023

        # Create Mock
        api_url_base = f'{logged_client.host_url}/design/cli-api'
        url = f'{api_url_base}{logged_client.design.URL_GET_ASSEMBLY_REPORT}/{TEST_REPORT_ID}'

        requests_mock.get(url, content=b'estoesunarchivobinario')

        # Create temporary folder
        local_filename = tmpdir.mkdir('assembly_report').join(
            f'report_{TEST_REPORT_ID}.zip')

        # Download report and make assertions
        report_filepath = logged_client.design.get_assembly_report(
            report_id=TEST_REPORT_ID,
            local_filename=local_filename,
        )

        assert Path(report_filepath).is_file()
def test_load_collection_arguments_040(requests_mock):
    requests_mock.get(API_URL, json={"api_version": "0.4.0"})
    conn = Connection(API_URL)
    requests_mock.get(API_URL + "collections/FOO",
                      json={
                          "properties": {
                              "eo:bands": [{
                                  "name": "red"
                              }, {
                                  "name": "green"
                              }, {
                                  "name": "blue"
                              }]
                          }
                      })
    spatial_extent = {"west": 1, "south": 2, "east": 3, "north": 4}
    temporal_extent = ["2019-01-01", "2019-01-22"]
    im = conn.load_collection("FOO",
                              spatial_extent=spatial_extent,
                              temporal_extent=temporal_extent,
                              bands=["red", "green"])
    node = im.graph[im.node_id]
    assert node["process_id"] == "load_collection"
    assert node["arguments"] == {
        "id": "FOO",
        "spatial_extent": spatial_extent,
        "temporal_extent": temporal_extent,
        "bands": ["red", "green"]
    }
 def test_render_from_a_template_already_uploaded(self, csdk,
                                                  requests_mock):
     file_name = "template.test.html"
     file_path = os.path.join(os.path.dirname(__file__), file_name)
     template_id = "75256dd5c260cdf039ae807d3a007e78791e2d8963ea1aa6aff87ba03074df7f"
     render_id = "MTAuMjAuMjEuMTAgICAg01E98H4R7PMC2H6XSE5Z6J8XYQ.odt"
     expected_report_name = "DGW298DWIU28939DOWIJ2322EWFEW.odt"
     # mock render report
     requests_mock.post(csdk._api_url + "/render/" + template_id,
                        json={
                            'success': True,
                            'data': {
                                'renderId': render_id,
                                'inputFileExtension': 'html'
                            }
                        })
     # mock request to get the report
     file_data = open(file_path, "rb")
     requests_mock.get(csdk._api_url + "/render/" + render_id,
                       body=file_data,
                       headers={
                           'content-disposition':
                           'filename="' + expected_report_name + '"'
                       })
     # Call the function
     resp, unique_report_name = csdk.render(
         file_path, {"data": {
             "firstname": "john",
             "lastname": "wick"
         }})
     file_data = open(file_path, "rb")
     assert file_data.read() == resp
     assert unique_report_name == expected_report_name
def test_create_public_udp(requests_mock):
    requests_mock.get(API_URL, json={"api_version": "1.0.0"})
    requests_mock.get(API_URL + "processes",
                      json={"processes": [{
                          "id": "add"
                      }]})
    conn = Connection(API_URL)

    new_udp = load_json_resource("data/1.0.0/udp_details.json")

    def check_body(request):
        body = request.json()
        assert body['process_graph'] == new_udp['process_graph']
        assert body['parameters'] == new_udp['parameters']
        assert body['public']
        return True

    adapter = requests_mock.put(API_URL + "process_graphs/evi",
                                additional_matcher=check_body)

    conn.save_user_defined_process(user_defined_process_id='evi',
                                   process_graph=new_udp['process_graph'],
                                   parameters=new_udp['parameters'],
                                   public=True)

    assert adapter.called
def test_authenticate_oidc_100_single_implicit(requests_mock):
    requests_mock.get(API_URL, json={"api_version": "1.0.0"})
    client_id = "myclient"
    requests_mock.get(API_URL + 'credentials/oidc',
                      json={
                          "providers": [{
                              "id": "fauth",
                              "issuer": "https://fauth.test",
                              "title": "Foo Auth",
                              "scopes": ["openid", "im"]
                          }]
                      })
    oidc_mock = OidcMock(
        requests_mock=requests_mock,
        expected_grant_type="authorization_code",
        expected_client_id=client_id,
        expected_fields={"scope": "im openid"},
        oidc_discovery_url=
        "https://fauth.test/.well-known/openid-configuration",
        scopes_supported=["openid", "im"],
    )

    # With all this set up, kick off the openid connect flow
    conn = Connection(API_URL)
    assert isinstance(conn.auth, NullAuth)
    conn.authenticate_OIDC(client_id=client_id,
                           webbrowser_open=oidc_mock.webbrowser_open)
    assert isinstance(conn.auth, BearerAuth)
    assert conn.auth.bearer == 'oidc/fauth/' + oidc_mock.state["access_token"]
예제 #30
0
파일: test_core.py 프로젝트: epopeia/lamper
def test_get_callapi_with_error(requests_mock):
    event = {
        'resource': '/example',
        'httpMethod': 'GET',
        'pathParameters': {
            'customer_id': None
        }
    }

    class ExamplePathParam(Schema):
        customer_id = fields.Str()
        name = fields.Str()

    class ExampleResponse(Schema):
        customer = fields.Str()
        name = fields.Str()

    with pytest.raises(exceptions.UnprocessableException):
        api_url = 'http://echo.jsontest.com/customer/'
        requests_mock.get(api_url, json={"customer": "1", "name": "EPOPEIA"})
        result = core.callapi(path_param_schema=ExamplePathParam,
                              response_schema=ExampleResponse,
                              http_method=core.HttpMethod.GET,
                              api_url=api_url,
                              event=event)
예제 #31
0
    def test_calling_tracker_when_status_query_indicates_started_updates_extraction_order_state(self, *args, **mocks):
        requests_mock = mocks['requests']
        requests_mock.get(
            'http://localhost:8901/api/conversion_result/53880847-faa9-43eb-ae84-dd92f3803a28/',
            text=self.fgdb_started_and_spatialite_queued_response
        )

        factory = APIRequestFactory()
        request = factory.get(
            reverse('job_progress:tracker', kwargs=dict(order_id=self.extraction_order.id)),
            data=dict(status='http://localhost:8901/api/conversion_result/53880847-faa9-43eb-ae84-dd92f3803a28/')
        )

        views.tracker(request, order_id=str(self.extraction_order.id))
        self.extraction_order.refresh_from_db()
        self.assertEqual(self.extraction_order.state, ExtractionOrderState.PROCESSING)
예제 #32
0
    def test_calling_tracker_when_status_query_indicates_started_informs_user(self, info_mock, *args, **mocks):
        requests_mock = mocks['requests']
        requests_mock.get(
            'http://localhost:8901/api/conversion_result/53880847-faa9-43eb-ae84-dd92f3803a28/',
            text=self.fgdb_started_and_spatialite_queued_response
        )

        factory = APIRequestFactory()
        request = factory.get(
            reverse('job_progress:tracker', kwargs=dict(order_id=self.extraction_order.id)),
            data=dict(status='http://localhost:8901/api/conversion_result/53880847-faa9-43eb-ae84-dd92f3803a28/')
        )

        views.tracker(request, order_id=str(self.extraction_order.id))
        info_mock.assert_called_with(
            'Extraction order {order_id} is now PROCESSING.'.format(
                order_id=self.extraction_order.id
            )
        )
예제 #33
0
    def test_calling_tracker_when_status_query_indicates_error_informs_user(
            self, emissary_info_mock, emissary_warn_mock, emissary_error_mock, *args, **mocks
    ):
        requests_mock = mocks['requests']
        requests_mock.get(
            'http://localhost:8901/api/conversion_result/53880847-faa9-43eb-ae84-dd92f3803a28/',
            text=json.dumps({
                "rq_job_id": "53880847-faa9-43eb-ae84-dd92f3803a28",
                "status": "error",
                "progress": "error",
                "gis_formats": [
                    {
                        "format": "fgdb",
                        "progress": "error",
                        "result_url": None
                    },
                    {
                        "format": "spatialite",
                        "progress": "error",
                        "result_url": None
                    }
                ]
            })
        )

        factory = APIRequestFactory()
        request = factory.get(
            reverse('job_progress:tracker', kwargs=dict(order_id=self.extraction_order.id)),
            data=dict(status='http://localhost:8901/api/conversion_result/53880847-faa9-43eb-ae84-dd92f3803a28/')
        )

        views.tracker(request, order_id=str(self.extraction_order.id))
        self.extraction_order.refresh_from_db()
        self.assertEqual(self.extraction_order.state, ExtractionOrderState.FAILED)
        emissary_info_mock.assert_not_called()
        emissary_warn_mock.assert_not_called()
        emissary_error_mock.assert_called_with('The extraction order "1" has failed. Please try again later.')