def test_offline_hello_api_call(self, monkeypatch):
        class MockSession:
            def get(self, *args, **kwargs):
                r = Response()
                r.status_code = 200
                r._content = json.dumps({
                    'helloResponse': {
                        'response': 'Hello World!'
                    }
                }).encode("utf-8")
                return r

        monkeypatch.setattr(requests, "Session", MockSession)

        cisco_hello_api = CiscoHelloApi()
        monkeypatch.setattr(
            cisco_hello_api,
            "create_temporary_access_token",
            lambda force_new_token=True: mock_access_token_generation())

        with pytest.raises(CiscoApiCallFailed) as exinfo:
            cisco_hello_api.hello_api_call()
        assert exinfo.match("Client not ready")

        cisco_hello_api.load_client_credentials()
        cisco_hello_api.create_temporary_access_token()

        json_result = cisco_hello_api.hello_api_call()
        assert json_result == {'helloResponse': {'response': 'Hello World!'}}
    def test_automatic_load_of_the_client_credentials(self):
        cisco_hello_api = CiscoHelloApi()
        assert cisco_hello_api.is_ready_for_use() is False

        assert cisco_hello_api.client_id is None
        assert cisco_hello_api.client_secret is None

        cisco_hello_api.get_client_credentials()

        assert cisco_hello_api.client_id is not None
        assert cisco_hello_api.client_secret is not None
    def test_automatic_load_of_the_client_credentials(self):
        cisco_hello_api = CiscoHelloApi()
        assert cisco_hello_api.is_ready_for_use() is False

        assert cisco_hello_api.client_id is None
        assert cisco_hello_api.client_secret is None

        cisco_hello_api.get_client_credentials()

        assert cisco_hello_api.client_id is not None
        assert cisco_hello_api.client_secret is not None
    def test_endpoint_unreachable(self, monkeypatch):
        def get_invalid_authentication_response():
            raise Exception()

        monkeypatch.setattr(requests, "post", lambda x, params: get_invalid_authentication_response())

        cisco_hello_api = CiscoHelloApi()
        cisco_hello_api.load_client_credentials()

        with pytest.raises(ConnectionFailedException) as exinfo:
            cisco_hello_api.create_temporary_access_token()
        assert exinfo.match("cannot contact authentication server")
    def test_read_from_cached_token(self):
        cisco_hello_api_one = CiscoHelloApi()
        cisco_hello_api_one.load_client_credentials()
        cisco_hello_api_one.create_temporary_access_token()

        assert cache.get(CiscoHelloApi.AUTH_TOKEN_CACHE_KEY, None) is not None

        cisco_hello_api_two = CiscoHelloApi()
        cisco_hello_api_two.load_client_credentials()
        cisco_hello_api_two.create_temporary_access_token()  # should load from cache

        assert cisco_hello_api_one.http_auth_header == cisco_hello_api_two.http_auth_header
    def test_invalid_login(self, monkeypatch):
        def get_invalid_authentication_response():
            r = Response()
            r.status_code = 401
            return r

        monkeypatch.setattr(requests, "post", lambda x, params: get_invalid_authentication_response())

        cisco_hello_api = CiscoHelloApi()
        cisco_hello_api.load_client_credentials()

        with pytest.raises(InvalidClientCredentialsException) as exinfo:
            cisco_hello_api.create_temporary_access_token()
        assert exinfo.match("Invalid client or client credentials")
    def test_gateway_timeout(self, monkeypatch):
        def get_invalid_authentication_response():
            r = Response()
            r.status_code = 200
            r._content = "<h1>Gateway Timeout</h1>".encode("utf-8")
            return r

        monkeypatch.setattr(requests, "post", lambda x, params: get_invalid_authentication_response())

        cisco_hello_api = CiscoHelloApi()
        cisco_hello_api.load_client_credentials()

        with pytest.raises(AuthorizationFailedException) as exinfo:
            cisco_hello_api.create_temporary_access_token()
        assert exinfo.match("API endpoint temporary unreachable")
    def test_api_500(self, monkeypatch):
        def get_invalid_authentication_response():
            r = Response()
            r.status_code = 500
            r._content = "".encode("utf-8")
            return r

        monkeypatch.setattr(requests, "post", lambda x, params: get_invalid_authentication_response())

        cisco_hello_api = CiscoHelloApi()
        cisco_hello_api.load_client_credentials()

        with pytest.raises(CiscoApiCallFailed) as exinfo:
            cisco_hello_api.create_temporary_access_token()
        assert exinfo.match("API response invalid, result was HTTP 500")
    def test_developer_inactive(self, monkeypatch):
        def get_invalid_authentication_response():
            r = Response()
            r.status_code = 200
            r._content = "<h1>Developer Inactive</h1>".encode("utf-8")
            return r

        monkeypatch.setattr(requests, "post", lambda x, params: get_invalid_authentication_response())

        cisco_hello_api = CiscoHelloApi()
        cisco_hello_api.load_client_credentials()

        with pytest.raises(AuthorizationFailedException) as exinfo:
            cisco_hello_api.create_temporary_access_token()
        assert exinfo.match("Insufficient Permissions on API endpoint")
    def test_invalid_json(self, monkeypatch):
        def get_invalid_authentication_response():
            r = Response()
            r.status_code = 200
            r._content = "My invalid JSON string".encode("utf-8")
            return r

        monkeypatch.setattr(requests, "post", lambda x, params: get_invalid_authentication_response())

        cisco_hello_api = CiscoHelloApi()
        cisco_hello_api.load_client_credentials()

        with pytest.raises(CiscoApiCallFailed) as exinfo:
            cisco_hello_api.create_temporary_access_token()
        assert exinfo.match("unexpected content from API endpoint")
    def test_automatic_renew_of_expired_token(self):
        cisco_hello_api = CiscoHelloApi()
        cisco_hello_api.load_client_credentials()
        cisco_hello_api.create_temporary_access_token()

        # test automatic recreation of the http_auth_header if the cached token was expired
        cisco_hello_api.token_expire_datetime = datetime.datetime.now()
        assert cisco_hello_api.is_ready_for_use() is True
        assert cisco_hello_api.http_auth_header is not None
Example #12
0
    def test_online_hello_api_call(self):
        cisco_hello_api = CiscoHelloApi()
        cisco_hello_api.load_client_credentials()
        cisco_hello_api.create_temporary_access_token()

        json_result = cisco_hello_api.hello_api_call()

        assert isinstance(json_result, dict)
    def test_online_hello_api_call(self):
        cisco_hello_api = CiscoHelloApi()
        cisco_hello_api.load_client_credentials()
        cisco_hello_api.create_temporary_access_token()

        json_result = cisco_hello_api.hello_api_call()

        assert json_result == {'helloResponse': {'response': 'Hello World!'}}
    def test_automatic_renew_of_expired_token(self):
        cisco_hello_api = CiscoHelloApi()
        cisco_hello_api.load_client_credentials()
        cisco_hello_api.create_temporary_access_token()

        # test automatic recreation of the http_auth_header if the cached token was expired
        cisco_hello_api.token_expire_datetime = datetime.datetime.now()
        assert cisco_hello_api.is_ready_for_use() is True
        assert cisco_hello_api.http_auth_header is not None
Example #15
0
def check_cisco_hello_api_access(client_id,
                                 client_secret,
                                 drop_credentials=True):
    """
    test the Cisco Hello API access
    """
    try:
        base_api = CiscoHelloApi()
        base_api.load_client_credentials()

        if drop_credentials:
            base_api.drop_cached_token()

        base_api.client_id = client_id
        base_api.client_secret = client_secret

        base_api.hello_api_call()

        return True

    except Exception:
        return False
Example #16
0
    def test_offline_hello_api_call_with_connection_issue(self, monkeypatch):
        class MockSession:
            def get(self, *args, **kwargs):
                raise Exception()

        monkeypatch.setattr(requests, "Session", MockSession)

        cisco_hello_api = CiscoHelloApi()
        monkeypatch.setattr(cisco_hello_api, "create_temporary_access_token", lambda force_new_token=True: mock_access_token_generation())
        cisco_hello_api.load_client_credentials()
        cisco_hello_api.create_temporary_access_token()

        with pytest.raises(ConnectionFailedException) as exinfo:
            cisco_hello_api.hello_api_call()
        assert exinfo.match("cannot contact API endpoint at")
    def test_online_hello_api_call(self):
        cisco_hello_api = CiscoHelloApi()
        cisco_hello_api.load_client_credentials()
        cisco_hello_api.create_temporary_access_token()

        json_result = cisco_hello_api.hello_api_call()

        assert json_result == {'response': 'Hello World'}
Example #18
0
def test_cisco_hello_api_access(client_id, client_secret, drop_credentials=True):
    """
    test the Cisco Hello API access
    """
    try:
        base_api = CiscoHelloApi()
        base_api.load_client_credentials()

        if drop_credentials:
            base_api.drop_cached_token()

        base_api.client_id = client_id
        base_api.client_secret = client_secret

        base_api.hello_api_call()

        return True

    except:
        return False
Example #19
0
def check_cisco_hello_api_access(client_id,
                                 client_secret,
                                 drop_credentials=True):
    """
    test the Cisco Hello API access
    """
    try:
        base_api = CiscoHelloApi()
        base_api.load_client_credentials()

        if drop_credentials:
            base_api.drop_cached_token()

        base_api.client_id = client_id
        base_api.client_secret = client_secret

        base_api.hello_api_call()

        return True

    except Exception as ex:
        logging.error("Cisco Hello API test access failed (%s)" % ex,
                      exc_info=True)
        return False
    def test_offline_hello_api_call_with_connection_issue(self, monkeypatch):
        def get_endpoint_result():
            raise Exception()

        monkeypatch.setattr(requests, "get", lambda x, headers: get_endpoint_result())

        cisco_hello_api = CiscoHelloApi()
        monkeypatch.setattr(cisco_hello_api, "create_temporary_access_token", lambda force_new_token=True: mock_access_token_generation())
        cisco_hello_api.load_client_credentials()
        cisco_hello_api.create_temporary_access_token()

        with pytest.raises(ConnectionFailedException) as exinfo:
            cisco_hello_api.hello_api_call()
        assert exinfo.match("cannot contact API endpoint at")
Example #21
0
    def test_offline_hello_api_call_with_malformed_result(self, monkeypatch):
        class MockSession:
            def get(self, *args, **kwargs):
                r = Response()
                r.status_code = 200
                r._content = "My invalid JSON string".encode("utf-8")
                return r

        monkeypatch.setattr(requests, "Session", MockSession)

        cisco_hello_api = CiscoHelloApi()
        monkeypatch.setattr(cisco_hello_api, "create_temporary_access_token", lambda force_new_token=True: mock_access_token_generation())
        cisco_hello_api.load_client_credentials()
        cisco_hello_api.create_temporary_access_token()

        with pytest.raises(CiscoApiCallFailed) as exinfo:
            cisco_hello_api.hello_api_call()
        assert exinfo.match("unexpected content from API endpoint")
Example #22
0
    def test_endpoint_unreachable(self, monkeypatch):
        def get_invalid_authentication_response():
            raise Exception()

        monkeypatch.setattr(requests, "post", lambda x, params: get_invalid_authentication_response())

        cisco_hello_api = CiscoHelloApi()
        cisco_hello_api.load_client_credentials()

        with pytest.raises(ConnectionFailedException) as exinfo:
            cisco_hello_api.create_temporary_access_token()
        assert exinfo.match("cannot contact authentication server")
    def test_offline_hello_api_call_with_malformed_result(self, monkeypatch):
        def get_endpoint_result():
            r = Response()
            r.status_code = 200
            r._content = "My invalid JSON string".encode("utf-8")
            return r

        monkeypatch.setattr(requests, "get", lambda x, headers: get_endpoint_result())

        cisco_hello_api = CiscoHelloApi()
        monkeypatch.setattr(cisco_hello_api, "create_temporary_access_token", lambda force_new_token=True: mock_access_token_generation())
        cisco_hello_api.load_client_credentials()
        cisco_hello_api.create_temporary_access_token()

        with pytest.raises(CiscoApiCallFailed) as exinfo:
            cisco_hello_api.hello_api_call()
        assert exinfo.match("unexpected content from API endpoint")
    def test_offline_hello_api_call(self, monkeypatch):
        def get_endpoint_result():
            r = Response()
            r.status_code = 200
            r._content = json.dumps({'response': 'Hello World'}).encode("utf-8")
            return r

        monkeypatch.setattr(requests, "get", lambda x, headers: get_endpoint_result())

        cisco_hello_api = CiscoHelloApi()
        monkeypatch.setattr(cisco_hello_api, "create_temporary_access_token", lambda force_new_token=True: mock_access_token_generation())

        with pytest.raises(CiscoApiCallFailed) as exinfo:
            cisco_hello_api.hello_api_call()
        assert exinfo.match("Client not ready")

        cisco_hello_api.load_client_credentials()
        cisco_hello_api.create_temporary_access_token()

        json_result = cisco_hello_api.hello_api_call()
        assert json_result == {'response': 'Hello World'}
Example #25
0
    def test_invalid_login(self, monkeypatch):
        def get_invalid_authentication_response():
            r = Response()
            r.status_code = 401
            return r

        monkeypatch.setattr(requests, "post", lambda x, params, proxies=None: get_invalid_authentication_response())

        cisco_hello_api = CiscoHelloApi()
        cisco_hello_api.load_client_credentials()

        with pytest.raises(InvalidClientCredentialsException) as exinfo:
            cisco_hello_api.create_temporary_access_token()
        assert exinfo.match("Invalid client or client credentials")
Example #26
0
    def test_developer_inactive(self, monkeypatch):
        def get_invalid_authentication_response():
            r = Response()
            r.status_code = 200
            r._content = "<h1>Developer Inactive</h1>".encode("utf-8")
            return r

        monkeypatch.setattr(requests, "post", lambda x, params, proxies=None: get_invalid_authentication_response())

        cisco_hello_api = CiscoHelloApi()
        cisco_hello_api.load_client_credentials()

        with pytest.raises(AuthorizationFailedException) as exinfo:
            cisco_hello_api.create_temporary_access_token()
        assert exinfo.match("Insufficient Permissions on API endpoint")
Example #27
0
    def test_api_500(self, monkeypatch):
        def get_invalid_authentication_response():
            r = Response()
            r.status_code = 500
            r._content = "".encode("utf-8")
            return r

        monkeypatch.setattr(requests, "post", lambda x, params, proxies=None: get_invalid_authentication_response())

        cisco_hello_api = CiscoHelloApi()
        cisco_hello_api.load_client_credentials()

        with pytest.raises(CiscoApiCallFailed) as exinfo:
            cisco_hello_api.create_temporary_access_token()
        assert exinfo.match("API response invalid, result was HTTP 500")
Example #28
0
    def test_invalid_json(self, monkeypatch):
        def get_invalid_authentication_response():
            r = Response()
            r.status_code = 200
            r._content = "My invalid JSON string".encode("utf-8")
            return r

        monkeypatch.setattr(requests, "post", lambda x, params, proxies=None: get_invalid_authentication_response())

        cisco_hello_api = CiscoHelloApi()
        cisco_hello_api.load_client_credentials()

        with pytest.raises(CiscoApiCallFailed) as exinfo:
            cisco_hello_api.create_temporary_access_token()
        assert exinfo.match("unexpected content from API endpoint")
Example #29
0
    def test_gateway_timeout(self, monkeypatch):
        def get_invalid_authentication_response():
            r = Response()
            r.status_code = 200
            r._content = "<h1>Gateway Timeout</h1>".encode("utf-8")
            return r

        monkeypatch.setattr(requests, "post", lambda x, params, proxies=None: get_invalid_authentication_response())

        cisco_hello_api = CiscoHelloApi()
        cisco_hello_api.load_client_credentials()

        with pytest.raises(AuthorizationFailedException) as exinfo:
            cisco_hello_api.create_temporary_access_token()
        assert exinfo.match("API endpoint temporary unreachable")
    def test_authorization_error(self, monkeypatch):
        def get_invalid_authentication_response():
            r = Response()
            r.status_code = 200
            r._content = "<h1>Not Authorized</h1>".encode("utf-8")
            return r

        monkeypatch.setattr(
            requests, "post",
            lambda x, params: get_invalid_authentication_response())

        cisco_hello_api = CiscoHelloApi()
        cisco_hello_api.load_client_credentials()

        with pytest.raises(AuthorizationFailedException) as exinfo:
            cisco_hello_api.create_temporary_access_token()
        assert exinfo.match("User authorization failed")
    def test_base_functionality(self):
        cisco_hello_api = CiscoHelloApi()
        assert cisco_hello_api.is_ready_for_use() is False

        assert cisco_hello_api.client_id is None
        assert cisco_hello_api.client_secret is None

        with pytest.raises(CredentialsNotFoundException):
            cisco_hello_api.create_temporary_access_token()

        cisco_hello_api.load_client_credentials()
        assert cisco_hello_api.client_id != "dummy_id", "Should contain valid test credentials"
        assert cisco_hello_api.client_id != "dummy_secret", "Should contain valid test credentials"

        with open(BaseCiscoApiConsoleSettings.CREDENTIALS_FILE) as f:
            jdata = json.loads(f.read())
        assert jdata == cisco_hello_api.get_client_credentials()

        # create a temporary access token
        cisco_hello_api.create_temporary_access_token()
        assert cisco_hello_api.current_access_token is not None
        assert cache.get(CiscoHelloApi.AUTH_TOKEN_CACHE_KEY,
                         None) is not None, "Cached value should be created"

        # test that the class is now ready to use
        assert cisco_hello_api.is_ready_for_use() is True

        # test automatic recreation of the http_auth_header if no cached temp token is available
        cisco_hello_api.http_auth_header = None
        cache.delete(CiscoHelloApi.AUTH_TOKEN_CACHE_KEY)
        assert cisco_hello_api.is_ready_for_use() is True
        assert cisco_hello_api.http_auth_header is not None

        # try to recreate it
        token_before = cisco_hello_api.current_access_token
        cisco_hello_api.create_temporary_access_token()
        assert cisco_hello_api.current_access_token == token_before

        # force the recreation of the token
        cisco_hello_api.current_access_token = {
            "token_type": "my dummy value",
            "access_token": "my dummy value"
        }  # manually overwrite it to see that something happens
        cisco_hello_api.create_temporary_access_token(force_new_token=True)
        assert cisco_hello_api.current_access_token != "my dummy value"

        # cleanup
        cisco_hello_api.drop_cached_token()
        assert cisco_hello_api.current_access_token is None
        assert cache.get(CiscoHelloApi.AUTH_TOKEN_CACHE_KEY,
                         None) is None, "Cached value should be removed"

        # try to drop it again (nothing should happen)
        cisco_hello_api.drop_cached_token()
    def test_base_functionality(self):
        cisco_hello_api = CiscoHelloApi()
        assert cisco_hello_api.is_ready_for_use() is False

        assert cisco_hello_api.client_id is None
        assert cisco_hello_api.client_secret is None

        with pytest.raises(CredentialsNotFoundException):
            cisco_hello_api.create_temporary_access_token()

        cisco_hello_api.load_client_credentials()
        assert cisco_hello_api.client_id != "dummy_id", "Should contain valid test credentials"
        assert cisco_hello_api.client_id != "dummy_secret", "Should contain valid test credentials"

        with open(BaseCiscoApiConsoleSettings.CREDENTIALS_FILE) as f:
            jdata = json.loads(f.read())
        assert jdata == cisco_hello_api.get_client_credentials()

        # create a temporary access token
        cisco_hello_api.create_temporary_access_token()
        assert cisco_hello_api.current_access_token is not None
        assert cache.get(CiscoHelloApi.AUTH_TOKEN_CACHE_KEY, None) is not None, "Cached value should be created"

        # test that the class is now ready to use
        assert cisco_hello_api.is_ready_for_use() is True

        # test automatic recreation of the http_auth_header if no cached temp token is available
        cisco_hello_api.http_auth_header = None
        cache.delete(CiscoHelloApi.AUTH_TOKEN_CACHE_KEY)
        assert cisco_hello_api.is_ready_for_use() is True
        assert cisco_hello_api.http_auth_header is not None

        # try to recreate it
        token_before = cisco_hello_api.current_access_token
        cisco_hello_api.create_temporary_access_token()
        assert cisco_hello_api.current_access_token == token_before

        # force the recreation of the token
        cisco_hello_api.current_access_token = {
            "token_type": "my dummy value",
            "access_token": "my dummy value"
        }  # manually overwrite it to see that something happens
        cisco_hello_api.create_temporary_access_token(force_new_token=True)
        assert cisco_hello_api.current_access_token != "my dummy value"

        # cleanup
        cisco_hello_api.drop_cached_token()
        assert cisco_hello_api.current_access_token is None
        assert cache.get(CiscoHelloApi.AUTH_TOKEN_CACHE_KEY, None) is None, "Cached value should be removed"

        # try to drop it again (nothing should happen)
        cisco_hello_api.drop_cached_token()
    def test_read_from_cached_token(self):
        cisco_hello_api_one = CiscoHelloApi()
        cisco_hello_api_one.load_client_credentials()
        cisco_hello_api_one.create_temporary_access_token()

        assert cache.get(CiscoHelloApi.AUTH_TOKEN_CACHE_KEY, None) is not None

        cisco_hello_api_two = CiscoHelloApi()
        cisco_hello_api_two.load_client_credentials()
        cisco_hello_api_two.create_temporary_access_token(
        )  # should load from cache

        assert cisco_hello_api_one.http_auth_header == cisco_hello_api_two.http_auth_header