示例#1
0
def test_post_sets_body_of_request_as_json(
        requests_mock: RequestsMock) -> None:
    requests_mock.add(requests_mock.POST, API_BASE_URL + "endpoint",
                      '{ "success": true }')

    api = APIClient(mock.Mock(), HTTPClient(mock.Mock()), "123", "456")
    api.post("endpoint", {"key1": "value1", "key2": "value2"})

    assert len(requests_mock.calls) == 1
    assert requests_mock.calls[0].request.url == API_BASE_URL + "endpoint"

    body = json.loads(requests_mock.calls[0].request.body)

    assert body["key1"] == "value1"
    assert body["key2"] == "value2"
示例#2
0
def test_oauth2_authentication_success(services, token_cache_mock,
                                       responses: RequestsMock):
    from pyxelrest import pyxelrestgenerator

    responses.add(
        responses.GET,
        "http://localhost:8946/oauth2/authentication/success",
        json=[],
        match_querystring=True,
    )
    assert pyxelrestgenerator.authenticated_get_oauth2_authentication_success(
    ) == [[""]]
    assert (_get_request(
        responses, "http://localhost:8946/oauth2/authentication/success").
            headers["Authorization"] == "Bearer 2YotnFZFEjr1zCsicMWpAA")
示例#3
0
def test_with_invalid_grant_request_invalid_request_error_and_error_description(
    token_cache, responses: RequestsMock
):
    auth = requests_auth.OAuth2ResourceOwnerPasswordCredentials(
        "http://provide_access_token", username="******", password="******"
    )
    responses.add(
        responses.POST,
        "http://provide_access_token",
        json={"error": "invalid_request", "error_description": "desc of the error"},
        status=400,
    )
    with pytest.raises(requests_auth.InvalidGrantRequest) as exception_info:
        requests.get("http://authorized_only", auth=auth)
    assert str(exception_info.value) == "invalid_request: desc of the error"
示例#4
0
def test_http_client_logs_debug_message_about_response_when_unsuccessful(requests_mock: RequestsMock,
                                                                         method: str,
                                                                         use_request: bool) -> None:
    requests_mock.add(method.upper(), EXAMPLE_URL, "Example body", status=404)

    logger = mock.Mock()
    http_client = HTTPClient(logger)

    with pytest.raises(requests.HTTPError):
        if use_request:
            http_client.request(method, EXAMPLE_URL)
        else:
            getattr(http_client, method)(EXAMPLE_URL)

    assert logger.debug.call_count == 2
def test_without_logging_configuration_file(responses: RequestsMock, tmpdir):
    """
    This test case assert that pyxelrest can be loaded without logging configuration
    """
    responses.add(
        responses.GET,
        url="http://localhost:8943/",
        json={
            "swagger": "2.0",
            "paths": {
                "/date": {
                    "get": {
                        "operationId": "get_date",
                        "responses": {
                            "200": {
                                "description": "return value",
                                "schema": {
                                    "type": "array",
                                    "items": {
                                        "type": "string",
                                        "format": "date"
                                    },
                                },
                            }
                        },
                    }
                }
            },
        },
        match_querystring=True,
    )
    this_dir = os.path.abspath(os.path.dirname(__file__))
    pyxelrest.LOGGING_CONFIGURATION_FILE_PATH = os.path.join(
        this_dir, "non_existing_configuration.yml")
    loader.load(
        tmpdir,
        {
            "usual_parameters": {
                "open_api": {
                    "definition": "http://localhost:8943/"
                },
                "udf": {
                    "return_types": ["sync_auto_expand"],
                    "shift_result": False
                },
            }
        },
    )
def test_refresh_token_access_token_not_expired(
    token_cache, responses: RequestsMock, browser_mock: BrowserMock
):
    auth = requests_auth.OAuth2AuthorizationCode(
        "http://provide_code", "http://provide_access_token"
    )
    tab = browser_mock.add_response(
        opened_url="http://provide_code?response_type=code&state=163f0455b3e9cad3ca04254e5a0169553100d3aa0756c7964d897da316a695ffed5b4f46ef305094fd0a88cfe4b55ff257652015e4aa8f87b97513dba440f8de&redirect_uri=http%3A%2F%2Flocalhost%3A5000%2F",
        reply_url="http://localhost:5000#code=SplxlOBeZQQYbYS6WxSbIA&state=163f0455b3e9cad3ca04254e5a0169553100d3aa0756c7964d897da316a695ffed5b4f46ef305094fd0a88cfe4b55ff257652015e4aa8f87b97513dba440f8de",
    )
    responses.add(
        responses.POST,
        "http://provide_access_token",
        json={
            "access_token": "2YotnFZFEjr1zCsicMWpAA",
            "token_type": "example",
            "expires_in": 3600,
            "refresh_token": "tGzv3JOkF0XG5Qx2TlKWIA",
            "example_parameter": "example_value",
        },
        match=[
            urlencoded_params_matcher(
                {
                    "grant_type": "authorization_code",
                    "redirect_uri": "http://localhost:5000/",
                    "response_type": "code",
                    "code": "SplxlOBeZQQYbYS6WxSbIA",
                }
            )
        ],
    )
    assert (
        get_header(responses, auth).get("Authorization")
        == "Bearer 2YotnFZFEjr1zCsicMWpAA"
    )
    assert (
        get_request(responses, "http://provide_access_token/").body
        == "grant_type=authorization_code&redirect_uri=http%3A%2F%2Flocalhost%3A5000%2F&response_type=code&code=SplxlOBeZQQYbYS6WxSbIA"
    )
    tab.assert_success(
        "You are now authenticated on 163f0455b3e9cad3ca04254e5a0169553100d3aa0756c7964d897da316a695ffed5b4f46ef305094fd0a88cfe4b55ff257652015e4aa8f87b97513dba440f8de. You may close this tab."
    )

    # expect Bearer token to remain the same
    response = requests.get("http://authorized_only", auth=auth)
    assert (
        response.request.headers.get("Authorization") == "Bearer 2YotnFZFEjr1zCsicMWpAA"
    )
示例#7
0
def test_post_sets_body_of_request_as_form_data(
        requests_mock: RequestsMock) -> None:
    requests_mock.add(requests_mock.POST, API_BASE_URL + "endpoint",
                      '{ "success": true }')

    api = APIClient(mock.Mock(), HTTPClient(mock.Mock()), "123", "456")
    api.post("endpoint", {
        "key1": "value1",
        "key2": "value2"
    },
             data_as_json=False)

    assert len(requests_mock.calls) == 1
    assert requests_mock.calls[0].request.url == API_BASE_URL + "endpoint"

    assert requests_mock.calls[0].request.body == "key1=value1&key2=value2"
示例#8
0
def test_api_key_header_authentication_success(services,
                                               responses: RequestsMock):
    from pyxelrest import pyxelrestgenerator

    responses.add(
        responses.GET,
        "http://localhost:8946/api/key/header/authentication/success",
        json=[],
        match_querystring=True,
    )
    assert pyxelrestgenerator.authenticated_get_api_key_header_authentication_success(
    ) == [[""]]
    request = _get_request(
        responses,
        "http://localhost:8946/api/key/header/authentication/success")
    assert request.headers["X-API-HEADER-KEY"] == "my_provided_api_key"
示例#9
0
def test_pyxelrest_basic_authentication_success(services,
                                                responses: RequestsMock):
    from pyxelrest import pyxelrestgenerator

    responses.add(
        responses.GET,
        "http://localhost:8946/basic/authentication/success",
        json=[],
        match_querystring=True,
    )
    assert pyxelrestgenerator.pyxelrest_get_url(
        "http://localhost:8946/basic/authentication/success",
        auth=["basic"]) == [[""]]
    request = _get_request(
        responses, "http://localhost:8946/basic/authentication/success")
    assert request.headers["Authorization"] == "Basic dGVzdF91c2VyOnRlc3RfcHdk"
示例#10
0
def test_get_with_empty_string(responses: RequestsMock, values_false_service,
                               tmpdir, service_config):
    pyxelrestgenerator = loader.load(tmpdir, service_config)
    responses.add(
        responses.GET,
        url="http://localhost:8945/with/empty/string",
        json=[{
            "empty_string": ""
        }],
        match_querystring=True,
    )

    assert pyxelrestgenerator.values_false_get_with_empty_string() == [
        ["empty_string"],
        [""],
    ]
示例#11
0
def test_get_with_false_boolean(responses: RequestsMock, values_false_service,
                                tmpdir, service_config):
    pyxelrestgenerator = loader.load(tmpdir, service_config)
    responses.add(
        responses.GET,
        url="http://localhost:8945/with/false/boolean",
        json=[{
            "false_boolean": False
        }],
        match_querystring=True,
    )

    assert pyxelrestgenerator.values_false_get_with_false_boolean() == [
        ["false_boolean"],
        [False],
    ]
示例#12
0
def test_get_with_zero_float(responses: RequestsMock, values_false_service,
                             tmpdir, service_config):
    pyxelrestgenerator = loader.load(tmpdir, service_config)
    responses.add(
        responses.GET,
        url="http://localhost:8945/with/zero/float",
        json=[{
            "zero_float": 0.0
        }],
        match_querystring=True,
    )

    assert pyxelrestgenerator.values_false_get_with_zero_float() == [
        ["zero_float"],
        [0.0],
    ]
示例#13
0
def test_warn_if_docker_image_outdated_does_nothing_when_not_outdated(
        requests_mock: RequestsMock) -> None:
    requests_mock.add(
        requests_mock.GET,
        "https://registry.hub.docker.com/v2/repositories/quantconnect/lean/tags/latest",
        '{ "images": [ { "digest": "abc" } ] }')

    logger, storage, docker_manager, update_manager = create_objects()

    docker_manager.tag_installed.return_value = True
    docker_manager.get_digest.return_value = "abc"

    update_manager.warn_if_docker_image_outdated(
        DockerImage(name="quantconnect/lean", tag="latest"))

    logger.warn.assert_not_called()
示例#14
0
def test_pass_status_custom_health_check_with_default_extractor(
        mock_http_health_datetime, responses: RequestsMock):
    responses.add(url="http://test/status",
                  method=responses.GET,
                  status=200,
                  body="pong")
    assert healthpy.http.check("tests", "http://test/status") == (
        "pass",
        {
            "tests:health": {
                "componentType": "http://test/status",
                "observedValue": "pong",
                "status": "pass",
                "time": "2018-10-11T15:05:05.663979",
            }
        },
    )
def test_with_invalid_grant_request_invalid_scope_error(
        token_cache, responses: RequestsMock):
    auth = requests_auth.OAuth2ClientCredentials("http://provide_access_token",
                                                 client_id="test_user",
                                                 client_secret="test_pwd")
    responses.add(
        responses.POST,
        "http://provide_access_token",
        json={"error": "invalid_scope"},
        status=400,
    )
    with pytest.raises(requests_auth.InvalidGrantRequest) as exception_info:
        requests.get("http://authorized_only", auth=auth)
    assert (
        str(exception_info.value) ==
        "invalid_scope: The requested scope is invalid, unknown, malformed, or "
        "exceeds the scope granted by the resource owner.")
def test_with_invalid_grant_request_unsupported_grant_type_error(
        token_cache, responses: RequestsMock):
    auth = requests_auth.OAuth2ClientCredentials("http://provide_access_token",
                                                 client_id="test_user",
                                                 client_secret="test_pwd")
    responses.add(
        responses.POST,
        "http://provide_access_token",
        json={"error": "unsupported_grant_type"},
        status=400,
    )
    with pytest.raises(requests_auth.InvalidGrantRequest) as exception_info:
        requests.get("http://authorized_only", auth=auth)
    assert (
        str(exception_info.value) ==
        "unsupported_grant_type: The authorization grant type is not supported by the "
        "authorization server.")
示例#17
0
def setup_responses(responses: RequestsMock,
                    search_term: str,
                    body: str,
                    num_pages: int = 5):
    for page in range(1, num_pages + 1):
        responses.add(
            method=responses.GET,
            url=RECIPE_SEARCH_URI,
            match=[
                matchers.query_param_matcher({
                    "search": search_term,
                    "page": str(page)
                })
            ],
            headers={"Cookie": "euConsent=true"},
            body=body,
        )
示例#18
0
def test_basic_or_api_key_authentication_success(services,
                                                 responses: RequestsMock):
    from pyxelrest import pyxelrestgenerator

    responses.add(
        responses.GET,
        "http://localhost:8946/basic/or/api/key/authentication/success",
        json=[],
        match_querystring=True,
    )
    assert pyxelrestgenerator.authenticated_get_basic_or_api_key_authentication_success(
    ) == [[""]]
    request = _get_request(
        responses,
        "http://localhost:8946/basic/or/api/key/authentication/success")
    assert "X-API-HEADER-KEY" not in request.headers
    assert request.headers["Authorization"] == "Basic dGVzdF91c2VyOnRlc3RfcHdk"
示例#19
0
def test_warn_if_cli_outdated_only_checks_once_every_day(
        requests_mock: RequestsMock, hours: int,
        update_warning_expected: bool) -> None:
    if update_warning_expected:
        requests_mock.add(requests_mock.GET, "https://pypi.org/pypi/lean/json",
                          '{ "info": { "version": "0.0.2" } }')

    logger, storage, docker_manager, update_manager = create_objects()
    storage.set("last-update-check-cli", (datetime.now(tz=timezone.utc) -
                                          timedelta(hours=hours)).timestamp())

    update_manager.warn_if_cli_outdated()

    if update_warning_expected:
        logger.warn.assert_called()
    else:
        logger.warn.assert_not_called()
示例#20
0
def test_mixed_operation_id(responses: RequestsMock, operation_id_services,
                            tmpdir):
    pyxelrestgenerator = loader.load(
        tmpdir,
        {
            "operation_id_not_provided": {
                "open_api": {
                    "definition":
                    "http://localhost:8948/operation_id_not_provided"
                },
                "udf": {
                    "return_types": ["sync_auto_expand"],
                    "shift_result": False
                },
            },
            "operation_id_not_always_provided": {
                "open_api": {
                    "definition":
                    "http://localhost:8948/operation_id_not_always_provided"
                },
                "udf": {
                    "return_types": ["sync_auto_expand"],
                    "shift_result": False
                },
            },
        },
    )
    responses.add(
        responses.GET,
        url="http://localhost:8948/without_operationId",
        json=["first"],
        match_querystring=True,
    )

    assert pyxelrestgenerator.operation_id_not_always_provided_get_without_operationId(
    ) == [["first"]]

    responses.add(
        responses.GET,
        url="http://localhost:8948/with_operationId",
        json=["second"],
        match_querystring=True,
    )
    assert pyxelrestgenerator.operation_id_not_always_provided_duplicated_get_without_operationId(
    ) == [["second"]]
示例#21
0
def content_type_service(responses: RequestsMock):
    responses.add(
        responses.GET,
        url="http://localhost:8956/",
        json={
            "swagger": "2.0",
            "paths": {
                "/json": {
                    "get": {
                        "operationId": "get_json",
                        "responses": {200: {"description": "successful operation"}},
                        "produces": ["application/json"],
                    }
                }
            },
        },
        match_querystring=True,
    )
示例#22
0
def test_with_invalid_grant_request_unauthorized_client_error(
        token_cache, responses: RequestsMock):
    auth = requests_auth.OAuth2ResourceOwnerPasswordCredentials(
        "http://provide_access_token",
        username="******",
        password="******")
    responses.add(
        responses.POST,
        "http://provide_access_token",
        json={"error": "unauthorized_client"},
        status=400,
    )
    with pytest.raises(requests_auth.InvalidGrantRequest) as exception_info:
        requests.get("http://authorized_only", auth=auth)
    assert (
        str(exception_info.value) ==
        "unauthorized_client: The authenticated client is not authorized to use this "
        "authorization grant type.")
示例#23
0
def test_expires_in_sent_as_str(token_cache, responses: RequestsMock):
    auth = requests_auth.OktaClientCredentials("test_okta",
                                               client_id="test_user",
                                               client_secret="test_pwd")
    responses.add(
        responses.POST,
        "https://test_okta/oauth2/default/v1/token",
        json={
            "access_token": "2YotnFZFEjr1zCsicMWpAA",
            "token_type": "example",
            "expires_in": "3600",
            "refresh_token": "tGzv3JOkF0XG5Qx2TlKWIA",
            "example_parameter": "example_value",
        },
    )
    assert (get_header(
        responses,
        auth).get("Authorization") == "Bearer 2YotnFZFEjr1zCsicMWpAA")
示例#24
0
def test_validation_failure(responses: RequestsMock):
    responses.add(
        responses.GET,
        "https://test_id_provider",
        json={
            "keys": [{
                "kid":
                "SSQdhI1cKvhQEDSJxE2gGYs40Q0",
                "x5c": [
                    "MIIDBTCCAe2gAwIBAgIQdEMOjSqDVbdN3mzb2IumCzANBgkqhkiG9w0BAQsFADAtMSswKQYDVQQDEyJhY2NvdW50cy5hY2Nlc3Njb250cm9sLndpbmRvd3MubmV0MB4XDTE5MDYwNDAwMDAwMFoXDTIxMDYwNDAwMDAwMFowLTErMCkGA1UEAxMiYWNjb3VudHMuYWNjZXNzY29udHJvbC53aW5kb3dzLm5ldDCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAKEUUBvom99MdPXlrQ6S9MFmoQPoYI3NJVqEFOJcARY11dj3zyJogL8MTsTRt+DI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FzOGtcvlBpmP6jVHfEDoJiqFM4NFh6r4IlOs2U2-jUb_bR5xi2zg"
    with pytest.raises(jwt.InvalidTokenError) as exception_info:
        oauth2helper.validate(expired, "https://test_id_provider")
    assert str(exception_info.value) == "Signature verification failed"
示例#25
0
def test_custom_http_error_status_health_check(mock_http_health_datetime,
                                               responses: RequestsMock):
    responses.add(url="http://test/health", method=responses.GET, status=500)
    assert healthpy.requests.check(
        "tests",
        "http://test/health",
        error_status_extracting=lambda x: healthpy.warn_status,
    ) == (
        "warn",
        {
            "tests:health": {
                "componentType": "http://test/health",
                "output": "",
                "status": "warn",
                "time": "2018-10-11T15:05:05.663979",
            }
        },
    )
示例#26
0
def test_query_api_key_and_multiple_authentication_can_be_combined(
        token_cache, responses: RequestsMock):
    api_key_auth = requests_auth.QueryApiKey("my_provided_api_key")
    api_key_auth2 = requests_auth.QueryApiKey("my_provided_api_key2",
                                              query_parameter_name="api_key2")
    api_key_auth3 = requests_auth.HeaderApiKey("my_provided_api_key3",
                                               header_name="X-Api-Key3")

    # Mock a dummy response
    responses.add(responses.GET, "http://authorized_only")
    # Send a request to this dummy URL with authentication
    response = requests.get("http://authorized_only",
                            auth=api_key_auth +
                            (api_key_auth2 + api_key_auth3))
    # Return headers received on this dummy URL
    assert (response.request.path_url ==
            "/?api_key=my_provided_api_key&api_key2=my_provided_api_key2")
    assert response.request.headers.get("X-Api-Key3") == "my_provided_api_key3"
def test_okta_pkce_flow_token_is_expired_after_30_seconds_by_default(
        token_cache, responses: RequestsMock, monkeypatch,
        browser_mock: BrowserMock):
    monkeypatch.setattr(requests_auth.authentication.os, "urandom",
                        lambda x: b"1" * 63)
    auth = requests_auth.OktaAuthorizationCodePKCE(
        "testserver.okta-emea.com", "54239d18-c68c-4c47-8bdd-ce71ea1d50cd")
    tab = browser_mock.add_response(
        opened_url=
        "https://testserver.okta-emea.com/oauth2/default/v1/authorize?client_id=54239d18-c68c-4c47-8bdd-ce71ea1d50cd&scope=openid&response_type=code&state=5264d11c8b268ccf911ce564ca42fd75cea68c4a3c1ec3ac1ab20243891ab7cd5250ad4c2d002017c6e8ac2ba34954293baa5e0e4fd00bb9ffd4a39c45f1960b&redirect_uri=http%3A%2F%2Flocalhost%3A5000%2F&code_challenge=5C_ph_KZ3DstYUc965SiqmKAA-ShvKF4Ut7daKd3fjc&code_challenge_method=S256",
        reply_url=
        "http://localhost:5000#code=SplxlOBeZQQYbYS6WxSbIA&state=5264d11c8b268ccf911ce564ca42fd75cea68c4a3c1ec3ac1ab20243891ab7cd5250ad4c2d002017c6e8ac2ba34954293baa5e0e4fd00bb9ffd4a39c45f1960b",
    )
    # Add a token that expires in 29 seconds, so should be considered as expired when issuing the request
    token_cache._add_token(
        key=
        "5264d11c8b268ccf911ce564ca42fd75cea68c4a3c1ec3ac1ab20243891ab7cd5250ad4c2d002017c6e8ac2ba34954293baa5e0e4fd00bb9ffd4a39c45f1960b",
        token="2YotnFZFEjr1zCsicMWpAA",
        expiry=requests_auth.oauth2_tokens._to_expiry(expires_in=29),
    )
    # Meaning a new one will be requested
    responses.add(
        responses.POST,
        "https://testserver.okta-emea.com/oauth2/default/v1/token",
        json={
            "access_token": "2YotnFZFEjr1zCsicMWpAA",
            "token_type": "example",
            "expires_in": 3600,
            "refresh_token": "tGzv3JOkF0XG5Qx2TlKWIA",
            "example_parameter": "example_value",
        },
    )
    assert (get_header(
        responses,
        auth).get("Authorization") == "Bearer 2YotnFZFEjr1zCsicMWpAA")
    assert (
        get_request(
            responses,
            "https://testserver.okta-emea.com/oauth2/default/v1/token").body ==
        "code_verifier=MTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTEx&grant_type=authorization_code&redirect_uri=http%3A%2F%2Flocalhost%3A5000%2F&client_id=54239d18-c68c-4c47-8bdd-ce71ea1d50cd&scope=openid&response_type=code&code=SplxlOBeZQQYbYS6WxSbIA"
    )
    tab.assert_success(
        "You are now authenticated on 5264d11c8b268ccf911ce564ca42fd75cea68c4a3c1ec3ac1ab20243891ab7cd5250ad4c2d002017c6e8ac2ba34954293baa5e0e4fd00bb9ffd4a39c45f1960b. You may close this tab."
    )
示例#28
0
def test_get_header_advanced_configuration(responses: RequestsMock,
                                           header_parameter_service,
                                           monkeypatch, tmpdir):
    import pyxelrest.session

    pyxelrest.session.sessions.clear()
    monkeypatch.setattr(pyxelrest.session, "datetime", DateTimeModuleMock)
    pyxelrestgenerator = loader.load(
        tmpdir,
        {
            "header_advanced_configuration": {
                "open_api": {
                    "definition": "http://localhost:8951/"
                },
                "udf": {
                    "return_types": ["vba_compatible"],
                    "shift_result": False
                },
                "headers": {
                    "X-PXL-CUSTOM": "MyCustomValue",
                    "X-PXL-OTHER": "MyOtherValue",
                    "X-PXL-ENVVAR": "%USERNAME%",
                },
            }
        },
    )
    responses.add(
        responses.GET,
        url="http://localhost:8951/header",
        json={},
        match_querystring=True,
    )

    assert pyxelrestgenerator.header_advanced_configuration_get_header(
        "sent header") == [[""]]
    headers = _get_request(responses, "http://localhost:8951/header").headers

    assert headers["X-Pxl-Custom"] == "MyCustomValue"
    assert headers["X-Pxl-Other"] == "MyOtherValue"
    assert headers["X-Pxl-Envvar"] == os.environ["USERNAME"]
    assert headers["X-Pxl-Request"]
    assert headers["User-Agent"] == "PyxelRest v1.0.0a1"
    assert headers["X-Pxl-Cell"] == "Python"
    assert headers["X-Pxl-Session"] == "2018-10-11T15:05:05.663979"
示例#29
0
def test_json_content_type(responses: RequestsMock, content_type_service, tmpdir):
    pyxelrestgenerator = loader.load(
        tmpdir,
        {
            "content_type": {
                "open_api": {"definition": "http://localhost:8956/"},
                "udf": {"return_types": ["sync_auto_expand"], "shift_result": False},
            }
        },
    )
    responses.add(
        responses.GET, url="http://localhost:8956/json", json={}, match_querystring=True
    )

    assert pyxelrestgenerator.content_type_get_json() == [[""]]
    assert (
        _get_request(responses, "http://localhost:8956/json").headers["Accept"]
        == "application/json"
    )
def test_get_matrix_servers(requests_responses: responses.RequestsMock):
    server_list_content = {
        "active_servers": ["http://server1", "http://server2"],
        "all_servers": ["http://server3", "http://server4"],
    }
    requests_responses.add(responses.GET, "http://server-list",
                           json.dumps(server_list_content))

    active_servers_default = get_matrix_servers("http://server-list")
    active_servers_explicit = get_matrix_servers(
        "http://server-list", server_list_type=ServerListType.ACTIVE_SERVERS)

    assert (active_servers_default == active_servers_explicit ==
            server_list_content["active_servers"])

    all_servers = get_matrix_servers(
        "http://server-list", server_list_type=ServerListType.ALL_SERVERS)

    assert all_servers == server_list_content["all_servers"]